forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

edith.rs8564 lines, 385.6 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 semitones, `-12` to `12`, written for each clip that is not at `0`,
252//! after the lanes it names (as `clippan` is). **Version 55** is the first dialect
253//! with one, whole semitones only. **Version 58** allows a fraction (`0.37`), which a
254//! pre-v58 reader would refuse; a project whose shifts are all whole keeps the header
255//! it needed before. A project with none is the bytes a v54 one was bar the version line.
256//!
257//! The `resolution` line is the **project's** picture size, which is a
258//! different thing from any source's: media of other sizes are placed on it.
259//! It belongs once, beside the playhead, and a file without one (every dialect
260//! before v7) means "source 0's own picture", which is what such a project
261//! always was.
262//!
263//! A source line is `source <audio stream> <path>`: which of the file's audio
264//! tracks that source plays, in the file order
265//! [`crate::AudioSession::probe_streams`] numbers, and then the path -- the
266//! stream first because a path runs to the end of the line (it may hold
267//! spaces) and an optional *trailing* field could not be told from one.
268//!
269//! An eq line is `eq <band>...`, one band per field, each
270//! `<frequency>:<gain dB>:<Q>:<shape>` with the shape spelled `ls`, `pk`, `hs`,
271//! `lc` (low cut) or `hc` (high cut) ([`crate::eq::BandKind`]). Like a source it is named by *position* --
272//! the first eq line is eq 0 -- and a clip names one, so twenty clips sharing a
273//! curve write it once. `eq` on its own is the empty cascade, which is a
274//! setting like any other. The numbers are printed to round trip bit-exactly;
275//! anything not finite is refused, here and at [`crate::Project::set_eq`].
276//!
277//! A colour line is `color <brightness>:<contrast>:<saturation>:<tint>`
278//! ([`crate::color::ColorParams`]), named by position exactly as an eq line is
279//! -- the first colour line is color 0 -- printed and refused by the same rules.
280//!
281//! A colour line's look ([`crate::color::Look`]) rides on three line types
282//! written at the end of the file and naming the colour line by position:
283//! `wheels <color> <lift> <gamma> <gain>` (each `<master>:<red>:<green>:<blue>`,
284//! -1..1), `curve <color> <channel> <x>:<y>,...` (channel `master`, `red`, `green`
285//! or `blue`, up to 16 points in 0..1 with rising inputs) and `lut <color> <mix>
286//! <path>` (mix 0..1, the path written as a source's is). **Version 43** is the
287//! first dialect with them; a project whose grades have no look is written under
288//! the header it needed before. A LUT file that is missing or malformed does not
289//! stop the load: the clip plays without it and the project names it
290//! ([`crate::Project::lut_problems`]).
291//!
292//! A transform line is `transform <pos_x>:<pos_y>:<scale>:<rotate>:<crop_l>:
293//! <crop_r>:<crop_t>:<crop_b>` ([`crate::transform::TransformParams`]), named by
294//! position exactly as an eq or a colour line is -- the first transform line is
295//! transform 0 -- printed and refused by the same rules: how a clip's picture
296//! sits, is sized, is turned and is trimmed on the canvas, on top of whatever
297//! its fit policy already placed.
298//!
299//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
300//! <color> <fit> <speed> <fade_in> <fade_out> <transition_out> <transform> <visualizer> <viz_paint>`:
301//! which lane the clip is on -- its kind and its 1-based number
302//! among the lanes of that kind, the [`crate::project::Lane::label`] a header
303//! column shows -- then where the clip sits on the timeline, the half-open
304//! source range it plays, the file it plays from, its group id, the eq line it
305//! plays through, the colour line it is graded by (`-` for none of those three)
306//! and how it meets a project canvas of another shape, spelled `fit`, `fill`,
307//! `stretch` or `center` ([`crate::scale::FitPolicy`]), how fast it plays,
308//! in thousandths of real time ([`crate::project::Speed`], `1000` for a clip
309//! nobody has speeded), and finally its ramp up from silence and ramp down to
310//! it, in timeline frames ([`crate::project::Clip::fade_in`],
311//! [`crate::project::Clip::fade_out`], `0 0` for a clip nobody has faded), its
312//! cross-dissolve into whatever abuts its end
313//! ([`crate::project::Clip::transition_out`], `0` for a hard cut), and last of
314//! all the transform line it is placed, sized, turned and cropped by, on top
315//! of everything its fit policy already did (`-` for a clip left at its fit
316//! policy's own spot, [`crate::project::Clip::transform`]), a visualizer
317//! flags byte (`0` for an ordinary picture, bit 0 for a waveform of the
318//! source's sound, the rest outline/smooth/fast/tint) and that waveform's
319//! packed look ([`crate::project::Clip::viz_paint`]): hue, sat, strands and
320//! glow in the low four bytes, then the strand colour's own hue and sat,
321//! with the top bit set once a clip has chosen one.
322//! Timeline placement is
323//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing
324//! to write for one, and nothing that can disagree about its length. The `<in>`
325//! and `<out>` are *source* frames whatever the speed says: how long the clip is
326//! on the timeline is that range divided by the rate, and is written nowhere.
327//!
328//! A lane is declared by the clips on it, in the order the lanes are displayed
329//! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
330//! is the only way an empty lane could still be there on the way back. A lane
331//! number may not skip one of its kind.
332//!
333//! A subtitle lane is a lane like the other two and is written in its place
334//! among them, `sub` for its kind: `sub <lane> <start> <frames> <track>
335//! <in> <out>` ([`crate::project::SubClip`]) -- where the caption sits on the
336//! timeline and how many frames it covers, then which `subtitle` line's words
337//! it shows (by position, the first one is track 0) and the half-open window of
338//! that track it shows, in *microseconds*, which is the clock the cues
339//! themselves are timed in. Two clocks on one line because a subtitle has two:
340//! a placement is in timeline frames like everything else, and a window is in
341//! the file's own time whatever the timeline runs at. A lane holding nothing
342//! has the bare `sub <lane>` line for the reason a video one does, and the
343//! track a caption names has to be one the file declared -- a `sub` line naming
344//! track 3 of a two-track palette is refused here, as a clip naming a source
345//! that is not there is.
346//!
347//! **Version 23** was this without the `flags` lines: such a project has no
348//! lane hidden, muted or locked, which is what every lane of every dialect
349//! before it is.
350//! **Version 22** was this with a 32-bit packed look: such a project's clips
351//! chose no strand colour, which is what the top bit still clear means, and
352//! their value is the low half of the one v23 writes.
353//! **Version 19** was this without the clip's transform field: such a project
354//! places no clip anywhere but its fit policy's own spot, which is what `-`
355//! still means. **Version 18** was that without the clip's transition field:
356//! such a project dissolves no clip into its neighbor, which is what `0` still
357//! means. **Version 17** was this without the clip's two fade fields: such a project
358//! holds no clip anyone has faded, which is what a `0 0` pair still means.
359//! **Version 15** was this without the caption's group field: such a project
360//! holds captions no hand ever grouped, which is every caption there could be.
361//! **Version 14** was that without the `sub` lines: such a project holds no
362//! subtitle lane at all -- its `subtitle` lines are the palette, and where the
363//! words of it were shown was nowhere in the file.
364//! **Version 13** was that without the `encoder` line: such a project takes the
365//! hardware seat where there is one and the software encoder
366//! everywhere else, which is the only choice those projects had.
367//! **Version 12** was that without the `autoproxy` line: such a project makes a
368//! stand-in for every film that wants one the moment it arrives, which is all
369//! any project could do.
370//! **Version 11** was that without the `proxy` line: such a project is cut on
371//! its films themselves, which is all any project could do.
372//! **Version 10** was that without the `tonemap` line: such a project is shown
373//! in the reference rendition, which is the only one there was.
374//! **Version 9** was that without the `subtitle` lines: such a project shows no
375//! subtitles, which is all any project could do.
376//! **Version 8** was that without the `fps` and `limiter` lines and without
377//! the `gain` ones: such a project mixes every lane at unity, limits nothing,
378//! and comes back at the rate its scaffolding source runs at.
379//! **Version 7** was that without the clip's speed field -- every clip of such
380//! a project plays at real time, which is the only rate there was.
381//! **Version 6** was that without the `resolution` line and without the clip's
382//! fit field -- such a project is the size of its first source and letterboxes
383//! nothing, because nothing on it could differ in size. **Version 5** was that
384//! without the colour lines and without the clip's colour
385//! field. **Version 4** was that without the eq lines and without the clip's eq
386//! field. **Version 3** was that without the lane number, and held one video
387//! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
388//! well, which is this file's stream 0 -- one per file, whichever audio track
389//! came first. **Version 1** wrote that and one lane, queued end to end: `clip
390//! <in> <out> <source>`. All six still load -- a v1 file's clips are laid out
391//! cumulatively and copied onto both lanes as one group each, which is exactly
392//! what a v1 timeline meant, and an older file simply equalizes and grades
393//! nothing, and an older one plays everything at real time, and an older one
394//! mixes flat, and an older one shows no subtitles, and an older one is shown
395//! in the reference rendition, and an older one places none of the words it
396//! names, and an older one has no lane hidden, muted or locked -- and saving
397//! any of them writes v24. An older
398//! reader refuses a newer file by name.
399//!
400//! Text because an edit list is a few integers and a path, and a path is
401//! *bytes* on this platform -- a JSON string would have to lossily decode one.
402//! So the path field is byte-escaped (`%` -> `%25`, newline -> `%0A`, which is
403//! everything a line-based format cannot carry) and survives round-trip
404//! exactly. Paths under the project file's own directory are written relative
405//! to it, so a folder holding the media and the `.edith` can be moved or
406//! copied anywhere and still open; anything else is absolute.
407//!
408//! The parser is strict and every refusal names its 1-based line: a project
409//! file is generated, so a line it did not generate is a corrupt file, not a
410//! dialect. Structure is checked here (fields, ordering, empty clips,
411//! out-of-range source indexes); whether the files on disk still match the
412//! timeline is [`crate::PlaybackSession::open_project`]'s business.
413//!
414//! Writing goes through `<path>.part` and a rename, as an export does, so an
415//! interrupted save cannot destroy the previous version of the project. The
416//! bytes are fsynced before the rename and the directory after it, so what a
417//! power loss can lose is a whole save, never half of one under the real name.
418
419use std::ffi::OsString;
420use std::io::Write;
421use std::os::unix::ffi::{OsStrExt, OsStringExt};
422use std::path::{Path, PathBuf};
423
424use crate::color::ColorParams;
425use crate::duck::{
426 Duck, MAX_ATTACK_MS, MAX_DEPTH_DB, MAX_RELEASE_MS, MAX_THRESHOLD_DB, MIN_DEPTH_DB,
427 MIN_THRESHOLD_DB, MIN_TIME_MS,
428};
429use crate::eq::{Band, BandKind, EqParams};
430use crate::limiter::Limiter;
431use crate::project::{
432 Chapter, Clip, Deinterlace, GainKey, Marker, MarkerColor, Lane, LaneFlags, LaneKind, MAX_CLIP_GAIN_DB, MAX_GAIN_KEYS,
433 MAX_SPEED_KEYS, MIN_CLIP_GAIN_DB, STILL_DEFAULT_SECS, STILL_MAX_SECS, STILL_MIN_SECS, Source, Speed, SpeedKey, SubClip,
434 Title, check_chapter, check_marker, check_title,
435};
436use crate::scale::FitPolicy;
437use crate::subtitle::SubtitleTrack;
438use crate::captionanim::{CaptionAnim, CaptionStyle, MAX_WORDS_PER_LINE};
439use crate::voice::{Compressor, DeEsser, Gate, NoiseReduction, VoiceFx};
440use crate::text::{Align, HPlace, Outline, Place, TextStyle, Weight};
441use crate::titleanim::{TitleAnim, TitleKey};
442use crate::color::{ColorKey, MAX_COLOR_KEYS};
443use crate::transitions::TransitionKind;
444use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS, OpacityKey, TransformKey, TransformParams};
445
446/// The newest project format version: the `N` in the `edith N` first line that
447/// [`save`] writes for a project that uses the newest features. A reader refuses any
448/// higher version by name.
449pub const NEWEST_VERSION: u32 = 58;
450
451/// What [`save`] writes. Read support goes back to `edith 1`; see the module
452/// docs for what those dialects looked like. Kept at [`NEWEST_VERSION`].
453const MAGIC: &[u8] = b"edith 58";
454const MAGIC_V57: &[u8] = b"edith 57";
455const MAGIC_V56: &[u8] = b"edith 56";
456const MAGIC_V55: &[u8] = b"edith 55";
457const MAGIC_V54: &[u8] = b"edith 54";
458const MAGIC_V53: &[u8] = b"edith 53";
459const MAGIC_V52: &[u8] = b"edith 52";
460const MAGIC_V51: &[u8] = b"edith 51";
461const MAGIC_V50: &[u8] = b"edith 50";
462const MAGIC_V49: &[u8] = b"edith 49";
463const MAGIC_V48: &[u8] = b"edith 48";
464const MAGIC_V47: &[u8] = b"edith 47";
465const MAGIC_V46: &[u8] = b"edith 46";
466/// The most bands one equalizer line may declare. A hand-built cascade is a
467/// handful; the cap keeps a crafted line from making every clip run a million
468/// filters.
469const MAX_EQ_BANDS: usize = 64;
470/// The most words one `cuewords` line may carry (a cue is a line or two).
471const MAX_CUE_WORDS: usize = 1_000;
472/// The most sequences (tabs) a project may hold, each a parse of its own.
473const MAX_SEQUENCES: usize = 256;
474/// The most chapters, and the most markers, a project may hold.
475const MAX_LIST_ENTRIES: usize = 100_000;
476
477const MAGIC_V45: &[u8] = b"edith 45";
478const MAGIC_V44: &[u8] = b"edith 44";
479const MAGIC_V43: &[u8] = b"edith 43";
480const MAGIC_V42: &[u8] = b"edith 42";
481const MAGIC_V41: &[u8] = b"edith 41";
482const MAGIC_V40: &[u8] = b"edith 40";
483const MAGIC_V39: &[u8] = b"edith 39";
484const MAGIC_V38: &[u8] = b"edith 38";
485const MAGIC_V37: &[u8] = b"edith 37";
486const MAGIC_V36: &[u8] = b"edith 36";
487const MAGIC_V35: &[u8] = b"edith 35";
488const MAGIC_V34: &[u8] = b"edith 34";
489const MAGIC_V33: &[u8] = b"edith 33";
490const MAGIC_V32: &[u8] = b"edith 32";
491const MAGIC_V31: &[u8] = b"edith 31";
492const MAGIC_V30: &[u8] = b"edith 30";
493const MAGIC_V29: &[u8] = b"edith 29";
494const MAGIC_V28: &[u8] = b"edith 28";
495const MAGIC_V27: &[u8] = b"edith 27";
496const MAGIC_V26: &[u8] = b"edith 26";
497const MAGIC_V25: &[u8] = b"edith 25";
498const MAGIC_V24: &[u8] = b"edith 24";
499const MAGIC_V23: &[u8] = b"edith 23";
500const MAGIC_V22: &[u8] = b"edith 22";
501const MAGIC_V21: &[u8] = b"edith 21";
502const MAGIC_V20: &[u8] = b"edith 20";
503const MAGIC_V19: &[u8] = b"edith 19";
504const MAGIC_V18: &[u8] = b"edith 18";
505const MAGIC_V17: &[u8] = b"edith 17";
506const MAGIC_V16: &[u8] = b"edith 16";
507const MAGIC_V15: &[u8] = b"edith 15";
508const MAGIC_V14: &[u8] = b"edith 14";
509const MAGIC_V13: &[u8] = b"edith 13";
510const MAGIC_V12: &[u8] = b"edith 12";
511const MAGIC_V11: &[u8] = b"edith 11";
512const MAGIC_V10: &[u8] = b"edith 10";
513const MAGIC_V9: &[u8] = b"edith 9";
514const MAGIC_V8: &[u8] = b"edith 8";
515const MAGIC_V7: &[u8] = b"edith 7";
516const MAGIC_V6: &[u8] = b"edith 6";
517const MAGIC_V5: &[u8] = b"edith 5";
518const MAGIC_V4: &[u8] = b"edith 4";
519const MAGIC_V3: &[u8] = b"edith 3";
520const MAGIC_V2: &[u8] = b"edith 2";
521const MAGIC_V1: &[u8] = b"edith 1";
522
523/// What a project file says: an edit list plus where the playhead stood.
524/// Structurally valid by construction -- see [`parse`].
525#[derive(Debug)]
526pub struct Document {
527 /// Paths absolute, relative entries already joined to the file's own
528 /// directory.
529 pub sources: Vec<Source>,
530 /// Every lane, in display order, which is the order
531 /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then
532 /// `A1` -- for every dialect before v4.
533 pub lanes: Vec<(LaneKind, Vec<Clip>)>,
534 /// What is placed on each lane, in the order `lanes` is in and as long as
535 /// it -- the `sub` lines. Empty for every video and audio lane, which hold
536 /// no [`SubClip`], and for every lane of every dialect before v15, which
537 /// placed no words anywhere ([`crate::Project::with_subs`] takes it back).
538 pub subs: Vec<Vec<SubClip>>,
539 /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for
540 /// every dialect before v5.
541 pub eq: Vec<EqParams>,
542 /// The colour table [`Clip::color`] indexes into, in file order. Empty for
543 /// every dialect before v6.
544 pub color: Vec<ColorParams>,
545 /// The transform table [`Clip::transform`] indexes into, in file order.
546 /// Empty for every dialect before v20.
547 pub transform: Vec<TransformParams>,
548 /// The project's own picture size. `None` for every dialect before v7 and
549 /// for a v7 file that leaves it out, which both mean "source 0's picture".
550 pub resolution: Option<(u32, u32)>,
551 /// Every lane's own volume in dB, in the order `lanes` is in and as long as
552 /// it; `0.0` for a lane nobody has turned, which is every lane of every
553 /// dialect before v9.
554 pub gains: Vec<f32>,
555 /// Every lane's switches -- hidden, muted, locked -- in the order `lanes` is
556 /// in and as long as it. All clear for every dialect before v24, which had
557 /// no such switches, and for a lane a `flags` line does not name.
558 pub flags: Vec<LaneFlags>,
559 /// Every lane's auto-ducks, in the order `lanes` is in and as long as it;
560 /// empty for every lane but an audio lane somebody has ducked. Each lane
561 /// has at most one duck per key. Empty of every list for every dialect
562 /// before v25, which had no ducks, and at most one per lane before v30.
563 pub ducks: Vec<Vec<Duck>>,
564 /// The title cards and text overlays, in the order the file has them.
565 /// Empty for every dialect before v26, which had none.
566 pub titles: Vec<Title>,
567 /// The chapter markers, in frame order. Empty for every dialect before v34.
568 pub chapters: Vec<Chapter>,
569 /// The comment markers, in frame order. Empty for every dialect before v36.
570 pub markers: Vec<Marker>,
571 /// How burned captions animate, the `capstyle` line. The default (static cues) for every
572 /// dialect before v40.
573 pub caption_style: CaptionStyle,
574 /// Every lane's voice processors, in the order `lanes` is in and as long as it.
575 /// All off for every dialect before v41, and for a lane no `voice` line names.
576 pub voices: Vec<VoiceFx>,
577 /// One display name per lane (empty for none), from the `lanename` lines (v46).
578 pub names: Vec<String>,
579 /// The master limiter. Off for every dialect before v9, and for a v9 file
580 /// that leaves the line out.
581 pub limiter: Limiter,
582 /// The subtitle tracks, as the file names them: the path the cues are in
583 /// and which track of it, which is what [`crate::subtitle::open`] takes.
584 /// Reading them is the loader's business, not this module's -- a `.edith`
585 /// holds no cues. Empty for every dialect before v10.
586 pub subtitles: Vec<(PathBuf, Option<u64>)>,
587 /// The language of a subtitle track, `(track, code)`: the track by its
588 /// position in `subtitles`, the code as the file holds it (ISO 639-2 for
589 /// one set by a person, a container's own tag for an embedded track that
590 /// was not retyped). Empty for every dialect before v33.
591 pub sub_langs: Vec<(usize, String)>,
592 /// The cue overrides, `(track, cue, text)`: the track by its position in
593 /// `subtitles`, the cue by its position in that track. Empty for every
594 /// dialect before v24.
595 pub cue_edits: Vec<(usize, usize, String)>,
596 /// The cues added to a track ([`crate::project::AddedCue`]), each on its
597 /// track's own clock. Empty for every dialect before v29.
598 pub cue_adds: Vec<crate::project::AddedCue>,
599 /// The word times of cues, `(track, cue, words)` with the cue by its position in the track
600 /// as it stands after the edits and additions: the `cuewords` lines (v40). Empty before v40.
601 pub cue_words: Vec<crate::project::CueWordRow>,
602 /// The timeline's frame rate. `None` for every dialect before v9 and for a
603 /// v9 file that leaves it out, which both mean "whatever the scaffolding
604 /// source runs at" -- the inference a project of nothing but stills and
605 /// songs has no answer for (see
606 /// [`crate::PlaybackSession::open_project`]).
607 pub fps: Option<f64>,
608 /// The HDR-to-SDR rendition every clip on an HDR curve is shown in.
609 /// [`crate::tonemap::Preset::Reference`] for every dialect before v11 and
610 /// for a v11 file that leaves the line out, which both mean the published
611 /// conversion -- the only one those projects had.
612 pub tone: crate::tonemap::Preset,
613 /// Whether the films are cut on their stand-ins ([`crate::proxy`]). `false`
614 /// for every dialect before v12 and for a v12 file that leaves the line
615 /// out, which both mean the films themselves -- the only thing those
616 /// projects could do.
617 pub proxy: bool,
618 /// Whether an import makes a stand-in for a film that wants one by itself
619 /// ([`crate::proxy`]). `true` for every dialect before v13 and for a v13
620 /// file that leaves the line out, which both mean by itself -- the only
621 /// thing those projects did.
622 pub auto_proxy: bool,
623 /// Which encoder an export writes the picture with
624 /// ([`crate::export::EncoderSeat`]). `Auto` for every dialect before v14 and
625 /// for a v14 file that leaves the line out, which both mean the seat this
626 /// machine has -- the only choice those projects offered.
627 pub encoder: crate::export::EncoderSeat,
628 /// The rate the project's *sound* is mixed and exported at, chosen rather
629 /// than probed. `None` for every dialect before v17 and for a v17 file that
630 /// leaves the line out, which both mean what they always did: the rate of
631 /// the sources' own: the highest rate among the sources that have sound,
632 /// or 48 kHz when every one of them is below 44.1 kHz. Playback and export
633 /// both resample every other source
634 /// to whichever rate this resolves to, exactly as they already resample a
635 /// source shot at another rate than the timeline's -- an explicit choice
636 /// here only changes what that timeline's own rate *is*.
637 pub sample_rate: Option<u32>,
638 pub playhead: u32,
639 /// The active sequence's id and name, from the `seqactive` line (v45). `None` for a file
640 /// that holds one sequence, which is every dialect before v45.
641 pub seq_active: Option<(u32, String)>,
642 /// The tab order, from the `seqorder` line.
643 pub seq_order: Vec<u32>,
644 /// The other sequences, each a complete document of its own (`seq` ... `endseq`).
645 pub sequences: Vec<SeqDoc>,
646 /// The `mcam` lines (v47): a multicam source sequence's id and one angle's name each, in
647 /// angle order. Empty for a file with no multicam clip.
648 pub mcams: Vec<(u32, String)>,
649 /// The library's bins, from the `bin` lines (v51). Empty for a file with none.
650 pub bins: Vec<crate::project::Bin>,
651 /// The project notes, from the `notes` line (v52). Empty for a file with none, and for
652 /// every dialect before v52.
653 pub notes: String,
654 /// The length a still is placed at, from the `still` line (v52). `None` for a file that
655 /// leaves it out, which means the default: every dialect before v52 placed stills at 5 s.
656 pub still_secs: Option<f64>,
657 /// The speech model, from the `speech` line (v57). `None` for a file that names none, which
658 /// means the model is picked.
659 pub speech_model: Option<String>,
660 /// The device the speech model runs on, from the `speech` line (v57). Auto for a file without one.
661 pub speech_device: crate::speech::DeviceChoice,
662}
663
664/// A parked sequence read off a v45 file.
665#[derive(Debug)]
666pub struct SeqDoc {
667 pub id: u32,
668 pub name: String,
669 pub doc: Document,
670}
671
672/// Writes the project to `path`, atomically. `sources`, `eq` and `color` should
673/// already be orphan-free ([`crate::Project::without_orphan_sources`]);
674/// `gains` is one dB per lane in the same order the lanes are in
675/// ([`crate::Project::lane_gains`]) and `subs` is one list of placements per
676/// lane in that same order ([`crate::Project::lane_subs`]).
677///
678/// The same as [`save_flagged`] with every lane's switches clear, for the
679/// callers that have none to write.
680#[allow(clippy::too_many_arguments)]
681pub fn save(
682 path: &Path,
683 sources: &[Source],
684 lanes: &[(LaneKind, Vec<Clip>)],
685 gains: &[f32],
686 subs: &[Vec<SubClip>],
687 subtitles: &[SubtitleTrack],
688 eq: &[EqParams],
689 color: &[ColorParams],
690 transform: &[TransformParams],
691 resolution: (u32, u32),
692 fps: Option<f64>,
693 tone: crate::tonemap::Preset,
694 proxy: bool,
695 auto_proxy: bool,
696 encoder: crate::export::EncoderSeat,
697 limiter: Limiter,
698 sample_rate: Option<u32>,
699 playhead: u32,
700) -> crate::Result<()> {
701 save_flagged(
702 path,
703 sources,
704 lanes,
705 gains,
706 subs,
707 subtitles,
708 eq,
709 color,
710 transform,
711 resolution,
712 fps,
713 tone,
714 proxy,
715 auto_proxy,
716 encoder,
717 limiter,
718 sample_rate,
719 playhead,
720 &[],
721 &[],
722 &[],
723 &[],
724 &[],
725 &[],
726 &[],
727 &CaptionStyle::default(),
728 &[],
729 &[],
730 )
731}
732
733/// The bytes [`save_flagged`] writes, for a caller that assembles a file of several parts
734/// ([`sequenced`]). `dir` is the project's directory, which relative paths are written against.
735#[allow(clippy::too_many_arguments)]
736pub fn encode_flagged(
737 dir: &Path,
738 sources: &[Source],
739 lanes: &[(LaneKind, Vec<Clip>)],
740 gains: &[f32],
741 subs: &[Vec<SubClip>],
742 subtitles: &[SubtitleTrack],
743 eq: &[EqParams],
744 color: &[ColorParams],
745 transform: &[TransformParams],
746 resolution: (u32, u32),
747 fps: Option<f64>,
748 tone: crate::tonemap::Preset,
749 proxy: bool,
750 auto_proxy: bool,
751 encoder: crate::export::EncoderSeat,
752 limiter: Limiter,
753 sample_rate: Option<u32>,
754 playhead: u32,
755 flags: &[LaneFlags],
756 ducks: &[Vec<Duck>],
757 cue_edits: &[(usize, usize, String)],
758 cue_adds: &[crate::project::AddedCue],
759 titles: &[Title],
760 chapters: &[Chapter],
761 markers: &[Marker],
762 caption_style: &CaptionStyle,
763 voices: &[VoiceFx],
764 names: &[String],
765) -> Vec<u8> {
766 let mut bytes = emit(
767 dir,
768 sources,
769 lanes,
770 gains,
771 subs,
772 subtitles,
773 eq,
774 color,
775 transform,
776 resolution,
777 fps,
778 tone,
779 proxy,
780 auto_proxy,
781 encoder,
782 limiter,
783 sample_rate,
784 playhead,
785 );
786 // The cue overrides after the subtitle lines `emit` wrote, which
787 // they name; then the switches, which name lanes, as the gains do.
788 bytes.extend_from_slice(&cue_lines(cue_edits));
789 bytes.extend_from_slice(&cue_add_lines(cue_adds));
790 let cue_words = cue_word_lines(subtitles);
791 bytes.extend_from_slice(&flag_lines(lanes, flags));
792 bytes.extend_from_slice(&duck_lines(lanes, ducks));
793 bytes.extend_from_slice(&title_lines(titles));
794 // The chapters after the titles, and a file that has any is v34 whatever
795 // `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
796 // the one line `emit` wrote that these change, so it is swapped here,
797 // where the lines they need are.
798 let ramped = lanes
799 .iter()
800 .any(|(_, clips)| clips.iter().any(|c| !c.speed_keys.is_empty()));
801 let transitioned = lanes.iter().any(|(_, clips)| {
802 clips.iter().any(|c| c.transition_kind != TransitionKind::Dissolve)
803 });
804 let reversed = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.reversed));
805 // ...and one with an opacity or colour animation, or a key easing beyond
806 // linear and `ease`, is v39.
807 let animated = lanes.iter().any(|(_, clips)| clips.iter().any(needs_v39));
808 // ...and one with a project caption style or cue word times is v40.
809 let captioned = *caption_style != CaptionStyle::default() || !cue_words.is_empty();
810 // ...and one with a lane's voice processor is v41.
811 let voiced = voices.iter().any(|v| !v.is_default());
812 // ...and one with a clip's effect is v42.
813 let effected = lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.effects.is_empty()));
814 // ...and one with a grade's wheels, curves or LUT is v43.
815 let looked = color.iter().any(|p| p.look != crate::color::Look::default());
816 // ...and one with a stabilised clip is v44.
817 let steadied = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.stabilise.is_some()));
818 // ...and one with a named lane or a clip's deinterlace choice is v46.
819 let named = names.iter().any(|n| !n.is_empty());
820 let deinterlaced = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.deinterlace != Deinterlace::Frame));
821 // ...and one with a multicam clip's angle is v47.
822 let angled = lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.angle.is_default()));
823 // ...and one with a generated source (a solid, a gradient, a countdown, bars, an adjustment
824 // layer), a clip's colour label or a switched-off clip is v48.
825 // ...and one with a title's colour, weight, alignment, position or box colour is v49.
826 let styled = titles.iter().any(|t| !title_look_is_default(&t.style));
827 // ...and one with a title's entrance or exit animation is v54.
828 let titled = titles.iter().any(|t| t.in_anim != TitleAnim::None || t.out_anim != TitleAnim::None);
829 let marked = sources.iter().any(|s| crate::generate::is_generated(&s.path))
830 || lanes.iter().any(|(_, clips)| clips.iter().any(|c| !c.mark.is_default()));
831 // ...and one with a clip pan or a lane pan is v50.
832 let panned = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pan != 0)) || flags.iter().any(|f| f.pan != 0.0);
833 // ...and one with an effect's keys is v56 (`ekeys`), as is one with a custom bezier key easing.
834 let keyed = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.effects.iter().any(|e| !e.keys.is_empty())));
835 // ...and one with a clip's pitch shift is v55.
836 let pitched = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pitch != 0.0));
837 // ...and one with a fractional pitch shift is v58.
838 let fractional = lanes.iter().any(|(_, clips)| clips.iter().any(|c| c.pitch.fract() != 0.0));
839 // ...and one with a title's own keys is v56 (`ttkeys`).
840 let title_keyed = titles.iter().any(|t| !t.keys.is_empty());
841 let curved = keyed || title_keyed || lanes.iter().any(|(_, clips)| clips.iter().any(has_bezier));
842 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() {
843 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
844 let header = if fractional {
845 MAGIC
846 } else if curved {
847 MAGIC_V56
848 } else if pitched {
849 MAGIC_V55
850 } else if titled {
851 MAGIC_V54
852 } else if panned {
853 MAGIC_V50
854 } else if styled {
855 MAGIC_V49
856 } else if marked {
857 MAGIC_V48
858 } else if angled {
859 MAGIC_V47
860 } else if named || deinterlaced {
861 MAGIC_V46
862 } else if steadied {
863 MAGIC_V44
864 } else if looked {
865 MAGIC_V43
866 } else if effected {
867 MAGIC_V42
868 } else if voiced {
869 MAGIC_V41
870 } else if captioned {
871 MAGIC_V40
872 } else if animated {
873 MAGIC_V39
874 } else if reversed {
875 MAGIC_V38
876 } else if transitioned {
877 MAGIC_V37
878 } else if !markers.is_empty() {
879 MAGIC_V36
880 } else if ramped {
881 MAGIC_V35
882 } else {
883 MAGIC_V34
884 };
885 bytes.splice(..first_end, header.iter().copied());
886 }
887 bytes.extend_from_slice(&chapter_lines(chapters));
888 bytes.extend_from_slice(&marker_lines(markers));
889 bytes.extend_from_slice(&capstyle_line(caption_style));
890 bytes.extend_from_slice(&cue_words);
891 bytes.extend_from_slice(&voice_lines(lanes, voices));
892 bytes.extend_from_slice(&clip_gain_lines(lanes));
893 bytes.extend_from_slice(&gain_key_lines(lanes));
894 bytes.extend_from_slice(&tkey_lines(lanes));
895 bytes.extend_from_slice(&speed_key_lines(lanes));
896 bytes.extend_from_slice(&transition_lines(lanes));
897 bytes.extend_from_slice(&reverse_lines(lanes));
898 bytes.extend_from_slice(&opacity_key_lines(lanes));
899 bytes.extend_from_slice(&color_key_lines(lanes));
900 bytes.extend_from_slice(&effect_lines(lanes));
901 bytes.extend_from_slice(&effect_key_lines(lanes));
902 bytes.extend_from_slice(&look_lines(color, dir));
903 bytes.extend_from_slice(&stab_lines(lanes));
904 bytes.extend_from_slice(&deint_lines(lanes));
905 bytes.extend_from_slice(&lane_name_lines(lanes, names));
906 bytes.extend_from_slice(&angle_lines(lanes));
907 bytes.extend_from_slice(&mark_lines(lanes));
908 bytes.extend_from_slice(&pan_lines(lanes, flags));
909 bytes.extend_from_slice(&pitch_lines(lanes));
910 bytes
911}
912
913/// `main` (a document as [`encode_flagged`] wrote it) with the library's lines after it (v51):
914/// `bin <id> <parent> <name>` for each bin, `srcbin <source> <bin>` for each filed source and
915/// `srcfav <source>` for each starred one. A library with none of these is `main` untouched, so
916/// such a project is the bytes it was before v51.
917/// `current` (a file's first line, without its newline) with `candidate` in its place when
918/// `candidate` is a newer dialect, else `current` untouched. The library and notes lines raise
919/// the header to what they need and never lower it, so a file with effect keys (v56) keeps v56.
920fn raise_header(current: &[u8], candidate: &[u8]) -> Vec<u8> {
921 let version = |h: &[u8]| {
922 std::str::from_utf8(h).ok().and_then(|l| l.strip_prefix("edith ")).and_then(|n| n.parse::<u32>().ok()).unwrap_or(0)
923 };
924 if version(candidate) > version(current) { candidate.to_vec() } else { current.to_vec() }
925}
926
927pub fn binned(mut main: Vec<u8>, sources: &[Source], bins: &[crate::project::Bin]) -> Vec<u8> {
928 let mut lines = Vec::new();
929 for b in bins {
930 lines.extend_from_slice(format!("bin {} {} ", b.id, b.parent).as_bytes());
931 escape_text(&b.name, &mut lines);
932 lines.push(b'\n');
933 }
934 for (i, s) in sources.iter().enumerate() {
935 if s.bin != 0 {
936 lines.extend_from_slice(format!("srcbin {i} {}\n", s.bin).as_bytes());
937 }
938 if s.fav {
939 lines.extend_from_slice(format!("srcfav {i}\n").as_bytes());
940 }
941 }
942 if lines.is_empty() {
943 return main;
944 }
945 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
946 let header = raise_header(&main[..first_end], MAGIC_V51);
947 main.splice(..first_end, header);
948 if main.last() != Some(&b'\n') {
949 main.push(b'\n');
950 }
951 main.extend_from_slice(&lines);
952 main
953}
954
955/// `main` with the project notes, the still length and the speech choices after it (v52, v57): a
956/// `notes` line when there are notes, a `still` line when the length is not the default, a
957/// `speech` line when a model or a device is picked. A project with none is `main` untouched, so
958/// it keeps the bytes it had before v52.
959pub fn noted(mut main: Vec<u8>, notes: &str, still_secs: f64, speech_model: Option<&str>, speech_device: crate::speech::DeviceChoice) -> Vec<u8> {
960 let mut lines = Vec::new();
961 if !notes.is_empty() {
962 lines.extend_from_slice(b"notes ");
963 escape_text(notes, &mut lines);
964 lines.push(b'\n');
965 }
966 if still_secs != STILL_DEFAULT_SECS {
967 lines.extend_from_slice(format!("still {still_secs:?}\n").as_bytes());
968 }
969 let speech = speech_model.is_some() || speech_device != crate::speech::DeviceChoice::Auto;
970 if speech {
971 lines.extend_from_slice(format!("speech {}", speech_device.as_str()).as_bytes());
972 if let Some(m) = speech_model {
973 lines.extend_from_slice(format!(" {m}").as_bytes());
974 }
975 lines.push(b'\n');
976 }
977 if lines.is_empty() {
978 return main;
979 }
980 let first_end = main.iter().position(|&b| b == b'\n').unwrap_or(main.len());
981 let header = raise_header(&main[..first_end], if speech { MAGIC_V57 } else { MAGIC_V52 });
982 main.splice(..first_end, header);
983 if main.last() != Some(&b'\n') {
984 main.push(b'\n');
985 }
986 main.extend_from_slice(&lines);
987 main
988}
989
990/// [`save`], with each lane's switches -- `flags` is one entry per lane in the
991/// same order as `lanes`, as `gains` is ([`crate::Project::lane_flags`]).
992#[allow(clippy::too_many_arguments)]
993pub fn save_flagged(
994 path: &Path,
995 sources: &[Source],
996 lanes: &[(LaneKind, Vec<Clip>)],
997 gains: &[f32],
998 subs: &[Vec<SubClip>],
999 subtitles: &[SubtitleTrack],
1000 eq: &[EqParams],
1001 color: &[ColorParams],
1002 transform: &[TransformParams],
1003 resolution: (u32, u32),
1004 fps: Option<f64>,
1005 tone: crate::tonemap::Preset,
1006 proxy: bool,
1007 auto_proxy: bool,
1008 encoder: crate::export::EncoderSeat,
1009 limiter: Limiter,
1010 sample_rate: Option<u32>,
1011 playhead: u32,
1012 flags: &[LaneFlags],
1013 ducks: &[Vec<Duck>],
1014 cue_edits: &[(usize, usize, String)],
1015 cue_adds: &[crate::project::AddedCue],
1016 titles: &[Title],
1017 chapters: &[Chapter],
1018 markers: &[Marker],
1019 caption_style: &CaptionStyle,
1020 voices: &[VoiceFx],
1021 names: &[String],
1022) -> crate::Result<()> {
1023 let dir = project_dir(path);
1024 let bytes = encode_flagged(
1025 &dir,
1026 sources,
1027 lanes,
1028 gains,
1029 subs,
1030 subtitles,
1031 eq,
1032 color,
1033 transform,
1034 resolution,
1035 fps,
1036 tone,
1037 proxy,
1038 auto_proxy,
1039 encoder,
1040 limiter,
1041 sample_rate,
1042 playhead,
1043 flags,
1044 ducks,
1045 cue_edits,
1046 cue_adds,
1047 titles,
1048 chapters,
1049 markers,
1050 caption_style,
1051 voices,
1052 names,
1053 );
1054 write_atomic(path, &bytes)
1055}
1056
1057/// One parked sequence as a file holds it: a whole standalone document of its own.
1058pub struct SeqBlock {
1059 pub id: u32,
1060 pub name: String,
1061 pub bytes: Vec<u8>,
1062}
1063
1064/// `main` (the active sequence, as [`encode_flagged`] wrote it) with the other sequences after
1065/// it, as a v45 file: the `seqactive` and `seqorder` lines, then each parked sequence between
1066/// `seq <id> <name>` and `endseq`. The body of each block is a complete document, so its lines
1067/// read exactly as a project file's do.
1068pub fn sequenced(main: Vec<u8>, active: (u32, &str), order: &[u32], blocks: &[SeqBlock], mcam: &[(u32, Vec<String>)]) -> Vec<u8> {
1069 let mut bytes = main;
1070 let first_end = bytes.iter().position(|&b| b == b'\n').unwrap_or(bytes.len());
1071 // v47 only when something in the file needs it (a multicam source or an angle somewhere), v46
1072 // when a part is v46; a newer-only line under an older header is refused.
1073 let is = |b: &[u8], m: &[u8]| b.starts_with(m) && b.get(m.len()) == Some(&b'\n');
1074 let v58 = is(&bytes, MAGIC) || blocks.iter().any(|b| is(&b.bytes, MAGIC));
1075 let v57 = v58 || is(&bytes, MAGIC_V57) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V57));
1076 let v56 = v57 || is(&bytes, MAGIC_V56) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V56));
1077 let v55 = v56 || is(&bytes, MAGIC_V55) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V55));
1078 let v54 = v55 || is(&bytes, MAGIC_V54) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V54));
1079 let v53 = v54 || is(&bytes, MAGIC_V53) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V53));
1080 let v52 = v53 || is(&bytes, MAGIC_V52) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V52));
1081 let v51 = v52 || is(&bytes, MAGIC_V51) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V51));
1082 let v50 = v51 || is(&bytes, MAGIC_V50) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V50));
1083 let v49 = v50 || is(&bytes, MAGIC_V49) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V49));
1084 let v48 = v49 || is(&bytes, MAGIC_V48) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V48));
1085 let v47 = !mcam.is_empty() || is(&bytes, MAGIC_V47) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V47));
1086 let v46 = is(&bytes, MAGIC_V46) || blocks.iter().any(|b| is(&b.bytes, MAGIC_V46));
1087 let header = if v58 { MAGIC } else if v57 { MAGIC_V57 } 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 };
1088 bytes.splice(..first_end, header.iter().copied());
1089 bytes.extend_from_slice(format!("seqactive {} ", active.0).as_bytes());
1090 escape_text(active.1, &mut bytes);
1091 bytes.push(b'\n');
1092 let ids: Vec<String> = order.iter().map(u32::to_string).collect();
1093 bytes.extend_from_slice(format!("seqorder {}\n", ids.join(" ")).as_bytes());
1094 for (id, names) in mcam {
1095 for name in names {
1096 bytes.extend_from_slice(format!("mcam {id} ").as_bytes());
1097 escape_text(name, &mut bytes);
1098 bytes.push(b'\n');
1099 }
1100 }
1101 for b in blocks {
1102 bytes.extend_from_slice(format!("seq {} ", b.id).as_bytes());
1103 escape_text(&b.name, &mut bytes);
1104 bytes.push(b'\n');
1105 bytes.extend_from_slice(&b.bytes);
1106 if bytes.last() != Some(&b'\n') {
1107 bytes.push(b'\n');
1108 }
1109 bytes.extend_from_slice(b"endseq\n");
1110 }
1111 bytes
1112}
1113
1114/// Writes `bytes` to `path` atomically: a `.part` file beside it, synced, renamed over it, and the
1115/// directory synced, so until the rename the old file is still the whole truth.
1116pub fn write_atomic(path: &Path, bytes: &[u8]) -> crate::Result<()> {
1117 let dir = project_dir(path);
1118 let mut part = path.to_path_buf().into_os_string();
1119 part.push(".part");
1120 let part = PathBuf::from(part);
1121 let result = std::fs::File::create(&part)
1122 .and_then(|mut f| {
1123 f.write_all(bytes)?;
1124 f.sync_all()
1125 })
1126 .and_then(|()| std::fs::rename(&part, path))
1127 .and_then(|()| std::fs::File::open(&dir)?.sync_all());
1128 if result.is_err() {
1129 let _ = std::fs::remove_file(&part);
1130 }
1131 result.map_err(Into::into)
1132}
1133
1134pub fn load(path: &Path) -> crate::Result<Document> {
1135 let data = std::fs::read(path)?;
1136 // Relative lines are joined to the directory the project was opened
1137 // through, so the file is reached the way the project was opened; the
1138 // save side compares canonically (`written_path`), so whichever way it
1139 // was opened, a saved source is written relative.
1140 parse(&data, path.parent().unwrap_or(Path::new("")))
1141}
1142
1143/// The form a source or subtitle path is written in: relative to the project's
1144/// directory when the file is inside it, however the path was spelled -- a
1145/// `..` or a symlink on the way in is resolved before the comparison -- and as
1146/// it is otherwise. This is the one rule every save follows.
1147fn written_path(path: &Path, dir: &Path) -> PathBuf {
1148 if let Ok(rel) = path.strip_prefix(dir) {
1149 return rel.to_path_buf();
1150 }
1151 if let Ok(real) = path.canonicalize()
1152 && let Ok(rel) = real.strip_prefix(dir)
1153 {
1154 return rel.to_path_buf();
1155 }
1156 path.to_path_buf()
1157}
1158
1159/// The directory a project file's relative source lines are measured from, in
1160/// the same canonical form [`crate::Project`] keeps its sources in -- without
1161/// that the prefix simply never matches and every line comes out absolute,
1162/// which is what `cd dir && edith clip.mp4` + save used to write (the parent of
1163/// a bare filename is `""`). Canonicalizing fails only if the directory does
1164/// not exist, and then the write is about to fail anyway.
1165pub(crate) fn project_dir(path: &Path) -> PathBuf {
1166 let dir = path
1167 .parent()
1168 .filter(|p| !p.as_os_str().is_empty())
1169 .unwrap_or(Path::new("."));
1170 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
1171}
1172
1173/// The `cue` lines: one per retyped cue, after the `subtitle` lines that name
1174/// their tracks. Only a cue somebody has retyped has one, so an unedited project
1175/// is the bytes it was.
1176fn cue_lines(edits: &[(usize, usize, String)]) -> Vec<u8> {
1177 let mut out = Vec::new();
1178 for (track, cue, text) in edits {
1179 out.extend_from_slice(format!("cue {track} {cue} ").as_bytes());
1180 escape_text(text, &mut out);
1181 out.push(b'\n');
1182 }
1183 out
1184}
1185
1186/// The `cuewords` lines (v40): `cuewords <track> <cue> <start_us> <end_us> <word> ...` for each
1187/// cue that has word times, the cue by its position in the track as it stands when saved. The
1188/// times are on the track's own clock; a word has no whitespace, so a space separates fields.
1189fn cue_word_lines(subtitles: &[SubtitleTrack]) -> Vec<u8> {
1190 let mut out = Vec::new();
1191 for (t, track) in subtitles.iter().enumerate() {
1192 for (c, cue) in track.cues.iter().enumerate().filter(|(_, c)| !c.words.is_empty()) {
1193 out.extend_from_slice(format!("cuewords {t} {c}").as_bytes());
1194 for (start, end, word) in &cue.words {
1195 out.extend_from_slice(format!(" {start} {end} ").as_bytes());
1196 escape_text(word, &mut out);
1197 }
1198 out.push(b'\n');
1199 }
1200 }
1201 out
1202}
1203
1204/// The `cueadd` lines: one per cue added to a track, after the `cue` lines, as
1205/// `cueadd <track> <start_us> <end_us> <text>`, the text escaped as a `cue` line's is.
1206fn cue_add_lines(adds: &[crate::project::AddedCue]) -> Vec<u8> {
1207 let mut out = Vec::new();
1208 for a in adds {
1209 out.extend_from_slice(format!("cueadd {} {} {} ", a.track, a.start_us, a.end_us).as_bytes());
1210 escape_text(&a.text, &mut out);
1211 out.push(b'\n');
1212 }
1213 out
1214}
1215
1216/// The `duck` lines: one per duck, in lane order and then in the order the lane
1217/// holds them, the key named as the lanes are (1-based), so a project with none
1218/// is the bytes a v24 one was bar the version line.
1219fn duck_lines(lanes: &[(LaneKind, Vec<Clip>)], ducks: &[Vec<Duck>]) -> Vec<u8> {
1220 let mut out = Vec::new();
1221 let mut audio = 0u32;
1222 for ((kind, _), lane_ducks) in lanes.iter().zip(ducks) {
1223 if *kind != LaneKind::Audio {
1224 continue;
1225 }
1226 audio += 1;
1227 for d in lane_ducks {
1228 out.extend_from_slice(
1229 format!(
1230 "duck audio {audio} {} {:?} {:?} {:?} {:?}\n",
1231 d.under + 1,
1232 d.depth_db,
1233 d.threshold_db,
1234 d.attack_ms,
1235 d.release_ms
1236 )
1237 .as_bytes(),
1238 );
1239 }
1240 }
1241 out
1242}
1243
1244/// The `voice` lines: `voice audio <ord> <processor> <fields>...`, one per processor of an
1245/// audio lane that is not at its default (so a lane nobody has cleaned writes none, and a
1246/// project with none is the bytes a v36 one was bar the version line). The processors:
1247/// `gate <on> <threshold> <attack> <release> <hold> <range>`, `nr <on> <strength> <floor>
1248/// <profile>` (the profile a comma-separated list of dB, or `-`), `comp <on> <threshold>
1249/// <ratio> <attack> <release> <knee> <makeup> <auto>` and `deess <on> <threshold> <amount>
1250/// <lo> <hi>`; `<on>` and `<auto>` are `0` or `1`.
1251fn voice_lines(lanes: &[(LaneKind, Vec<Clip>)], voices: &[VoiceFx]) -> Vec<u8> {
1252 let mut out = String::new();
1253 let mut audio = 0u32;
1254 for ((kind, _), v) in lanes.iter().zip(voices) {
1255 if *kind != LaneKind::Audio {
1256 continue;
1257 }
1258 audio += 1;
1259 let b = |x: bool| u8::from(x);
1260 if v.gate != Gate::DEFAULT {
1261 let g = &v.gate;
1262 out += &format!(
1263 "voice audio {audio} gate {} {:?} {:?} {:?} {:?} {:?}\n",
1264 b(g.on), g.threshold_db, g.attack_ms, g.release_ms, g.hold_ms, g.range_db
1265 );
1266 }
1267 if v.nr != NoiseReduction::default() {
1268 let n = &v.nr;
1269 let profile = if n.profile.is_empty() {
1270 "-".to_string()
1271 } else {
1272 n.profile.iter().map(|d| format!("{d:?}")).collect::<Vec<_>>().join(",")
1273 };
1274 out += &format!("voice audio {audio} nr {} {:?} {:?} {profile}\n", b(n.on), n.strength, n.floor_db);
1275 }
1276 if v.comp != Compressor::DEFAULT {
1277 let c = &v.comp;
1278 out += &format!(
1279 "voice audio {audio} comp {} {:?} {:?} {:?} {:?} {:?} {:?} {}\n",
1280 b(c.on), c.threshold_db, c.ratio, c.attack_ms, c.release_ms, c.knee_db, c.makeup_db, b(c.auto_makeup)
1281 );
1282 }
1283 if v.deess != DeEsser::DEFAULT {
1284 let d = &v.deess;
1285 out += &format!(
1286 "voice audio {audio} deess {} {:?} {:?} {:?} {:?}\n",
1287 b(d.on), d.threshold_db, d.amount, d.lo_hz, d.hi_hz
1288 );
1289 }
1290 }
1291 out.into_bytes()
1292}
1293
1294/// The pan lines (v50): `clippan audio <ord> <index> <pan>` for each audio clip that is not in the
1295/// middle, and `lanepan audio <ord> <pan>` for each audio lane that is not.
1296fn pan_lines(lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]) -> Vec<u8> {
1297 let mut out = Vec::new();
1298 let mut audio = 0u32;
1299 for (n, (kind, clips)) in lanes.iter().enumerate() {
1300 if *kind != LaneKind::Audio {
1301 continue;
1302 }
1303 audio += 1;
1304 if let Some(f) = flags.get(n).filter(|f| f.pan != 0.0) {
1305 out.extend_from_slice(format!("lanepan audio {audio} {}\n", f.pan).as_bytes());
1306 }
1307 for (idx, c) in clips.iter().enumerate() {
1308 if c.pan != 0 {
1309 out.extend_from_slice(format!("clippan audio {audio} {idx} {}\n", c.pan_value()).as_bytes());
1310 }
1311 }
1312 }
1313 out
1314}
1315
1316/// The pitch lines (v55): `pitch audio <ord> <index> <semitones>` for each audio clip whose
1317/// pitch shift is not `0`.
1318fn pitch_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1319 let mut out = Vec::new();
1320 let mut audio = 0u32;
1321 for (kind, clips) in lanes {
1322 if *kind != LaneKind::Audio {
1323 continue;
1324 }
1325 audio += 1;
1326 for (idx, c) in clips.iter().enumerate() {
1327 if c.pitch != 0.0 {
1328 out.extend_from_slice(format!("pitch audio {audio} {idx} {}\n", c.pitch).as_bytes());
1329 }
1330 }
1331 }
1332 out
1333}
1334
1335/// The `clipgain` lines: one per clip whose own gain is not unity, as
1336/// `clipgain <kind> <ord> <index> <db>`. `index` counts the lane's clips from
1337/// `0`, in lane order. Written after the lanes they name, and only for a clip
1338/// somebody has turned, so a project with none is the bytes a v26 one was bar
1339/// the version line.
1340fn clip_gain_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1341 let mut out = Vec::new();
1342 let (mut video, mut audio) = (0u32, 0u32);
1343 for (kind, clips) in lanes {
1344 let (keyword, ord) = match kind {
1345 LaneKind::Video => {
1346 video += 1;
1347 ("video", video)
1348 }
1349 LaneKind::Audio => {
1350 audio += 1;
1351 ("audio", audio)
1352 }
1353 LaneKind::Subtitle => continue,
1354 };
1355 for (idx, c) in clips.iter().enumerate() {
1356 if c.gain_db != 0.0 {
1357 out.extend_from_slice(
1358 format!("clipgain {keyword} {ord} {idx} {}\n", c.gain_db).as_bytes(),
1359 );
1360 }
1361 }
1362 }
1363 out
1364}
1365
1366/// The `gainkeys` lines: one per clip with a volume envelope, as
1367/// `gainkeys <kind> <ord> <index> <at>:<db> ...`, the points in source order.
1368/// `kind` and `ord` name the lane the way [`clip_gain_lines`] does; `index`
1369/// counts the lane's clips from `0`. Written after the lanes they name, and
1370/// only for a clip with points, so a project with none is the bytes a v27 one
1371/// was bar the version line.
1372fn gain_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1373 let mut out = Vec::new();
1374 let (mut video, mut audio) = (0u32, 0u32);
1375 for (kind, clips) in lanes {
1376 let (keyword, ord) = match kind {
1377 LaneKind::Video => {
1378 video += 1;
1379 ("video", video)
1380 }
1381 LaneKind::Audio => {
1382 audio += 1;
1383 ("audio", audio)
1384 }
1385 LaneKind::Subtitle => continue,
1386 };
1387 for (idx, c) in clips.iter().enumerate() {
1388 if c.gain_keys.is_empty() {
1389 continue;
1390 }
1391 let points: String = c
1392 .gain_keys
1393 .iter()
1394 .map(|k| match k.ease {
1395 KeyEase::Linear => format!(" {}:{}", k.at, k.db),
1396 ease => format!(" {}:{}:{}", k.at, k.db, ease.token()),
1397 })
1398 .collect();
1399 out.extend_from_slice(format!("gainkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1400 }
1401 }
1402 out
1403}
1404
1405/// The `tkeys` lines: one per clip with a placement animation, as
1406/// `speedkeys <kind> <ord> <index> <at>:<permille> ...`, the keys in frame order. The
1407/// speeds are thousandths, as a clip's own `speed` field is, so they read back exactly.
1408/// Only a clip with keys gets a line, and such a project is a v35 one.
1409fn speed_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1410 let mut out = Vec::new();
1411 let (mut video, mut audio) = (0u32, 0u32);
1412 for (kind, clips) in lanes {
1413 let (keyword, ord) = match kind {
1414 LaneKind::Video => {
1415 video += 1;
1416 ("video", video)
1417 }
1418 LaneKind::Audio => {
1419 audio += 1;
1420 ("audio", audio)
1421 }
1422 LaneKind::Subtitle => continue,
1423 };
1424 for (idx, c) in clips.iter().enumerate() {
1425 if c.speed_keys.is_empty() {
1426 continue;
1427 }
1428 let points: String = c
1429 .speed_keys
1430 .iter()
1431 .map(|k| format!(" {}:{}", k.at, k.speed.permille()))
1432 .collect();
1433 out.extend_from_slice(format!("speedkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1434 }
1435 }
1436 out
1437}
1438
1439/// The `transition` lines: one per clip whose transition is not a dissolve, as
1440/// `transition <kind> <ord> <index> <name>`. Such a project is a v37 one.
1441fn transition_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1442 let mut out = Vec::new();
1443 let (mut video, mut audio) = (0u32, 0u32);
1444 for (kind, clips) in lanes {
1445 let (keyword, ord) = match kind {
1446 LaneKind::Video => {
1447 video += 1;
1448 ("video", video)
1449 }
1450 LaneKind::Audio => {
1451 audio += 1;
1452 ("audio", audio)
1453 }
1454 LaneKind::Subtitle => continue,
1455 };
1456 for (idx, c) in clips.iter().enumerate() {
1457 if c.transition_kind != TransitionKind::Dissolve {
1458 out.extend_from_slice(
1459 format!("transition {keyword} {ord} {idx} {}\n", c.transition_kind.name()).as_bytes(),
1460 );
1461 }
1462 }
1463 }
1464 out
1465}
1466
1467/// Whether a clip needs the v39 dialect: an opacity or colour animation, or a
1468/// key easing that v35 has no word for (`in`, `out`, `hold` on a placement key,
1469/// anything but linear on a volume point).
1470fn needs_v39(c: &Clip) -> bool {
1471 !c.opacity_keys.is_empty()
1472 || !c.color_keys.is_empty()
1473 || c.gain_keys.iter().any(|k| k.ease != KeyEase::Linear)
1474 || c.transform_keys
1475 .iter()
1476 .any(|k| matches!(k.ease, KeyEase::EaseIn | KeyEase::EaseOut | KeyEase::Hold))
1477}
1478
1479/// Whether a clip has a key with a custom bezier easing, which only v56 can
1480/// hold: a placement, opacity, colour, volume or mask key.
1481fn has_bezier(c: &Clip) -> bool {
1482 let bezier = |e: KeyEase| matches!(e, KeyEase::Bezier(_));
1483 c.transform_keys.iter().any(|k| bezier(k.ease))
1484 || c.opacity_keys.iter().any(|k| bezier(k.ease))
1485 || c.color_keys.iter().any(|k| bezier(k.ease))
1486 || c.gain_keys.iter().any(|k| bezier(k.ease))
1487 || c.effects.iter().any(|e| e.keys.iter().any(|k| bezier(k.ease)))
1488}
1489
1490/// One line per video clip that `points` returns something for, as
1491/// `<name> video <ord> <index>{points}`: the shape of the `okeys` and `ckeys` lines.
1492fn video_key_lines(
1493 lanes: &[(LaneKind, Vec<Clip>)],
1494 name: &str,
1495 points: impl Fn(&Clip) -> String,
1496) -> Vec<u8> {
1497 let mut out = Vec::new();
1498 let mut video = 0u32;
1499 for (kind, clips) in lanes {
1500 if *kind != LaneKind::Video {
1501 continue;
1502 }
1503 video += 1;
1504 for (idx, c) in clips.iter().enumerate() {
1505 let points = points(c);
1506 if !points.is_empty() {
1507 out.extend_from_slice(format!("{name} video {video} {idx}{points}\n").as_bytes());
1508 }
1509 }
1510 }
1511 out
1512}
1513
1514/// The `reverse` lines: one per clip that plays backwards, as `reverse <kind> <ord>
1515/// <index>`. Only a reversed clip gets a line, and such a project is a v38 one.
1516fn reverse_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1517 let mut out = Vec::new();
1518 let (mut video, mut audio) = (0u32, 0u32);
1519 for (kind, clips) in lanes {
1520 let (keyword, ord) = match kind {
1521 LaneKind::Video => {
1522 video += 1;
1523 ("video", video)
1524 }
1525 LaneKind::Audio => {
1526 audio += 1;
1527 ("audio", audio)
1528 }
1529 LaneKind::Subtitle => continue,
1530 };
1531 for (idx, _) in clips.iter().enumerate().filter(|(_, c)| c.reversed) {
1532 out.extend_from_slice(format!("reverse {keyword} {ord} {idx}\n").as_bytes());
1533 }
1534 }
1535 out
1536}
1537
1538/// `deint video <ord> <index> <mode>`: one per clip whose mode is not `frame`, and such a
1539/// project is a v46 one.
1540fn deint_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1541 video_key_lines(lanes, "deint", |c| match c.deinterlace {
1542 Deinterlace::Frame => String::new(),
1543 d => format!(" {}", d.name()),
1544 })
1545}
1546
1547/// `lanename <kind> <ord> <name>`: one per lane that has a name.
1548fn lane_name_lines(lanes: &[(LaneKind, Vec<Clip>)], names: &[String]) -> Vec<u8> {
1549 let mut out = Vec::new();
1550 let (mut video, mut audio, mut sub) = (0u32, 0u32, 0u32);
1551 for ((kind, _), name) in lanes.iter().zip(names) {
1552 let (keyword, ord) = match kind {
1553 LaneKind::Video => {
1554 video += 1;
1555 ("video", video)
1556 }
1557 LaneKind::Audio => {
1558 audio += 1;
1559 ("audio", audio)
1560 }
1561 LaneKind::Subtitle => {
1562 sub += 1;
1563 ("sub", sub)
1564 }
1565 };
1566 if !name.is_empty() {
1567 out.extend_from_slice(format!("lanename {keyword} {ord} ").as_bytes());
1568 escape_text(name, &mut out);
1569 out.push(b'\n');
1570 }
1571 }
1572 out
1573}
1574
1575/// `stab video <ord> <index> <strength> <crop>`: one per stabilised clip, and such a
1576/// project is a v44 one.
1577fn stab_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1578 video_key_lines(lanes, "stab", |c| {
1579 c.stabilise.map_or(String::new(), |st| format!(" {} {}", st.amount(), st.crop().name()))
1580 })
1581}
1582
1583/// The `mark` lines: one per clip that has a colour label or is switched off, as `mark <kind>
1584/// <ord> <index> <label> <on|off>` with the label 0 to 8. Only such a clip gets a line, and such a
1585/// project is a v48 one.
1586fn mark_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1587 let mut out = Vec::new();
1588 let (mut video, mut audio) = (0u32, 0u32);
1589 for (kind, clips) in lanes {
1590 let (keyword, ord) = match kind {
1591 LaneKind::Video => {
1592 video += 1;
1593 ("video", video)
1594 }
1595 LaneKind::Audio => {
1596 audio += 1;
1597 ("audio", audio)
1598 }
1599 LaneKind::Subtitle => continue,
1600 };
1601 for (idx, c) in clips.iter().enumerate().filter(|(_, c)| !c.mark.is_default()) {
1602 let state = if c.mark.off { "off" } else { "on" };
1603 out.extend_from_slice(format!("mark {keyword} {ord} {idx} {} {state}\n", c.mark.label).as_bytes());
1604 }
1605 }
1606 out
1607}
1608
1609/// The `angle` lines: one per clip that shows another angle than the first, as `angle <kind> <ord>
1610/// <index> <picture> <sound>` with angles counted from 1 and `-` for a sound that follows the
1611/// picture. Only such a clip gets a line, and such a project is a v47 one.
1612fn angle_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1613 let mut out = Vec::new();
1614 let (mut video, mut audio) = (0u32, 0u32);
1615 for (kind, clips) in lanes {
1616 let (keyword, ord) = match kind {
1617 LaneKind::Video => {
1618 video += 1;
1619 ("video", video)
1620 }
1621 LaneKind::Audio => {
1622 audio += 1;
1623 ("audio", audio)
1624 }
1625 LaneKind::Subtitle => continue,
1626 };
1627 for (idx, c) in clips.iter().enumerate().filter(|(_, c)| !c.angle.is_default()) {
1628 let sound = c.angle.audio.map_or("-".to_string(), |a| (u32::from(a) + 1).to_string());
1629 out.extend_from_slice(format!("angle {keyword} {ord} {idx} {} {sound}\n", u32::from(c.angle.video) + 1).as_bytes());
1630 }
1631 }
1632 out
1633}
1634
1635/// `okeys video <ord> <index> <at>:<ease>:<opacity> ...`, the opacity keys in
1636/// source order. Only a clip with keys gets a line, and such a project is a v39 one.
1637fn opacity_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1638 video_key_lines(lanes, "okeys", |c| {
1639 c.opacity_keys
1640 .iter()
1641 .map(|k| format!(" {}:{}:{}", k.at, k.ease.token(), k.opacity))
1642 .collect()
1643 })
1644}
1645
1646/// `ckeys video <ord> <index> <at>:<ease>:<brightness>,<contrast>,<saturation>,<tint> ...`,
1647/// the colour keys in source order. Only a clip with keys gets a line, and such
1648/// a project is a v39 one.
1649fn color_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1650 video_key_lines(lanes, "ckeys", |c| {
1651 c.color_keys
1652 .iter()
1653 .map(|k| {
1654 let p = &k.params;
1655 format!(
1656 " {}:{}:{},{},{},{}",
1657 k.at,
1658 k.ease.token(),
1659 p.brightness,
1660 p.contrast,
1661 p.saturation,
1662 p.tint
1663 )
1664 })
1665 .collect()
1666 })
1667}
1668
1669/// The `effect` lines (v42): `effect video <ord> <index> <kind> <on> <value>...`, one per
1670/// effect of a clip's stack, in stack order. Only a clip with effects gets any.
1671fn effect_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1672 let mut out = String::new();
1673 let mut video = 0u32;
1674 for (kind, clips) in lanes {
1675 if *kind != LaneKind::Video {
1676 continue;
1677 }
1678 video += 1;
1679 for (idx, c) in clips.iter().enumerate() {
1680 for e in &c.effects {
1681 out += &format!("effect video {video} {idx} {} {}", e.kind.name(), u8::from(e.on));
1682 for v in &e.values[..e.kind.params().len()] {
1683 out += &format!(" {v}");
1684 }
1685 out.push('\n');
1686 }
1687 }
1688 }
1689 out.into_bytes()
1690}
1691
1692/// The `ekeys` lines (v56): `ekeys video <ord> <index> <slot> <at>:<ease>:<v0>,<v1>,... ...`,
1693/// the keys of the effect at stack position `slot`, in source order, with one value for each
1694/// of its [`crate::effects::EffectKind::params`]. Only an effect with keys gets a line.
1695fn effect_key_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1696 let mut out = String::new();
1697 let mut video = 0u32;
1698 for (kind, clips) in lanes {
1699 if *kind != LaneKind::Video {
1700 continue;
1701 }
1702 video += 1;
1703 for (idx, c) in clips.iter().enumerate() {
1704 for (slot, e) in c.effects.iter().enumerate() {
1705 if e.keys.is_empty() {
1706 continue;
1707 }
1708 out += &format!("ekeys video {video} {idx} {slot}");
1709 let count = e.kind.params().len();
1710 for k in &e.keys {
1711 let values: Vec<String> = k.values[..count].iter().map(|v| v.to_string()).collect();
1712 out += &format!(" {}:{}:{}", k.at, k.ease.token(), values.join(","));
1713 }
1714 out.push('\n');
1715 }
1716 }
1717 }
1718 out.into_bytes()
1719}
1720
1721/// The v43 look lines, one group per colour line that has one, named by the
1722/// colour line's position:
1723///
1724/// * `wheels <color> <lift> <gamma> <gain>`, each `<master>:<red>:<green>:<blue>`,
1725/// * `curve <color> <channel> <x>:<y>,<x>:<y>...`, one per channel (`master`,
1726/// `red`, `green`, `blue`) that holds points,
1727/// * `lut <color> <mix> <path>`, the path written as a source's is (relative
1728/// when inside the project's folder) and running to the end of the line.
1729fn look_lines(color: &[ColorParams], dir: &Path) -> Vec<u8> {
1730 let quad = |q: &[f32; 4]| format!("{:?}:{:?}:{:?}:{:?}", q[0], q[1], q[2], q[3]);
1731 let mut out = Vec::new();
1732 for (i, p) in color.iter().enumerate() {
1733 let look = &p.look;
1734 if look.wheels != crate::color::Wheels::default() {
1735 let w = &look.wheels;
1736 out.extend_from_slice(
1737 format!("wheels {i} {} {} {}\n", quad(&w.lift), quad(&w.gamma), quad(&w.gain)).as_bytes(),
1738 );
1739 }
1740 for (c, curve) in look.curves.iter().enumerate() {
1741 if curve.points().is_empty() {
1742 continue;
1743 }
1744 let pts: Vec<String> = curve.points().iter().map(|q| format!("{:?}:{:?}", q[0], q[1])).collect();
1745 out.extend_from_slice(
1746 format!("curve {i} {} {}\n", crate::color::CHANNELS[c], pts.join(",")).as_bytes(),
1747 );
1748 }
1749 if let Some(lut) = look.lut {
1750 out.extend_from_slice(format!("lut {i} {:?} ", look.lut_mix).as_bytes());
1751 escape(&written_path(&lut.path(), dir), &mut out);
1752 out.push(b'\n');
1753 }
1754 }
1755 out
1756}
1757
1758/// A `wheels`, `curve` or `lut` line (v43): see [`look_lines`]. A LUT file that is
1759/// missing or broken still loads -- the clip plays without it and
1760/// [`crate::Project::lut_problems`] names it -- but a malformed line is refused.
1761fn parse_look(head: &[u8], rest: &[u8], n: usize, dir: &Path, doc: &mut Document) -> crate::Result<()> {
1762 let sp = rest.iter().position(|&b| b == b' ').unwrap_or(rest.len());
1763 let at = number(&rest[..sp], n)? as usize;
1764 let rest = rest.get(sp + 1..).unwrap_or(&[]);
1765 let what = String::from_utf8_lossy(head).into_owned();
1766 if at >= doc.color.len() {
1767 return Err(format!("line {n}: {what} names color {at}, and there are {}", doc.color.len()).into());
1768 }
1769 let look = &mut doc.color[at].look;
1770 match head {
1771 b"wheels" => {
1772 let f = fields(rest, 3, "wheels", n)?;
1773 let mut q = [[0f32; 4]; 3];
1774 for (k, field) in f.iter().enumerate() {
1775 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
1776 if parts.len() != 4 {
1777 return Err(format!("line {n}: a wheel wants 4 values").into());
1778 }
1779 for (c, part) in parts.iter().enumerate() {
1780 let v = float(part, n)?;
1781 if !(-1.0..=1.0).contains(&v) {
1782 return Err(format!("line {n}: wheels has a value outside -1..1").into());
1783 }
1784 q[k][c] = v;
1785 }
1786 }
1787 look.wheels = crate::color::Wheels { lift: q[0], gamma: q[1], gain: q[2] };
1788 }
1789 b"curve" => {
1790 let f = fields(rest, 2, "curve", n)?;
1791 let channel = crate::color::CHANNELS
1792 .iter()
1793 .position(|c| c.as_bytes() == f[0])
1794 .ok_or_else(|| format!("line {n}: curve channel {:?} is not master, red, green or blue", String::from_utf8_lossy(f[0])))?;
1795 let mut pts = Vec::new();
1796 for pair in f[1].split(|&b| b == b',') {
1797 let xy: Vec<&[u8]> = pair.split(|&b| b == b':').collect();
1798 if xy.len() != 2 {
1799 return Err(format!("line {n}: a curve point is <x>:<y>").into());
1800 }
1801 pts.push([float(xy[0], n)?, float(xy[1], n)?]);
1802 }
1803 look.curves[channel] = crate::color::Curve::new(&pts).map_err(|e| format!("line {n}: {e}"))?;
1804 }
1805 _ => {
1806 let sp = rest.iter().position(|&b| b == b' ').ok_or_else(|| format!("line {n}: lut wants <mix> <path>"))?;
1807 let mix = float(&rest[..sp], n)?;
1808 if !(0.0..=1.0).contains(&mix) {
1809 return Err(format!("line {n}: lut mix must be 0..=1").into());
1810 }
1811 let path = unescape(&rest[sp + 1..], n)?;
1812 if path.as_os_str().is_empty() {
1813 return Err(format!("line {n}: lut without a path").into());
1814 }
1815 let path = if path.is_absolute() { path } else { dir.join(path) };
1816 look.lut = Some(crate::cube::LutRef::open(&path));
1817 look.lut_mix = mix;
1818 }
1819 }
1820 Ok(())
1821}
1822
1823/// `tkeys <kind> <ord> <index> <at>:<ease>:<pos_x>,<pos_y>,<scale>,<rotate>,<crop_l>,<crop_r>,<crop_t>,<crop_b>,<opacity> ...`,
1824/// the keys in source order. `ease` is `lin` or `ease`. Floats are written the
1825/// way the `transform` table writes them, `{}`, which reads back exactly. Only a
1826/// clip with keys gets a line, and such a project is a v32 one.
1827fn tkey_lines(lanes: &[(LaneKind, Vec<Clip>)]) -> Vec<u8> {
1828 let mut out = Vec::new();
1829 let (mut video, mut audio) = (0u32, 0u32);
1830 for (kind, clips) in lanes {
1831 let (keyword, ord) = match kind {
1832 LaneKind::Video => {
1833 video += 1;
1834 ("video", video)
1835 }
1836 LaneKind::Audio => {
1837 audio += 1;
1838 ("audio", audio)
1839 }
1840 LaneKind::Subtitle => continue,
1841 };
1842 for (idx, c) in clips.iter().enumerate() {
1843 if c.transform_keys.is_empty() {
1844 continue;
1845 }
1846 let points: String = c
1847 .transform_keys
1848 .iter()
1849 .map(|k| {
1850 let p = &k.params;
1851 let ease = k.ease.token();
1852 format!(
1853 " {}:{ease}:{},{},{},{},{},{},{},{},{}",
1854 k.at,
1855 p.pos_x,
1856 p.pos_y,
1857 p.scale,
1858 p.rotate,
1859 p.crop_l,
1860 p.crop_r,
1861 p.crop_t,
1862 p.crop_b,
1863 p.opacity
1864 )
1865 })
1866 .collect();
1867 out.extend_from_slice(format!("tkeys {keyword} {ord} {idx}{points}\n").as_bytes());
1868 }
1869 }
1870 out
1871}
1872
1873/// The `chapter` lines: one per chapter, in frame order, as [`save_flagged`]
1874/// writes them after the titles. A project with none writes nothing.
1875fn chapter_lines(chapters: &[Chapter]) -> Vec<u8> {
1876 let mut out = Vec::new();
1877 for c in chapters {
1878 out.extend_from_slice(format!("chapter {} ", c.frame).as_bytes());
1879 escape_text(&c.title, &mut out);
1880 out.push(b'\n');
1881 }
1882 out
1883}
1884
1885/// The `marker` lines, one per marker in frame order, then a `marknote` line for each one
1886/// that has a note, as [`save_flagged`] writes them after the chapters. None for a project with none.
1887/// The `capstyle` line, `capstyle <animation> <rrggbb> <box 0|1> <uppercase 0|1> <words per
1888/// line>`: how burned captions animate. None for the default style, so a project that never
1889/// touched it is the bytes it was before v40, bar the version line.
1890fn capstyle_line(cs: &CaptionStyle) -> Vec<u8> {
1891 if *cs == CaptionStyle::default() {
1892 return Vec::new();
1893 }
1894 let [r, g, b] = cs.highlight;
1895 format!(
1896 "capstyle {} {r:02x}{g:02x}{b:02x} {} {} {}\n",
1897 cs.anim.name(),
1898 u8::from(cs.hl_box),
1899 u8::from(cs.uppercase),
1900 cs.words_per_line
1901 )
1902 .into_bytes()
1903}
1904
1905fn marker_lines(markers: &[Marker]) -> Vec<u8> {
1906 let mut out = Vec::new();
1907 for m in markers {
1908 out.extend_from_slice(format!("marker {} {} {} ", m.frame, m.length, m.color.name()).as_bytes());
1909 escape_text(&m.name, &mut out);
1910 out.push(b'\n');
1911 }
1912 for (i, m) in markers.iter().enumerate().filter(|(_, m)| !m.note.is_empty()) {
1913 out.extend_from_slice(format!("marknote {i} ").as_bytes());
1914 escape_text(&m.note, &mut out);
1915 out.push(b'\n');
1916 }
1917 out
1918}
1919
1920/// The `title` lines: one per title, in list order, as [`save_flagged`] writes
1921/// them. A project with none is the bytes a v25 one was bar the version line.
1922fn title_lines(titles: &[Title]) -> Vec<u8> {
1923 let mut out = Vec::new();
1924 for t in titles {
1925 let outline = match t.style.outline {
1926 Outline::None => "none",
1927 Outline::Thin => "thin",
1928 Outline::Thick => "thick",
1929 };
1930 let place = match t.style.place {
1931 Place::Bottom => "bottom",
1932 Place::Top => "top",
1933 Place::Centre => "centre",
1934 };
1935 out.extend_from_slice(
1936 format!(
1937 "title {} {} {} {} {} {outline} {} {place} ",
1938 t.start,
1939 t.frames,
1940 t.fade_in,
1941 t.fade_out,
1942 t.style.size,
1943 u8::from(t.style.boxed)
1944 )
1945 .as_bytes(),
1946 );
1947 escape_text(&t.text, &mut out);
1948 out.push(b'\n');
1949 }
1950 // A title's colour, weight, alignment, position and box colour, one line per title that has
1951 // any of them off the default, so a project without them is the bytes it was.
1952 for (i, t) in titles.iter().enumerate() {
1953 let st = &t.style;
1954 if title_look_is_default(st) {
1955 continue;
1956 }
1957 let hplace = match st.hplace {
1958 HPlace::Centre => "centre",
1959 HPlace::Left => "left",
1960 HPlace::Right => "right",
1961 };
1962 let align = match st.align {
1963 Align::Centre => "centre",
1964 Align::Left => "left",
1965 Align::Right => "right",
1966 };
1967 let weight = match st.weight {
1968 Weight::Regular => "regular",
1969 Weight::Bold => "bold",
1970 };
1971 let [r, g, b] = st.ink;
1972 let [br, bg, bb, ba] = st.box_color;
1973 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());
1974 }
1975 // A title's entrance and exit, one line per title that has either.
1976 for (i, t) in titles.iter().enumerate() {
1977 if t.in_anim == TitleAnim::None && t.out_anim == TitleAnim::None {
1978 continue;
1979 }
1980 out.extend_from_slice(format!("titleanim {i} {} {} {}\n", t.in_anim.name(), t.out_anim.name(), t.anim_frames).as_bytes());
1981 }
1982 // A title's own keys, one line per title that has any, after its `titleanim` line.
1983 for (i, t) in titles.iter().enumerate() {
1984 if t.keys.is_empty() {
1985 continue;
1986 }
1987 out.extend_from_slice(format!("ttkeys {i}").as_bytes());
1988 for k in &t.keys {
1989 out.extend_from_slice(format!(" {}:{}:{},{},{},{}", k.at, k.ease.token(), k.x, k.y, k.scale, k.opacity).as_bytes());
1990 }
1991 out.push(b'\n');
1992 }
1993 out
1994}
1995
1996/// Whether a style has none of the v49 title looks: white, regular, centred, on the black box.
1997fn title_look_is_default(st: &TextStyle) -> bool {
1998 let d = TextStyle::default();
1999 st.hplace == d.hplace && st.align == d.align && st.weight == d.weight && st.ink == d.ink && st.box_color == d.box_color
2000}
2001
2002/// The `flags` lines: one per lane that has a switch set, in lane order. Only a
2003/// lane somebody has switched gets one, so a project with none is the bytes a
2004/// v23 one was bar the version line.
2005fn flag_lines(lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]) -> Vec<u8> {
2006 let mut out = Vec::new();
2007 let (mut video, mut audio, mut sub) = (0u32, 0u32, 0u32);
2008 for ((kind, _), f) in lanes.iter().zip(flags) {
2009 let (keyword, ord) = match kind {
2010 LaneKind::Video => {
2011 video += 1;
2012 ("video", video)
2013 }
2014 LaneKind::Audio => {
2015 audio += 1;
2016 ("audio", audio)
2017 }
2018 LaneKind::Subtitle => {
2019 sub += 1;
2020 ("sub", sub)
2021 }
2022 };
2023 let words: Vec<&str> = [
2024 (f.hidden, "hidden"),
2025 (f.muted, "muted"),
2026 (f.locked, "locked"),
2027 ]
2028 .into_iter()
2029 .filter_map(|(on, word)| on.then_some(word))
2030 .collect();
2031 if !words.is_empty() {
2032 out.extend_from_slice(
2033 format!("flags {keyword} {ord} {}\n", words.join(" ")).as_bytes(),
2034 );
2035 }
2036 }
2037 out
2038}
2039
2040#[allow(clippy::too_many_arguments)]
2041fn emit(
2042 dir: &Path,
2043 sources: &[Source],
2044 lanes: &[(LaneKind, Vec<Clip>)],
2045 gains: &[f32],
2046 subs: &[Vec<SubClip>],
2047 subtitles: &[SubtitleTrack],
2048 eq: &[EqParams],
2049 color: &[ColorParams],
2050 transform: &[TransformParams],
2051 resolution: (u32, u32),
2052 fps: Option<f64>,
2053 tone: crate::tonemap::Preset,
2054 proxy: bool,
2055 auto_proxy: bool,
2056 encoder: crate::export::EncoderSeat,
2057 limiter: Limiter,
2058 sample_rate: Option<u32>,
2059 playhead: u32,
2060) -> Vec<u8> {
2061 let mut out = Vec::new();
2062 // The file says which dialect it is by whether it needs the newest one:
2063 // a transform's opacity is the only thing v31 adds, so a project without
2064 // one is the bytes a v30 project always was, bar none, and an older reader
2065 // still opens it.
2066 // The newest dialect is only for a project that has placement keys
2067 // (`tkeys` lines, [`tkeys_lines`]); one with opacity alone is still v31.
2068 let needs_v33 = subtitles.iter().any(|t| !t.language.is_empty());
2069 let needs_v32 = lanes
2070 .iter()
2071 .any(|(_, clips)| clips.iter().any(|c| !c.transform_keys.is_empty()));
2072 let needs_v31 = transform.iter().any(|p| p.opacity != 1.0);
2073 out.extend_from_slice(if needs_v33 {
2074 MAGIC_V33
2075 } else if needs_v32 {
2076 MAGIC_V32
2077 } else if needs_v31 {
2078 MAGIC_V31
2079 } else {
2080 MAGIC_V30
2081 });
2082 out.push(b'\n');
2083 out.extend_from_slice(format!("playhead {playhead}\n").as_bytes());
2084 out.extend_from_slice(format!("resolution {} {}\n", resolution.0, resolution.1).as_bytes());
2085 // `{:?}`, the eq table's rule: the rate a timeline was cut at has to read
2086 // back as the very number, or every clip on it lands on another frame.
2087 if let Some(fps) = fps.filter(|f| f.is_finite() && *f > 0.0) {
2088 out.extend_from_slice(format!("fps {fps:?}\n").as_bytes());
2089 }
2090 // Beside it, and by the same rule: a project nobody chose a sound rate for
2091 // is the mix the source's own probe always gave it, which is what leaving
2092 // this line out still means.
2093 if let Some(rate) = sample_rate.filter(|&r| (1_000..=384_000).contains(&r)) {
2094 out.extend_from_slice(format!("samplerate {rate}\n").as_bytes());
2095 }
2096 // Beside the rate, and written only when it is not the default: a project
2097 // holding no HDR media has nothing to say here, and saying nothing is what
2098 // a v10 file already said.
2099 if tone != crate::tonemap::Preset::default() {
2100 out.extend_from_slice(format!("tonemap {}\n", tone.name()).as_bytes());
2101 }
2102 // Beside it and by the same rule: a project cut on the films themselves --
2103 // every project before there were stand-ins -- says nothing here.
2104 if proxy {
2105 out.extend_from_slice(b"proxy on\n");
2106 }
2107 // Beside it and by the same rule the other way up: making them by itself is
2108 // what every project before this line did, so only a project told to stop
2109 // has anything to say here.
2110 if !auto_proxy {
2111 out.extend_from_slice(b"autoproxy off\n");
2112 }
2113 // ...and which encoder writes the picture, by the same rule again: `auto`
2114 // is what every project before this line did, so only a project whose owner
2115 // picked a seat says anything here.
2116 if encoder != crate::export::EncoderSeat::default() {
2117 out.extend_from_slice(format!("encoder {}\n", encoder.name()).as_bytes());
2118 }
2119 // Written only when it is not the default, so a project nobody has limited
2120 // is the same bytes it was in v8 bar the version line.
2121 if limiter != Limiter::default() {
2122 out.extend_from_slice(
2123 format!(
2124 "limiter {:?} {}\n",
2125 limiter.ceiling_db,
2126 match limiter.on {
2127 true => "on",
2128 false => "off",
2129 }
2130 )
2131 .as_bytes(),
2132 );
2133 }
2134 for s in sources {
2135 out.extend_from_slice(format!("source {} ", s.audio_stream).as_bytes());
2136 escape(&written_path(&s.path, dir), &mut out);
2137 out.push(b'\n');
2138 }
2139 // The subtitle tracks, by reference: which track of which file, and never
2140 // the cues (see the module docs). Beside the sources because that is what
2141 // they are -- a file this project reads from -- although nothing indexes
2142 // them and their order is only the order they were added in.
2143 for t in subtitles {
2144 let track = t.track.map_or("-".to_string(), |n| n.to_string());
2145 out.extend_from_slice(format!("subtitle {track} ").as_bytes());
2146 escape(&written_path(&t.path, dir), &mut out);
2147 out.push(b'\n');
2148 }
2149 // The language of each track that has one, as `sublang` lines after the
2150 // subtitle lines they name: a standalone file's is set by an import or a
2151 // retype, and an embedded track's is its container's until a retype
2152 // replaces it. Only a track with one is written, and the header only says
2153 // v33 when one is, so a project with none is written exactly as before.
2154 for (track, t) in subtitles.iter().enumerate() {
2155 if t.language.is_empty() {
2156 continue;
2157 }
2158 out.extend_from_slice(format!("sublang {track} ").as_bytes());
2159 escape_text(&t.language, &mut out);
2160 out.push(b'\n');
2161 }
2162 // Before the clips, for the reason the sources are: a clip names one by the
2163 // position of its line, so the line has to be there first.
2164 for params in eq {
2165 out.extend_from_slice(b"eq");
2166 for b in &params.bands {
2167 // `{:?}` rather than `{}`: it is the formatting that promises the
2168 // shortest string parsing back to this exact f32, and it never
2169 // prints a bare integer, which would read as another field's shape.
2170 let kind = match b.kind {
2171 BandKind::LowShelf => "ls",
2172 BandKind::Peak => "pk",
2173 BandKind::HighShelf => "hs",
2174 BandKind::LowCut => "lc",
2175 BandKind::HighCut => "hc",
2176 };
2177 out.extend_from_slice(
2178 format!(" {:?}:{:?}:{:?}:{kind}", b.freq_hz, b.gain_db, b.q).as_bytes(),
2179 );
2180 }
2181 out.push(b'\n');
2182 }
2183 // ...and the colour table, for the same reason and by the same rules.
2184 for p in color {
2185 out.extend_from_slice(
2186 format!(
2187 "color {:?}:{:?}:{:?}:{:?}\n",
2188 p.brightness, p.contrast, p.saturation, p.tint
2189 )
2190 .as_bytes(),
2191 );
2192 }
2193 // ...and the transform table, for the same reason and by the same rules.
2194 for p in transform {
2195 let mut line = format!(
2196 "transform {:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}:{:?}",
2197 p.pos_x, p.pos_y, p.scale, p.rotate, p.crop_l, p.crop_r, p.crop_t, p.crop_b
2198 );
2199 // The ninth field only where it says something: an opacity of 1 is the
2200 // eight-field line every dialect since v20 wrote.
2201 if p.opacity != 1.0 {
2202 line.push_str(&format!(":{:?}", p.opacity));
2203 }
2204 line.push('\n');
2205 out.extend_from_slice(line.as_bytes());
2206 }
2207 // Lane by lane rather than interleaved by time: a lane reads as a list, the
2208 // parser gets its sortedness check for free from the order it is in, and
2209 // the lanes come back out in the order they are displayed in.
2210 let (mut video, mut audio, mut subtitle) = (0, 0, 0);
2211 for (at, (kind, clips)) in lanes.iter().enumerate() {
2212 let (keyword, ord) = match kind {
2213 LaneKind::Video => {
2214 video += 1;
2215 ("video", video)
2216 }
2217 LaneKind::Audio => {
2218 audio += 1;
2219 ("audio", audio)
2220 }
2221 LaneKind::Subtitle => {
2222 subtitle += 1;
2223 ("sub", subtitle)
2224 }
2225 };
2226 // A subtitle lane holds no `Clip` at all ([`LaneKind::Subtitle`]): what
2227 // is on it is in `subs`, one list per lane and in step with this one,
2228 // and it is written here so the lane comes back in its place among the
2229 // others.
2230 if *kind == LaneKind::Subtitle {
2231 let placed = subs.get(at).map_or(&[][..], Vec::as_slice);
2232 if placed.is_empty() {
2233 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
2234 }
2235 for s in placed {
2236 // The group field only when the caption is in one, for the
2237 // clip line's reason: a project nobody grouped a caption in is
2238 // the same bytes it was in v15.
2239 let link = s.link.map_or(String::new(), |l| format!(" {l}"));
2240 out.extend_from_slice(
2241 format!(
2242 "{keyword} {ord} {} {} {} {} {}{link}\n",
2243 s.start, s.frames, s.track, s.in_us, s.out_us
2244 )
2245 .as_bytes(),
2246 );
2247 }
2248 continue;
2249 }
2250 // A lane is declared by its clips; one holding nothing has to say so on
2251 // a line of its own, or the lane itself would not survive the round trip.
2252 if clips.is_empty() {
2253 out.extend_from_slice(format!("{keyword} {ord}\n").as_bytes());
2254 }
2255 for c in clips {
2256 let link = c.link.map_or("-".to_string(), |l| l.to_string());
2257 let eq = c.eq.map_or("-".to_string(), |e| e.to_string());
2258 let color = c.color.map_or("-".to_string(), |e| e.to_string());
2259 let transform = c.transform.map_or("-".to_string(), |e| e.to_string());
2260 out.extend_from_slice(
2261 format!(
2262 "{keyword} {ord} {} {} {} {} {link} {eq} {color} {} {} {} {} {} {transform} {} {}\n",
2263 c.start,
2264 c.in_frame,
2265 c.out_frame,
2266 c.source,
2267 fit_name(c.fit),
2268 c.speed.permille(),
2269 c.fade_in,
2270 c.fade_out,
2271 c.transition_out,
2272 c.visualizer,
2273 c.viz_paint,
2274 )
2275 .as_bytes(),
2276 );
2277 }
2278 }
2279 // After the lanes, not before them: a gain line names a lane that has to be
2280 // there already, and a lane is declared by its own lines. Only the lanes
2281 // somebody has turned get one.
2282 let (mut video, mut audio) = (0, 0);
2283 for ((kind, _), &db) in lanes.iter().zip(gains) {
2284 let (keyword, ord) = match kind {
2285 LaneKind::Video => {
2286 video += 1;
2287 ("video", video)
2288 }
2289 LaneKind::Audio => {
2290 audio += 1;
2291 ("audio", audio)
2292 }
2293 // In the list -- the two are zipped, so it has to be -- and never
2294 // written: a subtitle lane has no volume at all
2295 // (`Project::set_lane_gain_db` refuses one), so its entry is the
2296 // `0.0` no lane writes a line for.
2297 LaneKind::Subtitle => continue,
2298 };
2299 if db != 0.0 {
2300 out.extend_from_slice(format!("gain {keyword} {ord} {db:?}\n").as_bytes());
2301 }
2302 }
2303 out
2304}
2305
2306fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
2307 // One trailing newline is the line terminator of the last line, not an
2308 // empty line -- any further one is, and is refused below.
2309 let body = data.strip_suffix(b"\n").unwrap_or(data);
2310 let mut lines = body.split(|&b| b == b'\n').enumerate();
2311 let (_, first) = lines.next().unwrap_or((0, &[]));
2312 let v1 = first == MAGIC_V1;
2313 // The dialects that wrote a source line without its stream field. Reading
2314 // one is the whole of what "an old project still opens" means here.
2315 let streamless = v1 || first == MAGIC_V2;
2316 // The one that carries a clip's volume envelope, as `gainkeys` lines...
2317 // The one that lets a lane be ducked under several keys, as several `duck`
2318 // lines naming one lane; a v29 reader refuses it by name.
2319 // The one that carries a transform's opacity, as a ninth field on a
2320 // `transform` line; a v30 reader refuses it by its field count.
2321 // The one that carries a clip's placement animation, as `tkeys` lines...
2322 // The one that carries a clip's stabilisation, as `stab` lines...
2323 // The one that carries a clip's pitch shift, as `pitch` lines...
2324 let v58 = first == MAGIC;
2325 let v57 = v58 || first == MAGIC_V57;
2326 let v56 = v57 || first == MAGIC_V56;
2327 let v55 = v56 || first == MAGIC_V55;
2328 let v54 = v55 || first == MAGIC_V54;
2329 let v53 = v54 || first == MAGIC_V53;
2330 let v52 = v53 || first == MAGIC_V52;
2331 let v51 = v52 || first == MAGIC_V51;
2332 let v50 = v51 || first == MAGIC_V50;
2333 let v49 = v50 || first == MAGIC_V49;
2334 let v48 = v49 || first == MAGIC_V48;
2335 let v47 = v48 || first == MAGIC_V47;
2336 let v46 = v47 || first == MAGIC_V46;
2337 let v45 = v46 || first == MAGIC_V45;
2338 let v44 = v45 || first == MAGIC_V44;
2339 let v43 = v44 || first == MAGIC_V43;
2340 let v42 = v43 || first == MAGIC_V42;
2341 let v41 = v42 || first == MAGIC_V41;
2342 let v40 = v41 || first == MAGIC_V40;
2343 let v39 = v40 || first == MAGIC_V39;
2344 let v38 = v39 || first == MAGIC_V38;
2345 let v37 = v38 || first == MAGIC_V37;
2346 let v36 = v37 || first == MAGIC_V36;
2347 let v35 = v36 || first == MAGIC_V35;
2348 let v34 = v35 || first == MAGIC_V34;
2349 let v33 = v34 || first == MAGIC_V33;
2350 let v32 = v33 || first == MAGIC_V32;
2351 let v31 = v32 || first == MAGIC_V31;
2352 let v30 = v31 || first == MAGIC_V30;
2353 let v29 = v30 || first == MAGIC_V29;
2354 let v28 = v29 || first == MAGIC_V28;
2355 // The one that carries a clip's own gain in dB, as `clipgain` lines...
2356 let v27 = v28 || first == MAGIC_V27;
2357 // The one that carries the title cards and text overlays...
2358 let v26 = v27 || first == MAGIC_V26;
2359 // The one that says which lanes are ducked under which...
2360 let v25 = v26 || first == MAGIC_V25;
2361 // The one that says which lanes are hidden, muted or locked...
2362 let v24 = v25 || first == MAGIC_V24;
2363 // The one that carries a strand colour of its own above the packed
2364 // visualizer paint (hue/sat, with the top bit as the flag)...
2365 let v23 = v24 || first == MAGIC_V23;
2366 // The one that carries packed visualizer paint (hue/sat/strands/glow)...
2367 let v22 = v23 || first == MAGIC_V22;
2368 // The one that carries per-clip visualizer flags...
2369 let v21 = v22 || first == MAGIC_V21;
2370 // The one that carries a per-clip transform (position/scale/rotate/crop)...
2371 let v20 = v21 || first == MAGIC_V20;
2372 // ...the one that carries a per-clip cross-dissolve into its successor...
2373 let v19 = v20 || first == MAGIC_V19;
2374 // ...the one that carries a per-clip fade envelope...
2375 let v18 = v19 || first == MAGIC_V18;
2376 // ...the one that carries an explicit sound rate...
2377 let v17 = v18 || first == MAGIC_V17;
2378 // ...the one whose captions may carry a group id...
2379 let v16 = v17 || first == MAGIC_V16;
2380 // ...the one that places the words it names...
2381 let v15 = v16 || first == MAGIC_V15;
2382 // ...the ones that say which encoder an export takes...
2383 let v14 = v15 || first == MAGIC_V14;
2384 // ...the ones that say whether the stand-ins are made by themselves...
2385 let v13 = v14 || first == MAGIC_V13;
2386 // ...the ones that say whether it is cut on stand-ins...
2387 let v12 = v13 || first == MAGIC_V12;
2388 // ...the ones that carry an HDR rendition...
2389 let v11 = v12 || first == MAGIC_V11;
2390 // ...the ones that carry subtitle tracks...
2391 let v10 = v11 || first == MAGIC_V10;
2392 // ...the ones that carry the mix -- lane volumes, the master limiter and
2393 // the rate the timeline was cut at...
2394 let v9 = v10 || first == MAGIC_V9;
2395 // ...the ones that carry a per-clip speed...
2396 let v8 = v9 || first == MAGIC_V8;
2397 // ...the ones that carry a project resolution and per-clip fit policies...
2398 let v7 = v8 || first == MAGIC_V7;
2399 // ...the ones that carry colour grades...
2400 let v6 = v7 || first == MAGIC_V6;
2401 // ...the ones that carry equalizer settings...
2402 let v5 = v6 || first == MAGIC_V5;
2403 // ...and the ones that number their lanes. Every older one held two.
2404 let numbered = v5 || first == MAGIC_V4;
2405 if !numbered && !streamless && first != MAGIC_V3 {
2406 return Err(match first.strip_prefix(b"edith ") {
2407 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
2408 None => "line 1: not an edith file".to_string(),
2409 }
2410 .into());
2411 }
2412
2413 let mut doc = Document {
2414 sources: Vec::new(),
2415 // v4 on declares its lanes as they come; every dialect before it held
2416 // exactly `V1` and `A1`, either of which could be empty.
2417 lanes: if numbered {
2418 Vec::new()
2419 } else {
2420 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
2421 },
2422 // Resized to the lanes as they arrive, and once more at the end, so a
2423 // caller may zip the two exactly as it zips the gains. Nothing before
2424 // v15 places a word anywhere: those projects have the palette and no
2425 // subtitle lane to put any of it on.
2426 subs: Vec::new(),
2427 // Nothing before v5 equalizes anything, and nothing before v6 grades.
2428 eq: Vec::new(),
2429 color: Vec::new(),
2430 // Nothing before v20 places any clip anywhere but its fit policy's own
2431 // spot: the identity transform is what leaving a clip's index out
2432 // still means.
2433 transform: Vec::new(),
2434 // Nothing before v7 has a resolution of its own: source 0's picture is
2435 // what those projects were, and `None` is how the loader is told so.
2436 resolution: None,
2437 // ...and nothing before v9 carries a mix or a rate: every lane at unity,
2438 // no limiter, and the rate inferred from the scaffold as it always was.
2439 gains: Vec::new(),
2440 // Nothing before v24 could hide, mute or lock a lane: every lane is
2441 // showing, audible and unlocked, which is what leaving a line out means.
2442 flags: Vec::new(),
2443 // Nothing before v25 ducks a lane under another: every lane plays at
2444 // its own level, which is what leaving a line out means.
2445 ducks: Vec::new(),
2446 titles: Vec::new(),
2447 chapters: Vec::new(),
2448 markers: Vec::new(),
2449 caption_style: CaptionStyle::default(),
2450 voices: Vec::new(),
2451 names: Vec::new(),
2452 // Nothing before v10 shows a subtitle, and nothing before v11 was shown
2453 // in any rendition but the published one.
2454 subtitles: Vec::new(),
2455 sub_langs: Vec::new(),
2456 cue_edits: Vec::new(),
2457 cue_adds: Vec::new(),
2458 cue_words: Vec::new(),
2459 limiter: Limiter::default(),
2460 tone: crate::tonemap::Preset::default(),
2461 proxy: false,
2462 // ...and nothing before v13 could be told *not* to make one: an import
2463 // that wanted a stand-in got one, which is what leaving the line out
2464 // still means.
2465 auto_proxy: true,
2466 // ...and nothing before v14 could be told *which* encoder: an export
2467 // took the seat this machine had, which is what leaving the line out
2468 // still means.
2469 encoder: crate::export::EncoderSeat::default(),
2470 fps: None,
2471 // Nothing before v17 chose a sound rate: the source's own probe is
2472 // still what the mix is cut at, which is what `None` means everywhere
2473 // else it reaches (`PlaybackSession::open_project`).
2474 sample_rate: None,
2475 playhead: 0,
2476 seq_active: None,
2477 seq_order: Vec::new(),
2478 sequences: Vec::new(),
2479 mcams: Vec::new(),
2480 bins: Vec::new(),
2481 notes: String::new(),
2482 still_secs: None,
2483 speech_model: None,
2484 speech_device: crate::speech::DeviceChoice::Auto,
2485 };
2486 // The block of a parked sequence being read: its id, name and the lines so far.
2487 let mut block: Option<(u32, String, Vec<u8>)> = None;
2488 let mut playhead_seen = false;
2489 // Where the next v1 clip is placed: that dialect had no `start` field, the
2490 // clips simply queued up.
2491 let mut queued = 0u32;
2492 for (i, line) in lines {
2493 let n = i + 1;
2494 let (keyword, rest) = match line.iter().position(|&b| b == b' ') {
2495 Some(at) => (&line[..at], &line[at + 1..]),
2496 None => (line, &line[line.len()..]),
2497 };
2498 if let Some((id, name, buf)) = block.as_mut() {
2499 if line == b"endseq" {
2500 if doc.sequences.len() >= MAX_SEQUENCES {
2501 return Err(format!("line {n}: a project holds at most {MAX_SEQUENCES} sequences").into());
2502 }
2503 let sub = parse(buf, dir).map_err(|e| format!("sequence \"{name}\": {e}"))?;
2504 doc.sequences.push(SeqDoc { id: *id, name: std::mem::take(name), doc: sub });
2505 block = None;
2506 } else {
2507 buf.extend_from_slice(line);
2508 buf.push(b'\n');
2509 }
2510 continue;
2511 }
2512 match keyword {
2513 b"seqactive" if v45 => {
2514 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
2515 let id = number(id, n)?;
2516 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
2517 doc.seq_active = Some((id, name));
2518 }
2519 b"seqorder" if v45 => {
2520 for f in rest.split(|&b| b == b' ').filter(|f| !f.is_empty()) {
2521 if doc.seq_order.len() >= MAX_SEQUENCES {
2522 return Err(format!("line {n}: seqorder names more than {MAX_SEQUENCES} sequences").into());
2523 }
2524 doc.seq_order.push(number(f, n)?);
2525 }
2526 }
2527 b"seq" if v45 => {
2528 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
2529 let id = number(id, n)?;
2530 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
2531 block = Some((id, name, Vec::new()));
2532 }
2533 b"playhead" => {
2534 if playhead_seen || !doc.sources.is_empty() {
2535 return Err(
2536 format!("line {n}: playhead belongs once, before the sources").into(),
2537 );
2538 }
2539 doc.playhead = number(rest, n)?;
2540 playhead_seen = true;
2541 }
2542 b"resolution" if v7 => {
2543 if doc.resolution.is_some() || !doc.sources.is_empty() {
2544 return Err(
2545 format!("line {n}: resolution belongs once, before the sources").into(),
2546 );
2547 }
2548 let f = fields(rest, 2, "resolution", n)?;
2549 let (width, height) = (number(f[0], n)?, number(f[1], n)?);
2550 // The same bound the keystroke has (`crate::is_resolution`):
2551 // unbounded here, this line reached `open_black` and panicked
2552 // the open with a capacity overflow.
2553 if !crate::is_resolution(width, height) {
2554 return Err(format!("line {n}: {width}x{height} is not a picture").into());
2555 }
2556 doc.resolution = Some((width, height));
2557 }
2558 b"fps" if v9 => {
2559 if doc.fps.is_some() || !doc.sources.is_empty() {
2560 return Err(format!("line {n}: fps belongs once, before the sources").into());
2561 }
2562 let f = fields(rest, 1, "fps", n)?;
2563 let fps = std::str::from_utf8(f[0])
2564 .ok()
2565 .and_then(|s| s.parse::<f64>().ok())
2566 .filter(|f| f.is_finite() && *f > 0.0 && *f <= 1000.0)
2567 .ok_or_else(|| {
2568 format!(
2569 "line {n}: {:?} is not a frame rate",
2570 String::from_utf8_lossy(f[0])
2571 )
2572 })?;
2573 doc.fps = Some(fps);
2574 }
2575 b"samplerate" if v17 => {
2576 if doc.sample_rate.is_some() || !doc.sources.is_empty() {
2577 return Err(
2578 format!("line {n}: samplerate belongs once, before the sources").into(),
2579 );
2580 }
2581 let f = fields(rest, 1, "samplerate", n)?;
2582 let rate = number(f[0], n)?;
2583 if !(1_000..=384_000).contains(&rate) {
2584 return Err(format!("line {n}: {rate} Hz is not a sound rate").into());
2585 }
2586 doc.sample_rate = Some(rate);
2587 }
2588 b"tonemap" if v11 => {
2589 if !doc.sources.is_empty() {
2590 return Err(
2591 format!("line {n}: tonemap belongs once, before the sources").into(),
2592 );
2593 }
2594 let f = fields(rest, 1, "tonemap", n)?;
2595 doc.tone = crate::tonemap::Preset::from_name(f[0]).ok_or_else(|| {
2596 format!(
2597 "line {n}: {:?} is not a tone map",
2598 String::from_utf8_lossy(f[0])
2599 )
2600 })?;
2601 }
2602 b"proxy" if v12 => {
2603 if !doc.sources.is_empty() {
2604 return Err(format!("line {n}: proxy belongs once, before the sources").into());
2605 }
2606 let f = fields(rest, 1, "proxy", n)?;
2607 doc.proxy = match f[0] {
2608 b"on" => true,
2609 b"off" => false,
2610 other => {
2611 return Err(format!(
2612 "line {n}: proxy is on or off, not {:?}",
2613 String::from_utf8_lossy(other)
2614 )
2615 .into());
2616 }
2617 };
2618 }
2619 b"autoproxy" if v13 => {
2620 if !doc.sources.is_empty() {
2621 return Err(
2622 format!("line {n}: autoproxy belongs once, before the sources").into(),
2623 );
2624 }
2625 let f = fields(rest, 1, "autoproxy", n)?;
2626 doc.auto_proxy = match f[0] {
2627 b"on" => true,
2628 b"off" => false,
2629 other => {
2630 return Err(format!(
2631 "line {n}: autoproxy is on or off, not {:?}",
2632 String::from_utf8_lossy(other)
2633 )
2634 .into());
2635 }
2636 };
2637 }
2638 b"encoder" if v14 => {
2639 if !doc.sources.is_empty() {
2640 return Err(
2641 format!("line {n}: encoder belongs once, before the sources").into(),
2642 );
2643 }
2644 let f = fields(rest, 1, "encoder", n)?;
2645 doc.encoder = crate::export::EncoderSeat::from_name(f[0]).ok_or_else(|| {
2646 format!(
2647 "line {n}: encoder is auto, hardware or software, not {:?}",
2648 String::from_utf8_lossy(f[0])
2649 )
2650 })?;
2651 }
2652 b"limiter" if v9 => {
2653 if !doc.sources.is_empty() {
2654 return Err(
2655 format!("line {n}: limiter belongs once, before the sources").into(),
2656 );
2657 }
2658 let f = fields(rest, 2, "limiter", n)?;
2659 let on = match f[1] {
2660 b"on" => true,
2661 b"off" => false,
2662 other => {
2663 return Err(format!(
2664 "line {n}: limiter is on or off, not {:?}",
2665 String::from_utf8_lossy(other)
2666 )
2667 .into());
2668 }
2669 };
2670 // Through the same clamp a nudge goes through: a hand-written
2671 // ceiling above full scale is a ceiling that limits nothing.
2672 doc.limiter = Limiter {
2673 on,
2674 ..Limiter::default()
2675 }
2676 .with_ceiling(float(f[0], n)?);
2677 }
2678 // After the lanes it names, which is where `emit` writes it: a lane
2679 // is declared by its own lines, and a gain declares nothing.
2680 b"gain" if v9 => {
2681 let f = fields(rest, 3, "gain", n)?;
2682 let kind = match f[0] {
2683 b"video" => LaneKind::Video,
2684 b"audio" => LaneKind::Audio,
2685 other => {
2686 return Err(format!(
2687 "line {n}: gain names {:?}, not a lane kind",
2688 String::from_utf8_lossy(other)
2689 )
2690 .into());
2691 }
2692 };
2693 let ord = number(f[1], n)?;
2694 let at = doc
2695 .lanes
2696 .iter()
2697 .enumerate()
2698 .filter(|(_, (k, _))| *k == kind)
2699 .nth(ord.saturating_sub(1) as usize)
2700 .map(|(at, _)| at)
2701 .ok_or_else(|| format!("line {n}: gain names a lane that is not there"))?;
2702 doc.gains.resize(doc.lanes.len(), 0.0);
2703 doc.gains[at] = float(f[2], n)?;
2704 }
2705 // After the lanes, for the reason a gain is: it names one. A line
2706 // carries the switches that are set, in any order and each once, and
2707 // a switch the kind of lane cannot have is refused by name.
2708 // After the lanes, for the reason a gain is: it names one, and the key
2709 // it names is checked once the whole file is read.
2710 b"duck" if v25 => {
2711 let f = fields(rest, 7, "duck", n)?;
2712 if f[0] != b"audio" {
2713 return Err(format!(
2714 "line {n}: duck names {:?}, not an audio lane",
2715 String::from_utf8_lossy(f[0])
2716 )
2717 .into());
2718 }
2719 let ord = number(f[1], n)?;
2720 let at = doc
2721 .lanes
2722 .iter()
2723 .enumerate()
2724 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2725 .nth(ord.saturating_sub(1) as usize)
2726 .map(|(at, _)| at)
2727 .ok_or_else(|| format!("line {n}: duck names a lane that is not there"))?;
2728 // 1-based in the file, as a gain's lane is; 0-based in the struct.
2729 let under = number(f[2], n)?;
2730 let duck = Duck {
2731 under: under.checked_sub(1).ok_or_else(|| {
2732 format!("line {n}: duck names audio lane 0, and lanes count from 1")
2733 })? as usize,
2734 depth_db: float(f[3], n)?,
2735 threshold_db: float(f[4], n)?,
2736 attack_ms: float(f[5], n)?,
2737 release_ms: float(f[6], n)?,
2738 };
2739 let in_range = (MIN_DEPTH_DB..=MAX_DEPTH_DB).contains(&duck.depth_db)
2740 && (MIN_THRESHOLD_DB..=MAX_THRESHOLD_DB).contains(&duck.threshold_db)
2741 && duck.attack_ms >= MIN_TIME_MS
2742 && duck.attack_ms <= MAX_ATTACK_MS
2743 && duck.release_ms >= MIN_TIME_MS
2744 && duck.release_ms <= MAX_RELEASE_MS;
2745 if !in_range {
2746 return Err(format!("line {n}: duck has a number out of its range").into());
2747 }
2748 doc.ducks.resize(doc.lanes.len(), Vec::new());
2749 // Several keys for one lane are a v30 dialect; before it a lane
2750 // had one duck, and a second line for it is a file that says
2751 // something its dialect cannot.
2752 if !v30 && !doc.ducks[at].is_empty() {
2753 return Err(format!("line {n}: duck names a lane twice").into());
2754 }
2755 if doc.ducks[at].iter().any(|d| d.under == duck.under) {
2756 return Err(format!("line {n}: duck names the same key twice").into());
2757 }
2758 doc.ducks[at].push(duck);
2759 }
2760 b"voice" if v41 => parse_voice(rest, n, &mut doc)?,
2761 b"effect" if v42 => parse_effect(rest, n, &mut doc)?,
2762 b"wheels" | b"curve" | b"lut" if v43 => parse_look(keyword, rest, n, dir, &mut doc)?,
2763 // After the lanes, which is where `clip_gain_lines` writes it: a line
2764 // names a clip, and a clip is declared by its lane's lines. Only audio
2765 // clips take one, the setter's own rule.
2766 b"lanepan" | b"clippan" if v50 => {
2767 let clip = keyword == b"clippan";
2768 let f = fields(rest, if clip { 4 } else { 3 }, if clip { "clippan" } else { "lanepan" }, n)?;
2769 if f[0] != b"audio" {
2770 return Err(format!("line {n}: pan names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
2771 }
2772 let ord = number(f[1], n)?;
2773 let at = doc
2774 .lanes
2775 .iter()
2776 .enumerate()
2777 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2778 .nth(ord.saturating_sub(1) as usize)
2779 .map(|(at, _)| at)
2780 .ok_or_else(|| format!("line {n}: pan names a lane that is not there"))?;
2781 let pan = float(f[if clip { 3 } else { 2 }], n)?;
2782 if !(-1.0..=1.0).contains(&pan) {
2783 return Err(format!("line {n}: pan has a number out of its range").into());
2784 }
2785 if clip {
2786 let idx = number(f[2], n)? as usize;
2787 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;
2788 } else {
2789 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
2790 doc.flags[at].pan = pan;
2791 }
2792 }
2793 // After the lanes, which is where `pitch_lines` writes it, as `clippan` is.
2794 b"pitch" if v55 => {
2795 let f = fields(rest, 4, "pitch", n)?;
2796 if f[0] != b"audio" {
2797 return Err(format!("line {n}: pitch names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
2798 }
2799 let ord = number(f[1], n)?;
2800 let at = doc
2801 .lanes
2802 .iter()
2803 .enumerate()
2804 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2805 .nth(ord.saturating_sub(1) as usize)
2806 .map(|(at, _)| at)
2807 .ok_or_else(|| format!("line {n}: pitch names a lane that is not there"))?;
2808 let idx = number(f[2], n)? as usize;
2809 let semitones = std::str::from_utf8(f[3]).ok().and_then(|s| s.parse::<f32>().ok());
2810 let semitones = match semitones {
2811 Some(v) if (crate::project::MIN_CLIP_PITCH..=crate::project::MAX_CLIP_PITCH).contains(&v) && (v58 || v.fract() == 0.0) => v,
2812 _ => return Err(format!("line {n}: pitch has a number out of its range").into()),
2813 };
2814 doc.lanes[at]
2815 .1
2816 .get_mut(idx)
2817 .ok_or_else(|| format!("line {n}: pitch names clip {idx}, which the lane does not have"))?
2818 .pitch = semitones;
2819 }
2820 b"clipgain" if v27 => {
2821 let f = fields(rest, 4, "clipgain", n)?;
2822 if f[0] != b"audio" {
2823 return Err(format!(
2824 "line {n}: clipgain names {:?}, not an audio lane",
2825 String::from_utf8_lossy(f[0])
2826 )
2827 .into());
2828 }
2829 let ord = number(f[1], n)?;
2830 let at = doc
2831 .lanes
2832 .iter()
2833 .enumerate()
2834 .filter(|(_, (k, _))| *k == LaneKind::Audio)
2835 .nth(ord.saturating_sub(1) as usize)
2836 .map(|(at, _)| at)
2837 .ok_or_else(|| format!("line {n}: clipgain names a lane that is not there"))?;
2838 let idx = number(f[2], n)? as usize;
2839 let db = float(f[3], n)?;
2840 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&db) {
2841 return Err(format!("line {n}: clipgain has a number out of its range").into());
2842 }
2843 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2844 format!("line {n}: clipgain names clip {idx}, which the lane does not have")
2845 })?;
2846 clip.gain_db = db;
2847 }
2848 // After the lanes, which is where `tkey_lines` writes it: a placement
2849 // key is source-ordered and unique by source frame, at most
2850 // `MAX_TRANSFORM_KEYS` of them, each a finite placement with an opacity
2851 // in `0..=1`. Only a video clip can carry them.
2852 b"tkeys" if v32 => {
2853 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2854 if f.len() < 4 {
2855 return Err(format!("line {n}: tkeys wants a clip and a key").into());
2856 }
2857 let lane_kind = match f[0] {
2858 b"video" => LaneKind::Video,
2859 other => {
2860 return Err(format!(
2861 "line {n}: tkeys names {:?}, not a video lane",
2862 String::from_utf8_lossy(other)
2863 )
2864 .into())
2865 }
2866 };
2867 let ord = number(f[1], n)?;
2868 let at = doc
2869 .lanes
2870 .iter()
2871 .enumerate()
2872 .filter(|(_, (k, _))| *k == lane_kind)
2873 .nth(ord.saturating_sub(1) as usize)
2874 .map(|(at, _)| at)
2875 .ok_or_else(|| format!("line {n}: tkeys names a lane that is not there"))?;
2876 let idx = number(f[2], n)? as usize;
2877 let points = &f[3..];
2878 if points.len() > MAX_TRANSFORM_KEYS {
2879 return Err(
2880 format!("line {n}: tkeys has more than {MAX_TRANSFORM_KEYS} keys").into(),
2881 );
2882 }
2883 let mut keys: Vec<TransformKey> = Vec::with_capacity(points.len());
2884 for point in points {
2885 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
2886 if parts.len() != 3 {
2887 return Err(format!("line {n}: tkeys key wants at:ease:values").into());
2888 }
2889 let ease = KeyEase::from_token(parts[1])
2890 .filter(|e| v39 || matches!(e, KeyEase::Linear | KeyEase::Ease))
2891 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
2892 .ok_or_else(|| format!("line {n}: tkeys ease is lin, in, out, ease or hold"))?;
2893 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
2894 if v.len() != 9 {
2895 return Err(format!("line {n}: tkeys key wants 9 values").into());
2896 }
2897 let params = TransformParams {
2898 pos_x: float(v[0], n)?,
2899 pos_y: float(v[1], n)?,
2900 scale: float(v[2], n)?,
2901 rotate: float(v[3], n)?,
2902 crop_l: float(v[4], n)?,
2903 crop_r: float(v[5], n)?,
2904 crop_t: float(v[6], n)?,
2905 crop_b: float(v[7], n)?,
2906 opacity: float(v[8], n)?,
2907 };
2908 if !(0.0..=1.0).contains(&params.opacity) {
2909 return Err(format!("line {n}: tkeys opacity must be 0..=1").into());
2910 }
2911 let key = TransformKey {
2912 at: number(parts[0], n)?,
2913 params,
2914 ease,
2915 };
2916 if keys.last().is_some_and(|k| k.at >= key.at) {
2917 return Err(
2918 format!("line {n}: tkeys keys are not in source order").into()
2919 );
2920 }
2921 keys.push(key);
2922 }
2923 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2924 format!("line {n}: tkeys names clip {idx}, which the lane does not have")
2925 })?;
2926 clip.transform_keys = keys;
2927 }
2928 // After the lanes, which is where `opacity_key_lines` and `color_key_lines`
2929 // write them: a video clip's opacity (`0..=1`) and colour animation,
2930 // source-ordered and unique by source frame, at most `MAX_TRANSFORM_KEYS`
2931 // and `MAX_COLOR_KEYS` of them, each in range.
2932 // A stabilised video clip, named as an `okeys` line names its clip.
2933 b"deint" if v46 => {
2934 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2935 if f.len() != 4 || f[0] != b"video" {
2936 return Err(format!("line {n}: deint wants a video clip and a mode").into());
2937 }
2938 let ord = number(f[1], n)?;
2939 let at = doc
2940 .lanes
2941 .iter()
2942 .enumerate()
2943 .filter(|(_, (k, _))| *k == LaneKind::Video)
2944 .nth(ord.saturating_sub(1) as usize)
2945 .map(|(at, _)| at)
2946 .ok_or_else(|| format!("line {n}: deint names a lane that is not there"))?;
2947 let idx = number(f[2], n)? as usize;
2948 let mode = std::str::from_utf8(f[3])
2949 .ok()
2950 .and_then(Deinterlace::from_name)
2951 .ok_or_else(|| format!("line {n}: deint mode must be frame, field or off"))?;
2952 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
2953 format!("line {n}: deint names clip {idx}, which the lane does not have")
2954 })?;
2955 clip.deinterlace = mode;
2956 }
2957 b"lanename" if v46 => {
2958 let mut parts = rest.splitn(3, |&b| b == b' ');
2959 let kind = match parts.next().unwrap_or_default() {
2960 b"video" => LaneKind::Video,
2961 b"audio" => LaneKind::Audio,
2962 b"sub" => LaneKind::Subtitle,
2963 other => {
2964 return Err(format!("line {n}: lanename names {:?}, not a lane kind", String::from_utf8_lossy(other)).into());
2965 }
2966 };
2967 let ord = number(parts.next().unwrap_or_default(), n)?;
2968 let at = doc
2969 .lanes
2970 .iter()
2971 .enumerate()
2972 .filter(|(_, (k, _))| *k == kind)
2973 .nth(ord.saturating_sub(1) as usize)
2974 .map(|(at, _)| at)
2975 .ok_or_else(|| format!("line {n}: lanename names a lane that is not there"))?;
2976 let name = unescape_text(parts.next().unwrap_or_default(), n)?;
2977 if name.is_empty() || name.chars().count() > crate::project::MAX_LANE_NAME_CHARS || name.chars().any(char::is_control) {
2978 return Err(format!("line {n}: a lane name is 1 to {} characters", crate::project::MAX_LANE_NAME_CHARS).into());
2979 }
2980 doc.names.resize(doc.lanes.len(), String::new());
2981 doc.names[at] = name;
2982 }
2983 b"stab" if v44 => {
2984 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
2985 if f.len() != 5 || f[0] != b"video" {
2986 return Err(format!("line {n}: stab wants a video clip, a strength and a crop").into());
2987 }
2988 let ord = number(f[1], n)?;
2989 let at = doc
2990 .lanes
2991 .iter()
2992 .enumerate()
2993 .filter(|(_, (k, _))| *k == LaneKind::Video)
2994 .nth(ord.saturating_sub(1) as usize)
2995 .map(|(at, _)| at)
2996 .ok_or_else(|| format!("line {n}: stab names a lane that is not there"))?;
2997 let idx = number(f[2], n)? as usize;
2998 let strength = std::str::from_utf8(f[3])
2999 .ok()
3000 .and_then(|v| v.parse::<f32>().ok())
3001 .filter(|v| (0.0..=1.0).contains(v))
3002 .ok_or_else(|| format!("line {n}: stab strength must be a number from 0 to 1"))?;
3003 let crop = std::str::from_utf8(f[4])
3004 .ok()
3005 .and_then(crate::stabilise::Crop::from_name)
3006 .ok_or_else(|| format!("line {n}: stab crop must be zoom or full"))?;
3007 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3008 format!("line {n}: stab names clip {idx}, which the lane does not have")
3009 })?;
3010 clip.stabilise = Some(crate::stabilise::Stabilise::new(strength, crop));
3011 }
3012 // A v53 mask's keys: five values, the mask's invert stays at its static value.
3013 b"mkeys" if v53 => {
3014 use crate::effects::EffectKind;
3015 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3016 if f.len() < 5 || f[0] != b"video" {
3017 return Err(format!("line {n}: mkeys wants a video clip, a slot and a key").into());
3018 }
3019 let ord = number(f[1], n)?;
3020 let at = doc
3021 .lanes
3022 .iter()
3023 .enumerate()
3024 .filter(|(_, (k, _))| *k == LaneKind::Video)
3025 .nth(ord.saturating_sub(1) as usize)
3026 .map(|(at, _)| at)
3027 .ok_or_else(|| format!("line {n}: mkeys names a lane that is not there"))?;
3028 let idx = number(f[2], n)? as usize;
3029 let slot = number(f[3], n)? as usize;
3030 let clip = doc.lanes[at]
3031 .1
3032 .get_mut(idx)
3033 .ok_or_else(|| format!("line {n}: mkeys names clip {idx}, which the lane does not have"))?;
3034 let effect = clip
3035 .effects
3036 .get_mut(slot)
3037 .filter(|e| matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask))
3038 .ok_or_else(|| format!("line {n}: mkeys names an effect that is not a mask"))?;
3039 let invert = effect.values[5];
3040 let mut keys = read_effect_keys("mkeys", &f[4..], &EffectKind::RectMask.params()[..5], n, v56)?;
3041 for k in &mut keys {
3042 k.values[5] = invert;
3043 }
3044 effect.keys = keys;
3045 }
3046 b"ekeys" if v56 => {
3047 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3048 if f.len() < 4 || f[0] != b"video" {
3049 return Err(format!("line {n}: ekeys wants a video clip, a slot and a key").into());
3050 }
3051 let ord = number(f[1], n)?;
3052 let at = doc
3053 .lanes
3054 .iter()
3055 .enumerate()
3056 .filter(|(_, (k, _))| *k == LaneKind::Video)
3057 .nth(ord.saturating_sub(1) as usize)
3058 .map(|(at, _)| at)
3059 .ok_or_else(|| format!("line {n}: ekeys names a lane that is not there"))?;
3060 let idx = number(f[2], n)? as usize;
3061 let slot = number(f[3], n)? as usize;
3062 let clip = doc.lanes[at]
3063 .1
3064 .get_mut(idx)
3065 .ok_or_else(|| format!("line {n}: ekeys names clip {idx}, which the lane does not have"))?;
3066 let effect = clip
3067 .effects
3068 .get_mut(slot)
3069 .ok_or_else(|| format!("line {n}: ekeys names an effect the clip does not have"))?;
3070 let specs = effect.kind.params();
3071 let mut keys = read_effect_keys("ekeys", &f[4..], specs, n, v56)?;
3072 // A parameter that cannot be keyed (a switch or a choice) keeps its static value.
3073 for k in &mut keys {
3074 for (i, _) in specs.iter().enumerate().filter(|(_, s)| !s.keyable()) {
3075 k.values[i] = effect.values[i];
3076 }
3077 }
3078 effect.keys = keys;
3079 }
3080 b"okeys" | b"ckeys" if v39 => {
3081 let colour = keyword == b"ckeys";
3082 let name = if colour { "ckeys" } else { "okeys" };
3083 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3084 if f.len() < 4 || f[0] != b"video" {
3085 return Err(format!("line {n}: {name} wants a video clip and a key").into());
3086 }
3087 let ord = number(f[1], n)?;
3088 let at = doc
3089 .lanes
3090 .iter()
3091 .enumerate()
3092 .filter(|(_, (k, _))| *k == LaneKind::Video)
3093 .nth(ord.saturating_sub(1) as usize)
3094 .map(|(at, _)| at)
3095 .ok_or_else(|| format!("line {n}: {name} names a lane that is not there"))?;
3096 let idx = number(f[2], n)? as usize;
3097 let points = &f[3..];
3098 let cap = if colour { MAX_COLOR_KEYS } else { MAX_TRANSFORM_KEYS };
3099 if points.len() > cap {
3100 return Err(format!("line {n}: {name} has more than {cap} keys").into());
3101 }
3102 let mut okeys: Vec<OpacityKey> = Vec::new();
3103 let mut ckeys: Vec<ColorKey> = Vec::new();
3104 for point in points {
3105 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
3106 if parts.len() != 3 {
3107 return Err(format!("line {n}: {name} key wants at:ease:values").into());
3108 }
3109 let at_frame = number(parts[0], n)?;
3110 let ease = KeyEase::from_token(parts[1])
3111 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
3112 .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease or hold"))?;
3113 let last = if colour { ckeys.last().map(|k| k.at) } else { okeys.last().map(|k| k.at) };
3114 if last.is_some_and(|l| l >= at_frame) {
3115 return Err(format!("line {n}: {name} keys are not in source order").into());
3116 }
3117 if colour {
3118 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
3119 if v.len() != 4 {
3120 return Err(format!("line {n}: ckeys key wants 4 values").into());
3121 }
3122 let params = ColorParams {
3123 brightness: float(v[0], n)?,
3124 contrast: float(v[1], n)?,
3125 saturation: float(v[2], n)?,
3126 tint: float(v[3], n)?,
3127 ..Default::default()
3128 };
3129 if !((-1.0..=1.0).contains(&params.brightness)
3130 && (0.0..=2.0).contains(&params.contrast)
3131 && (0.0..=2.0).contains(&params.saturation)
3132 && (-1.0..=1.0).contains(&params.tint))
3133 {
3134 return Err(format!("line {n}: ckeys has a value out of its range").into());
3135 }
3136 ckeys.push(ColorKey { at: at_frame, params, ease });
3137 } else {
3138 let opacity = float(parts[2], n)?;
3139 if !(0.0..=1.0).contains(&opacity) {
3140 return Err(format!("line {n}: okeys opacity must be 0..=1").into());
3141 }
3142 okeys.push(OpacityKey { at: at_frame, opacity, ease });
3143 }
3144 }
3145 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3146 format!("line {n}: {name} names clip {idx}, which the lane does not have")
3147 })?;
3148 if colour {
3149 clip.color_keys = ckeys;
3150 } else {
3151 clip.opacity_keys = okeys;
3152 }
3153 }
3154 // After the lanes, which is where `gain_key_lines` writes it: a line
3155 // names a clip, and a clip is declared by its lane's lines. Its points
3156 // are source-ordered and unique by source frame, as the setters keep
3157 // them, and at most `MAX_GAIN_KEYS` of them, each in range.
3158 b"gainkeys" if v28 => {
3159 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3160 if f.len() < 4 {
3161 return Err(format!("line {n}: gainkeys wants a clip and a point").into());
3162 }
3163 let kind = match f[0] {
3164 b"audio" => LaneKind::Audio,
3165 b"video" => LaneKind::Video,
3166 other => {
3167 return Err(format!(
3168 "line {n}: gainkeys names {:?}, not a lane kind",
3169 String::from_utf8_lossy(other)
3170 )
3171 .into());
3172 }
3173 };
3174 let ord = number(f[1], n)?;
3175 let at = doc
3176 .lanes
3177 .iter()
3178 .enumerate()
3179 .filter(|(_, (k, _))| *k == kind)
3180 .nth(ord.saturating_sub(1) as usize)
3181 .map(|(at, _)| at)
3182 .ok_or_else(|| format!("line {n}: gainkeys names a lane that is not there"))?;
3183 let idx = number(f[2], n)? as usize;
3184 let points = &f[3..];
3185 if points.len() > MAX_GAIN_KEYS {
3186 return Err(
3187 format!("line {n}: gainkeys has more than {MAX_GAIN_KEYS} points").into(),
3188 );
3189 }
3190 let mut keys = Vec::with_capacity(points.len());
3191 for point in points {
3192 let colon = point
3193 .iter()
3194 .position(|&b| b == b':')
3195 .ok_or_else(|| format!("line {n}: gainkeys point wants at:db"))?;
3196 let (a, d) = (&point[..colon], &point[colon + 1..]);
3197 // A v39 point may end in the ease of the segment that leaves it.
3198 let (d, ease) = match d.iter().position(|&b| b == b':') {
3199 Some(c) if v39 => (
3200 &d[..c],
3201 KeyEase::from_token(&d[c + 1..])
3202 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
3203 .ok_or_else(|| format!("line {n}: gainkeys ease is lin, in, out, ease or hold"))?,
3204 ),
3205 _ => (d, KeyEase::Linear),
3206 };
3207 let key = GainKey {
3208 at: number(a, n)?,
3209 db: float(d, n)?,
3210 ease,
3211 };
3212 if !(MIN_CLIP_GAIN_DB..=MAX_CLIP_GAIN_DB).contains(&key.db) {
3213 return Err(format!("line {n}: gainkeys has a dB out of its range").into());
3214 }
3215 if keys.last().is_some_and(|k: &GainKey| k.at >= key.at) {
3216 return Err(
3217 format!("line {n}: gainkeys points are not in source order").into()
3218 );
3219 }
3220 keys.push(key);
3221 }
3222 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3223 format!("line {n}: gainkeys names clip {idx}, which the lane does not have")
3224 })?;
3225 clip.gain_keys = keys;
3226 }
3227 // After the lanes and the subtitle palette: a title names neither,
3228 // and its text is the rest of the line, so it is the ninth field.
3229 b"title" if v26 => {
3230 let f: Vec<&[u8]> = rest.splitn(9, |&b| b == b' ').collect();
3231 if f.len() != 9 {
3232 return Err(format!("line {n}: title wants 9 fields, found {}", f.len()).into());
3233 }
3234 let outline = match f[5] {
3235 b"none" => Outline::None,
3236 b"thin" => Outline::Thin,
3237 b"thick" => Outline::Thick,
3238 other => {
3239 return Err(format!(
3240 "line {n}: title outline {:?} is none, thin or thick",
3241 String::from_utf8_lossy(other)
3242 )
3243 .into());
3244 }
3245 };
3246 let boxed = match f[6] {
3247 b"0" => false,
3248 b"1" => true,
3249 other => {
3250 return Err(format!(
3251 "line {n}: title boxed {:?} is 0 or 1",
3252 String::from_utf8_lossy(other)
3253 )
3254 .into());
3255 }
3256 };
3257 let place = match f[7] {
3258 b"bottom" => Place::Bottom,
3259 b"top" => Place::Top,
3260 b"centre" => Place::Centre,
3261 other => {
3262 return Err(format!(
3263 "line {n}: title place {:?} is bottom, top or centre",
3264 String::from_utf8_lossy(other)
3265 )
3266 .into());
3267 }
3268 };
3269 let title = Title {
3270 start: number(f[0], n)?,
3271 frames: number(f[1], n)?,
3272 text: unescape_text(f[8], n)?,
3273 style: TextStyle {
3274 size: number(f[4], n)?,
3275 outline,
3276 boxed,
3277 place,
3278 ..TextStyle::default()
3279 },
3280 fade_in: number(f[2], n)?,
3281 fade_out: number(f[3], n)?,
3282 in_anim: TitleAnim::None,
3283 out_anim: TitleAnim::None,
3284 anim_frames: 0,
3285 keys: Vec::new(),
3286 };
3287 check_title(&title).map_err(|e| format!("line {n}: {e}"))?;
3288 doc.titles.push(title);
3289 }
3290 // A chapter is a frame and a name: the name is the rest of the line, escaped
3291 // as a `cue` line's is. Written in frame order, one per frame.
3292 // A clip's speed ramp, as `speedkeys` lines, after the lanes they name.
3293 // Its keys are clip-relative and sorted, at most `MAX_SPEED_KEYS` of them, each
3294 // speed in range; the clip's footprint grows with the ramp, so the lane is
3295 // checked again here, where the ramp lands.
3296 b"speedkeys" if v35 => {
3297 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3298 if f.len() < 4 {
3299 return Err(format!("line {n}: speedkeys wants a clip and a point").into());
3300 }
3301 let kind = match f[0] {
3302 b"audio" => LaneKind::Audio,
3303 b"video" => LaneKind::Video,
3304 other => {
3305 return Err(format!(
3306 "line {n}: speedkeys names {:?}, not a lane kind",
3307 String::from_utf8_lossy(other)
3308 )
3309 .into());
3310 }
3311 };
3312 let ord = number(f[1], n)?;
3313 let at = doc
3314 .lanes
3315 .iter()
3316 .enumerate()
3317 .filter(|(_, (k, _))| *k == kind)
3318 .nth(ord.saturating_sub(1) as usize)
3319 .map(|(at, _)| at)
3320 .ok_or_else(|| format!("line {n}: speedkeys names a lane that is not there"))?;
3321 let idx = number(f[2], n)? as usize;
3322 let points = &f[3..];
3323 if points.len() > MAX_SPEED_KEYS {
3324 return Err(format!("line {n}: speedkeys has more than {MAX_SPEED_KEYS} points").into());
3325 }
3326 let mut keys = Vec::with_capacity(points.len());
3327 for point in points {
3328 let colon = point
3329 .iter()
3330 .position(|&b| b == b':')
3331 .ok_or_else(|| format!("line {n}: speedkeys point wants at:permille"))?;
3332 let (a, p) = (&point[..colon], &point[colon + 1..]);
3333 let permille = number(p, n)?;
3334 if permille < u32::from(Speed::MIN.permille())
3335 || permille > u32::from(Speed::MAX.permille())
3336 {
3337 return Err(format!("line {n}: speedkeys speed {permille} is out of range").into());
3338 }
3339 let key = SpeedKey {
3340 at: number(a, n)?,
3341 speed: Speed::from_permille(permille as u16),
3342 };
3343 if keys.last().is_some_and(|k: &SpeedKey| k.at >= key.at) {
3344 return Err(format!("line {n}: speedkeys points are not in frame order").into());
3345 }
3346 keys.push(key);
3347 }
3348 let lane = &mut doc.lanes[at].1;
3349 let clip = lane.get_mut(idx).ok_or_else(|| {
3350 format!("line {n}: speedkeys names clip {idx}, which the lane does not have")
3351 })?;
3352 clip.speed_keys = keys;
3353 let end = clip.start.checked_add(clip.frames()).ok_or_else(|| {
3354 format!("line {n}: speed ramp runs past the last frame there is")
3355 })?;
3356 if lane.get(idx + 1).is_some_and(|next| next.start < end) {
3357 return Err(format!("line {n}: speed ramp runs into the next clip on its lane").into());
3358 }
3359 }
3360 // How a clip's transition is drawn, after the lanes it names.
3361 b"transition" if v37 => {
3362 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3363 if f.len() != 4 {
3364 return Err(format!("line {n}: transition wants a clip and a kind").into());
3365 }
3366 let kind = match f[0] {
3367 b"audio" => LaneKind::Audio,
3368 b"video" => LaneKind::Video,
3369 other => {
3370 return Err(format!(
3371 "line {n}: transition names {:?}, not a lane kind",
3372 String::from_utf8_lossy(other)
3373 )
3374 .into());
3375 }
3376 };
3377 let ord = number(f[1], n)?;
3378 let at = doc
3379 .lanes
3380 .iter()
3381 .enumerate()
3382 .filter(|(_, (k, _))| *k == kind)
3383 .nth(ord.saturating_sub(1) as usize)
3384 .map(|(at, _)| at)
3385 .ok_or_else(|| format!("line {n}: transition names a lane that is not there"))?;
3386 let idx = number(f[2], n)? as usize;
3387 let name = String::from_utf8_lossy(f[3]);
3388 let kind = TransitionKind::parse(&name)
3389 .ok_or_else(|| format!("line {n}: transition kind {name:?} is not one"))?;
3390 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3391 format!("line {n}: transition names clip {idx}, which the lane does not have")
3392 })?;
3393 clip.transition_kind = kind;
3394 }
3395 // A reversed clip: named like a `speedkeys` line names its clip. The
3396 // window, speed and ramp are the clip's own lines; this is the direction.
3397 b"reverse" if v38 => {
3398 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3399 if f.len() != 3 {
3400 return Err(format!("line {n}: reverse wants a lane and a clip").into());
3401 }
3402 let kind = match f[0] {
3403 b"audio" => LaneKind::Audio,
3404 b"video" => LaneKind::Video,
3405 other => {
3406 return Err(format!(
3407 "line {n}: reverse names {:?}, not a lane kind",
3408 String::from_utf8_lossy(other)
3409 )
3410 .into());
3411 }
3412 };
3413 let ord = number(f[1], n)?;
3414 let at = doc
3415 .lanes
3416 .iter()
3417 .enumerate()
3418 .filter(|(_, (k, _))| *k == kind)
3419 .nth(ord.saturating_sub(1) as usize)
3420 .map(|(at, _)| at)
3421 .ok_or_else(|| format!("line {n}: reverse names a lane that is not there"))?;
3422 let idx = number(f[2], n)? as usize;
3423 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3424 format!("line {n}: reverse names clip {idx}, which the lane does not have")
3425 })?;
3426 clip.reversed = true;
3427 }
3428 b"angle" if v47 => {
3429 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3430 if f.len() != 5 {
3431 return Err(format!("line {n}: angle wants a lane, a clip, a picture angle and a sound angle").into());
3432 }
3433 let kind = match f[0] {
3434 b"audio" => LaneKind::Audio,
3435 b"video" => LaneKind::Video,
3436 _ => return Err(format!("line {n}: angle names a lane kind that is not video or audio").into()),
3437 };
3438 let ord = number(f[1], n)?;
3439 let at = doc
3440 .lanes
3441 .iter()
3442 .enumerate()
3443 .filter(|(_, (k, _))| *k == kind)
3444 .nth(ord.saturating_sub(1) as usize)
3445 .map(|(at, _)| at)
3446 .ok_or_else(|| format!("line {n}: angle names a lane that is not there"))?;
3447 let idx = number(f[2], n)? as usize;
3448 let one_based = |f: &[u8]| -> crate::Result<u8> {
3449 let v = number(f, n)?;
3450 u8::try_from(v.wrapping_sub(1))
3451 .ok()
3452 .filter(|a| usize::from(*a) < crate::project::MAX_ANGLES)
3453 .ok_or_else(|| format!("line {n}: an angle is a number from 1 to {}", crate::project::MAX_ANGLES).into())
3454 };
3455 let video = one_based(f[3])?;
3456 let audio = if f[4] == b"-" { None } else { Some(one_based(f[4])?) };
3457 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3458 format!("line {n}: angle names clip {idx}, which the lane does not have")
3459 })?;
3460 clip.angle = crate::project::Angle { video, audio };
3461 }
3462 // A title's look: which title (by its position in the list), where its block sits,
3463 // how its lines line up, its weight, its colour and its box colour.
3464 b"titlestyle" if v49 => {
3465 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3466 if f.len() != 6 {
3467 return Err(format!("line {n}: titlestyle wants a title, a position, an alignment, a weight and two colours").into());
3468 }
3469 let idx = number(f[0], n)? as usize;
3470 let side = |b: &[u8], what: &str| -> crate::Result<u8> {
3471 match b {
3472 b"centre" => Ok(0),
3473 b"left" => Ok(1),
3474 b"right" => Ok(2),
3475 other => Err(format!("line {n}: title {what} {:?} is centre, left or right", String::from_utf8_lossy(other)).into()),
3476 }
3477 };
3478 let hplace = match side(f[1], "position")? {
3479 1 => HPlace::Left,
3480 2 => HPlace::Right,
3481 _ => HPlace::Centre,
3482 };
3483 let align = match side(f[2], "alignment")? {
3484 1 => Align::Left,
3485 2 => Align::Right,
3486 _ => Align::Centre,
3487 };
3488 let weight = match f[3] {
3489 b"regular" => Weight::Regular,
3490 b"bold" => Weight::Bold,
3491 other => return Err(format!("line {n}: title weight {:?} is regular or bold", String::from_utf8_lossy(other)).into()),
3492 };
3493 let hex = |b: &[u8], len: usize| -> crate::Result<Vec<u8>> {
3494 let ok = b.len() == len * 2 && b.iter().all(u8::is_ascii_hexdigit);
3495 if !ok {
3496 return Err(format!("line {n}: a title colour is {} hex digits", len * 2).into());
3497 }
3498 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())
3499 };
3500 let c = hex(f[4], 3)?;
3501 let bc = hex(f[5], 4)?;
3502 let title = doc
3503 .titles
3504 .get_mut(idx)
3505 .ok_or_else(|| format!("line {n}: titlestyle names title {idx}, which the file does not have"))?;
3506 title.style.hplace = hplace;
3507 title.style.align = align;
3508 title.style.weight = weight;
3509 title.style.ink = [c[0], c[1], c[2]];
3510 title.style.box_color = [bc[0], bc[1], bc[2], bc[3]];
3511 }
3512 // A title's entrance and exit: which title (by its place in the list), the two animations
3513 // and how many frames each takes.
3514 b"titleanim" if v54 => {
3515 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3516 if f.len() != 4 {
3517 return Err(format!("line {n}: titleanim wants a title, an entrance, an exit and a length").into());
3518 }
3519 let idx = number(f[0], n)? as usize;
3520 let anim = |b: &[u8]| {
3521 let name = String::from_utf8_lossy(b).into_owned();
3522 TitleAnim::from_name(&name).ok_or_else(|| format!("line {n}: title animation {name:?} is not one of the known ones"))
3523 };
3524 let (in_anim, out_anim) = (anim(f[1])?, anim(f[2])?);
3525 let anim_frames = number(f[3], n)?;
3526 let title = doc
3527 .titles
3528 .get_mut(idx)
3529 .ok_or_else(|| format!("line {n}: titleanim names title {idx}, which the file does not have"))?;
3530 title.in_anim = in_anim;
3531 title.out_anim = out_anim;
3532 title.anim_frames = anim_frames;
3533 check_title(title).map_err(|e| format!("line {n}: {e}"))?;
3534 }
3535 // A title's own keys (v56): the title by its place in the list, then each key as
3536 // `at:ease:x,y,scale,opacity`, in frame order. `check_title` holds the ranges and order.
3537 b"ttkeys" if v56 => {
3538 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').filter(|f| !f.is_empty()).collect();
3539 if f.is_empty() {
3540 return Err(format!("line {n}: ttkeys wants a title and its keys").into());
3541 }
3542 let idx = number(f[0], n)? as usize;
3543 let mut keys = Vec::with_capacity(f.len() - 1);
3544 for point in &f[1..] {
3545 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
3546 if parts.len() != 3 {
3547 return Err(format!("line {n}: ttkeys key wants at:ease:x,y,scale,opacity").into());
3548 }
3549 let at = number(parts[0], n)?;
3550 let ease = KeyEase::from_token(parts[1])
3551 .ok_or_else(|| format!("line {n}: ttkeys ease is lin, in, out, ease, hold or a bezier curve"))?;
3552 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
3553 if v.len() != 4 {
3554 return Err(format!("line {n}: ttkeys key wants 4 values").into());
3555 }
3556 let (x, y, scale, opacity) = (float(v[0], n)?, float(v[1], n)?, float(v[2], n)?, float(v[3], n)?);
3557 keys.push(TitleKey { at, x, y, scale, opacity, ease });
3558 }
3559 let title = doc
3560 .titles
3561 .get_mut(idx)
3562 .ok_or_else(|| format!("line {n}: ttkeys names title {idx}, which the file does not have"))?;
3563 title.keys = keys;
3564 check_title(title).map_err(|e| format!("line {n}: {e}"))?;
3565 }
3566 b"mark" if v48 => {
3567 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3568 if f.len() != 5 {
3569 return Err(format!("line {n}: mark wants a lane, a clip, a label and on or off").into());
3570 }
3571 let kind = match f[0] {
3572 b"audio" => LaneKind::Audio,
3573 b"video" => LaneKind::Video,
3574 _ => return Err(format!("line {n}: mark names a lane kind that is not video or audio").into()),
3575 };
3576 let ord = number(f[1], n)?;
3577 let at = doc
3578 .lanes
3579 .iter()
3580 .enumerate()
3581 .filter(|(_, (k, _))| *k == kind)
3582 .nth(ord.saturating_sub(1) as usize)
3583 .map(|(at, _)| at)
3584 .ok_or_else(|| format!("line {n}: mark names a lane that is not there"))?;
3585 let idx = number(f[2], n)? as usize;
3586 let label = u8::try_from(number(f[3], n)?)
3587 .ok()
3588 .filter(|l| *l <= crate::project::LABEL_COUNT)
3589 .ok_or_else(|| format!("line {n}: a label is a number from 0 to {}", crate::project::LABEL_COUNT))?;
3590 let off = match f[4] {
3591 b"on" => false,
3592 b"off" => true,
3593 _ => return Err(format!("line {n}: mark ends with on or off").into()),
3594 };
3595 let clip = doc.lanes[at].1.get_mut(idx).ok_or_else(|| {
3596 format!("line {n}: mark names clip {idx}, which the lane does not have")
3597 })?;
3598 clip.mark = crate::project::ClipMark { label, off };
3599 }
3600 // The library (v51): `bin <id> <parent> <name>`, then `srcbin <source> <bin>` and
3601 // `srcfav <source>` for the sources that are filed or starred.
3602 // The project notes (v52): one `notes` line, its text escaped as a cue's is, so a
3603 // note of several lines is one line in the file.
3604 b"notes" if v52 => {
3605 if !doc.notes.is_empty() {
3606 return Err(format!("line {n}: notes is given twice").into());
3607 }
3608 doc.notes = unescape_text(rest, n)?;
3609 }
3610 // The length a still is placed at (v52), in seconds, within the range the editor allows.
3611 b"still" if v52 => {
3612 let f = fields(rest, 1, "still", n)?;
3613 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"))?;
3614 if !(STILL_MIN_SECS..=STILL_MAX_SECS).contains(&secs) {
3615 return Err(format!("line {n}: a still is {STILL_MIN_SECS} to {STILL_MAX_SECS} s long, not {secs}").into());
3616 }
3617 doc.still_secs = Some(secs);
3618 }
3619 b"speech" if v57 => {
3620 let text = std::str::from_utf8(rest).map_err(|_| format!("line {n}: speech is not text"))?;
3621 let f: Vec<&str> = text.split(' ').collect();
3622 doc.speech_device = f
3623 .first()
3624 .and_then(|d| crate::speech::DeviceChoice::parse(d))
3625 .ok_or_else(|| format!("line {n}: speech wants a device, auto, cpu or gpu"))?;
3626 doc.speech_model = match f.get(1) {
3627 None => None,
3628 Some(m) if crate::speech::MODELS.contains(m) && f.len() == 2 => Some(m.to_string()),
3629 Some(m) => return Err(format!("line {n}: speech model `{m}` is not one of {}", crate::speech::MODELS.join(", ")).into()),
3630 };
3631 }
3632 b"bin" if v51 => {
3633 let f: Vec<&[u8]> = rest.splitn(3, |&b| b == b' ').collect();
3634 if f.len() != 3 {
3635 return Err(format!("line {n}: bin wants an id, a parent and a name").into());
3636 }
3637 let id = number(f[0], n)?;
3638 let parent = number(f[1], n)?;
3639 let name = unescape_text(f[2], n)?;
3640 if id == 0 || doc.bins.iter().any(|b| b.id == id) {
3641 return Err(format!("line {n}: bin {id} is not a new id").into());
3642 }
3643 if parent != 0 && !doc.bins.iter().any(|b| b.id == parent && b.parent == 0) {
3644 return Err(format!("line {n}: bin {id} is inside bin {parent}, which is not a top-level bin before it").into());
3645 }
3646 let name = crate::project::clean_bin_name(&name).map_err(|e| format!("line {n}: {e}"))?;
3647 if doc.bins.iter().any(|b| b.parent == parent && b.name.eq_ignore_ascii_case(&name)) {
3648 return Err(format!("line {n}: two bins named {name} in one place").into());
3649 }
3650 if doc.bins.len() >= crate::project::MAX_BINS {
3651 return Err(format!("line {n}: a project holds at most {} bins", crate::project::MAX_BINS).into());
3652 }
3653 doc.bins.push(crate::project::Bin { id, parent, name });
3654 }
3655 b"srcbin" if v51 => {
3656 let f = fields(rest, 2, "srcbin", n)?;
3657 let (src, bin) = (number(f[0], n)? as usize, number(f[1], n)?);
3658 if !doc.bins.iter().any(|b| b.id == bin) {
3659 return Err(format!("line {n}: srcbin names bin {bin}, which is not defined before it").into());
3660 }
3661 doc.sources
3662 .get_mut(src)
3663 .ok_or_else(|| format!("line {n}: srcbin names source {src}, which the file does not have"))?
3664 .bin = bin;
3665 }
3666 b"srcfav" if v51 => {
3667 let f = fields(rest, 1, "srcfav", n)?;
3668 let src = number(f[0], n)? as usize;
3669 doc.sources
3670 .get_mut(src)
3671 .ok_or_else(|| format!("line {n}: srcfav names source {src}, which the file does not have"))?
3672 .fav = true;
3673 }
3674 b"mcam" if v47 => {
3675 let (id, name) = rest.split_at(rest.iter().position(|&b| b == b' ').unwrap_or(rest.len()));
3676 let id = number(id, n)?;
3677 let name = unescape_text(name.strip_prefix(b" ").unwrap_or(name), n)?;
3678 doc.mcams.push((id, name));
3679 }
3680 b"chapter" if v34 => {
3681 let mut fields = rest.splitn(2, |&b| b == b' ');
3682 let frame = number(fields.next().unwrap_or_default(), n)?;
3683 let title = unescape_text(fields.next().unwrap_or_default(), n)?;
3684 let chapter = Chapter { frame, title };
3685 check_chapter(&chapter).map_err(|e| format!("line {n}: {e}"))?;
3686 if doc.chapters.last().is_some_and(|c| c.frame >= frame) {
3687 return Err(format!("line {n}: chapter at frame {frame} is not after the one before it").into());
3688 }
3689 if doc.chapters.len() >= MAX_LIST_ENTRIES {
3690 return Err(format!("line {n}: a project holds at most {MAX_LIST_ENTRIES} chapters").into());
3691 }
3692 doc.chapters.push(chapter);
3693 }
3694 b"marker" if v36 => {
3695 let f: Vec<&[u8]> = rest.splitn(4, |&b| b == b' ').collect();
3696 if f.len() < 4 {
3697 return Err(format!("line {n}: marker wants a frame, a length, a colour and a name").into());
3698 }
3699 let color = std::str::from_utf8(f[2])
3700 .ok()
3701 .and_then(MarkerColor::from_name)
3702 .ok_or_else(|| format!("line {n}: marker names {:?}, not a colour", String::from_utf8_lossy(f[2])))?;
3703 let marker = Marker {
3704 frame: number(f[0], n)?,
3705 length: number(f[1], n)?,
3706 name: unescape_text(f[3], n)?,
3707 note: String::new(),
3708 color,
3709 };
3710 check_marker(&marker).map_err(|e| format!("line {n}: {e}"))?;
3711 if doc.markers.last().is_some_and(|m| m.frame > marker.frame) {
3712 return Err(format!("line {n}: marker at frame {} is before the one above it", marker.frame).into());
3713 }
3714 if doc.markers.len() >= MAX_LIST_ENTRIES {
3715 return Err(format!("line {n}: a project holds at most {MAX_LIST_ENTRIES} markers").into());
3716 }
3717 doc.markers.push(marker);
3718 }
3719 b"cuewords" if v40 => {
3720 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
3721 if f.len() < 5 || !(f.len() - 2).is_multiple_of(3) {
3722 return Err(format!("line {n}: cuewords wants a track, a cue and whole (start, end, word) triples").into());
3723 }
3724 if (f.len() - 2) / 3 > MAX_CUE_WORDS {
3725 return Err(format!("line {n}: cuewords carries more than {MAX_CUE_WORDS} words").into());
3726 }
3727 let track = number(f[0], n)? as usize;
3728 if track >= doc.subtitles.len() {
3729 return Err(format!("line {n}: cuewords names subtitle track {track} of {}", doc.subtitles.len()).into());
3730 }
3731 let mut words = Vec::new();
3732 for w in f[2..].chunks(3) {
3733 let time = |b: &[u8]| -> crate::Result<i64> {
3734 std::str::from_utf8(b)
3735 .ok()
3736 .and_then(|t| t.parse::<i64>().ok())
3737 .ok_or_else(|| format!("line {n}: cuewords time is not a number").into())
3738 };
3739 words.push((time(w[0])?, time(w[1])?, unescape_text(w[2], n)?));
3740 }
3741 doc.cue_words.push((track, number(f[1], n)? as usize, words));
3742 }
3743 b"capstyle" if v40 => {
3744 let f: Vec<&str> = fields(rest, 5, "capstyle", n)?
3745 .into_iter()
3746 .map(|b| std::str::from_utf8(b).unwrap_or(""))
3747 .collect();
3748 let anim = CaptionAnim::from_name(f[0])
3749 .ok_or_else(|| format!("line {n}: capstyle names {:?}, not an animation", f[0]))?;
3750 let hex = f[1];
3751 let rgb = (hex.len() == 6)
3752 .then(|| u32::from_str_radix(hex, 16).ok())
3753 .flatten()
3754 .ok_or_else(|| format!("line {n}: capstyle colour {hex:?} is not six hex digits"))?;
3755 let flag = |s: &str| match s {
3756 "0" => Ok(false),
3757 "1" => Ok(true),
3758 other => Err(format!("line {n}: capstyle flag {other:?} is not 0 or 1")),
3759 };
3760 let words_per_line: u8 = f[4]
3761 .parse()
3762 .ok()
3763 .filter(|&w| w <= MAX_WORDS_PER_LINE)
3764 .ok_or_else(|| format!("line {n}: capstyle words per line {:?} is not 0 to {MAX_WORDS_PER_LINE}", f[4]))?;
3765 doc.caption_style = CaptionStyle {
3766 anim,
3767 highlight: [(rgb >> 16) as u8, (rgb >> 8) as u8, rgb as u8],
3768 hl_box: flag(f[2])?,
3769 uppercase: flag(f[3])?,
3770 words_per_line,
3771 };
3772 }
3773 b"marknote" if v36 => {
3774 let mut fields = rest.splitn(2, |&b| b == b' ');
3775 let idx = number(fields.next().unwrap_or_default(), n)? as usize;
3776 let note = unescape_text(fields.next().unwrap_or_default(), n)?;
3777 let marker = doc
3778 .markers
3779 .get_mut(idx)
3780 .ok_or_else(|| format!("line {n}: marknote names marker {idx}, which the file does not have"))?;
3781 marker.note = note;
3782 check_marker(marker).map_err(|e| format!("line {n}: {e}"))?;
3783 }
3784 b"flags" if v24 => {
3785 let mut words = rest.split(|&b| b == b' ');
3786 let kind = match words.next().unwrap_or_default() {
3787 b"video" => LaneKind::Video,
3788 b"audio" => LaneKind::Audio,
3789 b"sub" => LaneKind::Subtitle,
3790 other => {
3791 return Err(format!(
3792 "line {n}: flags names {:?}, not a lane kind",
3793 String::from_utf8_lossy(other)
3794 )
3795 .into());
3796 }
3797 };
3798 let ord = number(words.next().unwrap_or_default(), n)?;
3799 let at = doc
3800 .lanes
3801 .iter()
3802 .enumerate()
3803 .filter(|(_, (k, _))| *k == kind)
3804 .nth(ord.saturating_sub(1) as usize)
3805 .map(|(at, _)| at)
3806 .ok_or_else(|| format!("line {n}: flags names a lane that is not there"))?;
3807 let mut set = LaneFlags::default();
3808 let mut any = false;
3809 for word in words {
3810 let (slot, name) = match word {
3811 b"hidden" if kind != LaneKind::Audio => (&mut set.hidden, "hidden"),
3812 b"muted" if kind == LaneKind::Audio => (&mut set.muted, "muted"),
3813 b"locked" => (&mut set.locked, "locked"),
3814 other => {
3815 return Err(format!(
3816 "line {n}: flags {:?} cannot be set on that lane",
3817 String::from_utf8_lossy(other)
3818 )
3819 .into());
3820 }
3821 };
3822 if std::mem::replace(slot, true) {
3823 return Err(format!("line {n}: flags names {name} twice").into());
3824 }
3825 any = true;
3826 }
3827 if !any {
3828 return Err(format!("line {n}: flags names no switch").into());
3829 }
3830 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
3831 set.pan = doc.flags[at].pan;
3832 doc.flags[at] = set;
3833 }
3834 // Beside the source lines and read the same way: fields first, the
3835 // path last, because a path runs to the end of the line.
3836 b"subtitle" if v10 => {
3837 let at = rest
3838 .iter()
3839 .position(|&b| b == b' ')
3840 .ok_or_else(|| format!("line {n}: subtitle without a path"))?;
3841 let track = match &rest[..at] {
3842 b"-" => None,
3843 field => Some(u64::from(number(field, n)?)),
3844 };
3845 let path = unescape(&rest[at + 1..], n)?;
3846 if path.as_os_str().is_empty() {
3847 return Err(format!("line {n}: subtitle without a path").into());
3848 }
3849 doc.subtitles.push((
3850 // Relative to the project file, as a source path is.
3851 if path.is_absolute() {
3852 path
3853 } else {
3854 dir.join(path)
3855 },
3856 track,
3857 ));
3858 }
3859 // After the subtitle lines, which declare the tracks it names. The
3860 // text is the rest of the line, so it may hold spaces: the track and
3861 // the cue are the two fields before it.
3862 b"cue" if v24 => {
3863 let mut fields = rest.splitn(3, |&b| b == b' ');
3864 let track = number(fields.next().unwrap_or_default(), n)? as usize;
3865 let cue = number(
3866 fields
3867 .next()
3868 .ok_or_else(|| format!("line {n}: cue without a cue index"))?,
3869 n,
3870 )? as usize;
3871 let text = fields
3872 .next()
3873 .ok_or_else(|| format!("line {n}: cue without its text"))?;
3874 if track >= doc.subtitles.len() {
3875 return Err(format!(
3876 "line {n}: cue names subtitle track {track} of {}",
3877 doc.subtitles.len()
3878 )
3879 .into());
3880 }
3881 doc.cue_edits.push((track, cue, unescape_text(text, n)?));
3882 }
3883 // After the subtitle lines, which declare the tracks it names: the
3884 // track, then the language as the rest of the line, escaped as a cue's
3885 // text is. A language is one field to a reader, not a list of words.
3886 b"sublang" if v33 => {
3887 let mut fields = rest.splitn(2, |&b| b == b' ');
3888 let track = number(fields.next().unwrap_or_default(), n)? as usize;
3889 let lang = fields
3890 .next()
3891 .ok_or_else(|| format!("line {n}: sublang without a language"))?;
3892 if track >= doc.subtitles.len() {
3893 return Err(format!(
3894 "line {n}: sublang names subtitle track {track} of {}",
3895 doc.subtitles.len()
3896 )
3897 .into());
3898 }
3899 let lang = unescape_text(lang, n)?;
3900 if lang.is_empty() {
3901 return Err(format!("line {n}: sublang without a language").into());
3902 }
3903 doc.sub_langs.push((track, lang));
3904 }
3905 // After the subtitle lines, which declare the tracks it names, and
3906 // the `cue` lines, so an added cue lands after the file's own cues.
3907 // The text is the rest of the line, as a `cue` line's is.
3908 b"cueadd" if v29 => {
3909 let mut fields = rest.splitn(4, |&b| b == b' ');
3910 let mut field = |what: &str| fields.next().ok_or_else(|| format!("line {n}: cueadd without {what}"));
3911 let track = number(field("a track")?, n)? as usize;
3912 let start_us = number64(field("a start")?, n)? as i64;
3913 let end_us = number64(field("an end")?, n)? as i64;
3914 let text = field("its text")?;
3915 if track >= doc.subtitles.len() {
3916 return Err(format!(
3917 "line {n}: cueadd names subtitle track {track} of {}",
3918 doc.subtitles.len()
3919 )
3920 .into());
3921 }
3922 if end_us <= start_us {
3923 return Err(format!("line {n}: cueadd ends at {end_us} µs, not after its start {start_us} µs").into());
3924 }
3925 doc.cue_adds.push(crate::project::AddedCue {
3926 track,
3927 start_us,
3928 end_us,
3929 text: unescape_text(text, n)?,
3930 });
3931 }
3932 b"source" => {
3933 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3934 return Err(format!("line {n}: source after a clip").into());
3935 }
3936 // The stream comes first and the path is everything after it,
3937 // spaces and all; an older dialect wrote no stream and meant 0.
3938 let (audio_stream, rest) = if streamless {
3939 (0, rest)
3940 } else {
3941 // No space at all still has to reach `number`, so a v2 line
3942 // in a v3 file is refused as the missing field it is rather
3943 // than as a missing path.
3944 let at = rest.iter().position(|&b| b == b' ');
3945 (
3946 number(&rest[..at.unwrap_or(rest.len())], n)? as usize,
3947 &rest[at.map_or(rest.len(), |at| at + 1)..],
3948 )
3949 };
3950 if rest.is_empty() {
3951 return Err(format!("line {n}: source without a path").into());
3952 }
3953 let path = unescape(rest, n)?;
3954 // Relative means "next to the project file", which is what
3955 // makes a whole folder relocatable.
3956 doc.sources.push(Source {
3957 path: if path.is_absolute() {
3958 path
3959 } else {
3960 dir.join(path)
3961 },
3962 audio_stream,
3963 ..Default::default()
3964 });
3965 }
3966 b"eq" if v5 => {
3967 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3968 return Err(format!("line {n}: eq after a clip").into());
3969 }
3970 // A bare `eq` is the empty cascade -- a setting that moves
3971 // nothing, which is not the same thing as no setting at all.
3972 if rest.split(|&b| b == b' ').count() > MAX_EQ_BANDS {
3973 return Err(format!("line {n}: an equalizer holds at most {MAX_EQ_BANDS} bands").into());
3974 }
3975 let bands = match rest.is_empty() {
3976 true => Vec::new(),
3977 false => rest
3978 .split(|&b| b == b' ')
3979 .map(|field| band(field, n))
3980 .collect::<crate::Result<Vec<Band>>>()?,
3981 };
3982 doc.eq.push(EqParams { bands });
3983 }
3984 b"color" if v6 => {
3985 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
3986 return Err(format!("line {n}: color after a clip").into());
3987 }
3988 let f = fields(rest, 1, "color", n)?;
3989 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
3990 if parts.len() != 4 {
3991 return Err(
3992 format!("line {n}: color wants 4 fields, found {}", parts.len()).into(),
3993 );
3994 }
3995 doc.color.push(ColorParams {
3996 brightness: float(parts[0], n)?,
3997 contrast: float(parts[1], n)?,
3998 saturation: float(parts[2], n)?,
3999 tint: float(parts[3], n)?,
4000 ..Default::default()
4001 });
4002 }
4003 b"transform" if v20 => {
4004 if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
4005 return Err(format!("line {n}: transform after a clip").into());
4006 }
4007 let f = fields(rest, 1, "transform", n)?;
4008 let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
4009 // v31 may add the opacity as a ninth field; an earlier dialect
4010 // has eight, and a ninth there is a line it never wrote.
4011 let want = if v31 { 8..=9 } else { 8..=8 };
4012 if !want.contains(&parts.len()) {
4013 return Err(format!(
4014 "line {n}: transform wants 8 fields, found {}",
4015 parts.len()
4016 )
4017 .into());
4018 }
4019 let opacity = match parts.get(8) {
4020 Some(p) => float(p, n)?,
4021 None => 1.0,
4022 };
4023 if !(0.0..=1.0).contains(&opacity) {
4024 return Err(format!("line {n}: transform opacity must be 0..=1").into());
4025 }
4026 doc.transform.push(TransformParams {
4027 pos_x: float(parts[0], n)?,
4028 pos_y: float(parts[1], n)?,
4029 scale: float(parts[2], n)?,
4030 rotate: float(parts[3], n)?,
4031 crop_l: float(parts[4], n)?,
4032 crop_r: float(parts[5], n)?,
4033 crop_t: float(parts[6], n)?,
4034 crop_b: float(parts[7], n)?,
4035 opacity,
4036 });
4037 }
4038 // v1: one lane, no placement, no groups. Every clip becomes one
4039 // grouped video+audio pair laid where the queue reached, which is
4040 // what the file always meant.
4041 b"clip" if v1 => {
4042 let f = fields(rest, 3, "clip", n)?;
4043 let clip = check(
4044 Clip {
4045 speed_keys: Vec::new(),
4046 reversed: false,
4047 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
4048 angle: Default::default(),
4049 fade_in: 0,
4050 fade_out: 0,
4051 transition_out: 0,
4052 transition_kind: Default::default(),
4053 visualizer: 0,
4054 viz_paint: 0,
4055 gain_db: 0.0,
4056 gain_keys: Vec::new(),
4057 pan: 0,
4058 transform_keys: Vec::new(),
4059 opacity_keys: Vec::new(),
4060 color_keys: Vec::new(),
4061 effects: Vec::new(),
4062 start: queued,
4063 in_frame: number(f[0], n)?,
4064 out_frame: number(f[1], n)?,
4065 source: number(f[2], n)? as usize,
4066 link: Some(doc.lanes[0].1.len() as u32),
4067 eq: None,
4068 color: None,
4069 transform: None,
4070 fit: FitPolicy::default(),
4071 speed: Speed::NORMAL,
4072 pitch: 0.0,
4073 },
4074 &doc,
4075 n,
4076 )?;
4077 queued = clip.end();
4078 doc.lanes[0].1.push(clip.clone());
4079 doc.lanes[1].1.push(clip);
4080 }
4081 // A lane line like the two below it, in its place among them, and
4082 // read into `subs` rather than into the clips: the lane holds
4083 // words, and no media path may ever meet one
4084 // ([`crate::project::LaneKind::Subtitle`]).
4085 b"sub" if v15 => {
4086 let at = rest.iter().position(|&b| b == b' ');
4087 let ord = number(&rest[..at.unwrap_or(rest.len())], n)?;
4088 let rest = &rest[at.map_or(rest.len(), |at| at + 1)..];
4089 let at = lane_of(&mut doc.lanes, LaneKind::Subtitle, ord, n)?;
4090 doc.subs.resize(doc.lanes.len(), Vec::new());
4091 // The bare line is the empty lane's whole existence, exactly as
4092 // it is for a video one.
4093 if rest.is_empty() {
4094 continue;
4095 }
4096 // v16 on may carry a sixth field -- the caption's group id, the
4097 // same spelling a clip's link takes (`-` for none). A v15 line
4098 // stops at five, and a sixth field in one is a file this parser
4099 // never wrote.
4100 let all: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4101 let ok = all.len() == 5 || (v16 && all.len() == 6);
4102 if !ok {
4103 return Err(format!(
4104 "line {n}: sub wants {} fields, found {}",
4105 if v16 { "5 or 6" } else { "5" },
4106 all.len()
4107 )
4108 .into());
4109 }
4110 let link = match all.get(5) {
4111 None => None,
4112 Some(f) if *f == b"-" => None,
4113 Some(f) => Some(number(f, n)?),
4114 };
4115 let f = &all;
4116 let sub = SubClip {
4117 start: number(f[0], n)?,
4118 frames: number(f[1], n)?,
4119 track: number(f[2], n)? as usize,
4120 in_us: micros(f[3], n)?,
4121 out_us: micros(f[4], n)?,
4122 link,
4123 };
4124 // The never-empty invariant at both clocks, which is what
4125 // [`crate::Project::place_sub`] refuses on the live timeline.
4126 if sub.frames == 0 || sub.out_us <= sub.in_us || sub.in_us < 0 {
4127 return Err(format!(
4128 "line {n}: caption at {} is empty: {} frames of [{}, {})",
4129 sub.start, sub.frames, sub.in_us, sub.out_us
4130 )
4131 .into());
4132 }
4133 // The width of that window, which the check above cannot see:
4134 // it asks whether the window is *open*, never how wide it is,
4135 // and a `sub` line is the one number in this format a hand (or
4136 // a hostile actor) can set to `i64::MAX` and have accepted.
4137 // Every cut, split, ripple and group trim re-derives the two
4138 // halves of the window by proportion
4139 // ([`crate::project::SubClip::window_at`]), a multiply that
4140 // overflowed on the first frame inside the caption -- a panic
4141 // on the UI thread the first time a hand ripple-deleted across
4142 // it, and in a release build a silently wrapped clock. The
4143 // same bound [`crate::is_resolution`] holds a `resolution`
4144 // line to, and for the same reason: refused by name at the
4145 // door rather than clamped into something nobody wrote.
4146 if sub.out_us - sub.in_us > crate::project::MAX_WINDOW_US {
4147 return Err(format!(
4148 "line {n}: caption at {} is a {}us window, past the {}us a caption can hold",
4149 sub.start,
4150 sub.out_us - sub.in_us,
4151 crate::project::MAX_WINDOW_US
4152 )
4153 .into());
4154 }
4155 // The palette bound, which is a clip's source bound for words:
4156 // the `subtitle` lines are written before these and a caption
4157 // names one of them by position.
4158 if sub.track >= doc.subtitles.len() {
4159 return Err(format!(
4160 "line {n}: caption names subtitle track {} of {}",
4161 sub.track,
4162 doc.subtitles.len()
4163 )
4164 .into());
4165 }
4166 if sub.start.checked_add(sub.frames).is_none() {
4167 return Err(format!(
4168 "line {n}: caption at {} runs past the last frame there is",
4169 sub.start
4170 )
4171 .into());
4172 }
4173 let lane = &mut doc.subs[at];
4174 if lane.last().is_some_and(|prev| prev.end() > sub.start) {
4175 return Err(format!(
4176 "line {n}: caption at {} overlaps the one before it, or comes before it",
4177 sub.start
4178 )
4179 .into());
4180 }
4181 lane.push(sub);
4182 }
4183 b"video" | b"audio" if !v1 => {
4184 let kind = match keyword {
4185 b"video" => LaneKind::Video,
4186 _ => LaneKind::Audio,
4187 };
4188 // v4 on names the lane, and a line naming nothing else is an
4189 // empty lane's whole existence. Older dialects had one lane per
4190 // kind.
4191 let (ord, rest) = if numbered {
4192 let at = rest.iter().position(|&b| b == b' ');
4193 (
4194 number(&rest[..at.unwrap_or(rest.len())], n)?,
4195 &rest[at.map_or(rest.len(), |at| at + 1)..],
4196 )
4197 } else {
4198 (1, rest)
4199 };
4200 let at = lane_of(&mut doc.lanes, kind, ord, n)?;
4201 if numbered && rest.is_empty() {
4202 continue;
4203 }
4204 // v20 grew the transform field, v18 the two fade fields, v19
4205 // the transition one, v8 the speed one, v7 the fit one, v6
4206 // the colour one and v5 the eq one; every older dialect ends
4207 // at the link.
4208 let want = 5
4209 + usize::from(v5)
4210 + usize::from(v6)
4211 + usize::from(v7)
4212 + usize::from(v8)
4213 + 2 * usize::from(v18)
4214 + usize::from(v19)
4215 + usize::from(v20)
4216 + usize::from(v21)
4217 + usize::from(v22);
4218 let f = fields(rest, want, "clip", n)?;
4219 let in_frame = number(f[1], n)?;
4220 let out_frame = number(f[2], n)?;
4221 let speed = speed_of(f.get(8).copied(), n)?;
4222 // Clamped to the clip's own timeline length,
4223 // [`Project::set_fade_in`]'s rule: a crafted or hand-edited
4224 // file asking for more ramp than the clip has frames gets the
4225 // clip's whole length rather than a refusal.
4226 // A v35 clip's ramp comes on a later line and may lengthen it, so its
4227 // fades are clamped once the ramps are in (after the last line).
4228 let frames = if v35 {
4229 u32::MAX
4230 } else {
4231 speed.frames(out_frame.saturating_sub(in_frame))
4232 };
4233 let clip = check(
4234 Clip {
4235 speed_keys: Vec::new(),
4236 reversed: false,
4237 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
4238 angle: Default::default(),
4239 fade_in: number(f.get(9).copied().unwrap_or(b"0"), n)?.min(frames),
4240 fade_out: number(f.get(10).copied().unwrap_or(b"0"), n)?.min(frames),
4241 transition_out: number(f.get(11).copied().unwrap_or(b"0"), n)?.min(frames),
4242 transition_kind: Default::default(),
4243 visualizer: flags_byte(f.get(13).copied().unwrap_or(b"0"), n)?,
4244 viz_paint: number64(f.get(14).copied().unwrap_or(b"0"), n)?,
4245 gain_db: 0.0,
4246 gain_keys: Vec::new(),
4247 pan: 0,
4248 transform_keys: Vec::new(),
4249 opacity_keys: Vec::new(),
4250 color_keys: Vec::new(),
4251 effects: Vec::new(),
4252 start: number(f[0], n)?,
4253 in_frame,
4254 out_frame,
4255 source: number(f[3], n)? as usize,
4256 link: match f[4] {
4257 b"-" => None,
4258 field => Some(number(field, n)?),
4259 },
4260 eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
4261 color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
4262 transform: table_index(
4263 f.get(12).copied(),
4264 doc.transform.len(),
4265 "transform",
4266 n,
4267 )?,
4268 fit: fit_policy(f.get(7).copied(), n)?,
4269 speed,
4270 pitch: 0.0,
4271 },
4272 &doc,
4273 n,
4274 )?;
4275 let lane = &mut doc.lanes[at].1;
4276 // The sorted, non-overlapping placement invariant, checked at
4277 // the only door untrusted clips come in through.
4278 // A v35 file's `speedkeys` lines follow the clips, so a ramped clip still
4279 // has its constant footprint here, which a shorter ramp undercuts: only
4280 // the order is checked at this door, and the footprints after the last line.
4281 let behind = |prev: &Clip| {
4282 if v35 {
4283 prev.start >= clip.start
4284 } else {
4285 prev.end() > clip.start
4286 }
4287 };
4288 if lane.last().is_some_and(behind) {
4289 return Err(format!(
4290 "line {n}: clip at {} overlaps the one before it, or comes before it",
4291 clip.start
4292 )
4293 .into());
4294 }
4295 lane.push(clip);
4296 }
4297 // Empty lines land here too: nothing in this format is optional
4298 // whitespace. A lane keyword in a v1 file (or `clip` in a v2 one)
4299 // is a file mixing dialects, and is refused the same way.
4300 _ => {
4301 return Err(format!(
4302 "line {n}: unknown keyword {:?}",
4303 String::from_utf8_lossy(keyword)
4304 )
4305 .into());
4306 }
4307 }
4308 }
4309 // The ramps are in now: every clip ends before the next one starts.
4310 if v35 {
4311 for (_, clips) in &mut doc.lanes {
4312 for c in clips.iter_mut() {
4313 let frames = c.frames();
4314 c.fade_in = c.fade_in.min(frames);
4315 c.fade_out = c.fade_out.min(frames);
4316 c.transition_out = c.transition_out.min(frames);
4317 }
4318 if let Some(w) = clips.windows(2).find(|w| w[0].end() > w[1].start) {
4319 return Err(format!("clip at {} overlaps the one before it", w[1].start).into());
4320 }
4321 }
4322 }
4323 if block.is_some() {
4324 return Err("a sequence block never ends: the file is cut short".into());
4325 }
4326 // One per lane whatever the file said, so a caller may zip the two -- and
4327 // the same for the placements, whose lanes are the very same list.
4328 doc.gains.resize(doc.lanes.len(), 0.0);
4329 doc.flags.resize(doc.lanes.len(), LaneFlags::default());
4330 doc.ducks.resize(doc.lanes.len(), Vec::new());
4331 doc.voices.resize(doc.lanes.len(), VoiceFx::default());
4332 doc.names.resize(doc.lanes.len(), String::new());
4333 doc.subs.resize(doc.lanes.len(), Vec::new());
4334 // A key is another audio lane of this file, named by its position among
4335 // them, and never the lane it ducks: a file that says otherwise would ask
4336 // the mixer to duck under nothing.
4337 let audio_lanes = doc
4338 .lanes
4339 .iter()
4340 .filter(|(k, _)| *k == LaneKind::Audio)
4341 .count();
4342 for (i, lane_ducks) in doc.ducks.iter().enumerate() {
4343 let own_ord = doc.lanes[..i]
4344 .iter()
4345 .filter(|(k, _)| *k == LaneKind::Audio)
4346 .count();
4347 for duck in lane_ducks {
4348 if duck.under >= audio_lanes || duck.under == own_ord {
4349 return Err(format!(
4350 "duck names audio lane {}, which is not another audio lane of this project",
4351 duck.under + 1
4352 )
4353 .into());
4354 }
4355 }
4356 }
4357 // A file whose lanes are all empty *is* a project -- the emptied timeline,
4358 // saved. What it may not be is laneless; [`crate::Project::from_parts`]
4359 // refuses that one, by the name it has there.
4360 Ok(doc)
4361}
4362
4363/// Where the lane a v4 line names sits, appending it if this is its first line.
4364/// Lanes arrive in display order, so a number that skips one of its kind is a
4365/// lane that was never declared, and is refused by the name it would have had.
4366fn lane_of(
4367 lanes: &mut Vec<(LaneKind, Vec<Clip>)>,
4368 kind: LaneKind,
4369 ord: u32,
4370 line: usize,
4371) -> crate::Result<usize> {
4372 let mut seen = 0;
4373 for (at, (k, _)) in lanes.iter().enumerate() {
4374 if *k == kind {
4375 seen += 1;
4376 if seen == ord {
4377 return Ok(at);
4378 }
4379 }
4380 }
4381 if ord != seen + 1 {
4382 return Err(match ord.checked_sub(1) {
4383 Some(prev) => format!(
4384 "line {line}: lane {} comes before {}",
4385 Lane::new(kind, prev as usize).label(),
4386 Lane::new(kind, seen as usize).label()
4387 ),
4388 None => format!("line {line}: lane numbers start at 1"),
4389 }
4390 .into());
4391 }
4392 lanes.push((kind, Vec::new()));
4393 Ok(lanes.len() - 1)
4394}
4395
4396/// Splits a line's fields, refusing the wrong count by name.
4397fn fields<'a>(
4398 rest: &'a [u8],
4399 want: usize,
4400 what: &str,
4401 line: usize,
4402) -> crate::Result<Vec<&'a [u8]>> {
4403 let fields: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4404 if fields.len() != want {
4405 return Err(format!(
4406 "line {line}: {what} wants {want} fields, found {}",
4407 fields.len()
4408 )
4409 .into());
4410 }
4411 Ok(fields)
4412}
4413
4414/// The per-clip structure checks both dialects share.
4415fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
4416 if clip.out_frame <= clip.in_frame {
4417 return Err(format!(
4418 "line {line}: clip [{}, {}) is empty",
4419 clip.in_frame, clip.out_frame
4420 )
4421 .into());
4422 }
4423 if clip.source >= doc.sources.len() && !crate::project::is_sequence_source(clip.source) {
4424 return Err(format!(
4425 "line {line}: clip names source {} of {}",
4426 clip.source,
4427 doc.sources.len()
4428 )
4429 .into());
4430 }
4431 // Everything downstream -- `Clip::end`, the overlap check, the v1 queue --
4432 // adds `start + len` as plain `u32`, which panics in debug and wraps in
4433 // release on a crafted file. Bound it here, at the door.
4434 if clip.start.checked_add(clip.frames()).is_none() {
4435 return Err(format!(
4436 "line {line}: clip at {} runs past the last frame there is",
4437 clip.start
4438 )
4439 .into());
4440 }
4441 Ok(clip)
4442}
4443
4444/// A clip's `<speed>` field: thousandths of real time, as
4445/// [`crate::project::Speed`] holds it -- `1000` is the rate it was shot at. A
4446/// dialect with no such field (everything before v8) means real time, which is
4447/// what such a project always played at. A number outside the range the editor
4448/// can set is *refused* rather than clamped: a project file is generated, so
4449/// that is a corrupt line and not a dialect.
4450fn speed_of(field: Option<&[u8]>, line: usize) -> crate::Result<Speed> {
4451 let Some(field) = field else {
4452 return Ok(Speed::NORMAL);
4453 };
4454 let permille = number(field, line)?;
4455 let speed = Speed::from_permille(permille.min(u32::from(u16::MAX)) as u16);
4456 if u32::from(speed.permille()) != permille {
4457 return Err(format!(
4458 "line {line}: speed {permille} is outside {}-{} thousandths",
4459 Speed::MIN.permille(),
4460 Speed::MAX.permille()
4461 )
4462 .into());
4463 }
4464 Ok(speed)
4465}
4466
4467/// How a fit policy is spelled in the file. One word each, so a clip line stays
4468/// readable, and the same word the parser takes back.
4469fn fit_name(fit: FitPolicy) -> &'static str {
4470 match fit {
4471 FitPolicy::Fit => "fit",
4472 FitPolicy::Fill => "fill",
4473 FitPolicy::Stretch => "stretch",
4474 FitPolicy::Center => "center",
4475 }
4476}
4477
4478/// A clip's `<fit>` field. A dialect that has no such field at all means the
4479/// default -- those projects held one resolution, so no clip of theirs was ever
4480/// placed on anything.
4481fn fit_policy(field: Option<&[u8]>, line: usize) -> crate::Result<FitPolicy> {
4482 let Some(field) = field else {
4483 return Ok(FitPolicy::default());
4484 };
4485 match field {
4486 b"fit" => Ok(FitPolicy::Fit),
4487 b"fill" => Ok(FitPolicy::Fill),
4488 b"stretch" => Ok(FitPolicy::Stretch),
4489 b"center" => Ok(FitPolicy::Center),
4490 other => Err(format!(
4491 "line {line}: {:?} is not a fit policy",
4492 String::from_utf8_lossy(other)
4493 )
4494 .into()),
4495 }
4496}
4497
4498/// An `effect` line (v42): see [`effect_lines`]. The kind must be one, the switch `0` or
4499/// `1`, every value in its range and a clip's stack no longer than
4500/// [`crate::effects::MAX_EFFECTS`].
4501fn parse_effect(rest: &[u8], n: usize, doc: &mut Document) -> crate::Result<()> {
4502 use crate::effects::{Effect, EffectKind, MAX_EFFECTS, MAX_PARAMS};
4503 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4504 if f.len() < 5 || f[0] != b"video" {
4505 return Err(format!("line {n}: effect wants a video clip, a kind and a switch").into());
4506 }
4507 let ord = number(f[1], n)?;
4508 let at = doc
4509 .lanes
4510 .iter()
4511 .enumerate()
4512 .filter(|(_, (k, _))| *k == LaneKind::Video)
4513 .nth(ord.saturating_sub(1) as usize)
4514 .map(|(at, _)| at)
4515 .ok_or_else(|| format!("line {n}: effect names a lane that is not there"))?;
4516 let idx = number(f[2], n)? as usize;
4517 let name = String::from_utf8_lossy(f[3]);
4518 let kind = EffectKind::from_name(&name).ok_or_else(|| format!("line {n}: effect {name:?} is not one"))?;
4519 let on = match f[4] {
4520 b"1" => true,
4521 b"0" => false,
4522 _ => return Err(format!("line {n}: effect switch is not 0 or 1").into()),
4523 };
4524 let specs = kind.params();
4525 if f.len() - 5 != specs.len() {
4526 return Err(format!("line {n}: effect {name} wants {} values, found {}", specs.len(), f.len() - 5).into());
4527 }
4528 let mut values = [0.0; MAX_PARAMS];
4529 for ((v, field), spec) in values.iter_mut().zip(&f[5..]).zip(specs) {
4530 *v = float(field, n)?;
4531 if !(spec.min..=spec.max).contains(v) {
4532 return Err(format!("line {n}: effect {name} {} is out of its range", spec.name).into());
4533 }
4534 }
4535 let clip = doc.lanes[at]
4536 .1
4537 .get_mut(idx)
4538 .ok_or_else(|| format!("line {n}: effect names clip {idx}, which the lane does not have"))?;
4539 if clip.effects.len() >= MAX_EFFECTS {
4540 return Err(format!("line {n}: a clip holds at most {MAX_EFFECTS} effects").into());
4541 }
4542 clip.effects.push(Effect { kind, on, values, keys: Vec::new() });
4543 Ok(())
4544}
4545
4546/// A `voice` line (v41): see [`voice_lines`]. Every number is range-checked the way the
4547/// setter clamps it, and a noise reduction that is on must carry its profile.
4548fn parse_voice(rest: &[u8], n: usize, doc: &mut Document) -> crate::Result<()> {
4549 let f: Vec<&[u8]> = rest.split(|&b| b == b' ').collect();
4550 if f.len() < 3 {
4551 return Err(format!("line {n}: voice wants a lane, a number and a processor").into());
4552 }
4553 if f[0] != b"audio" {
4554 return Err(format!("line {n}: voice names {:?}, not an audio lane", String::from_utf8_lossy(f[0])).into());
4555 }
4556 let ord = number(f[1], n)?;
4557 let at = doc
4558 .lanes
4559 .iter()
4560 .enumerate()
4561 .filter(|(_, (k, _))| *k == LaneKind::Audio)
4562 .nth(ord.saturating_sub(1) as usize)
4563 .map(|(at, _)| at)
4564 .ok_or_else(|| format!("line {n}: voice names a lane that is not there"))?;
4565 doc.voices.resize(doc.lanes.len(), VoiceFx::default());
4566 let flag = |field: &[u8]| match field {
4567 b"0" => Ok(false),
4568 b"1" => Ok(true),
4569 _ => Err(format!("line {n}: {:?} is not 0 or 1", String::from_utf8_lossy(field))),
4570 };
4571 let want = |count: usize, what: &str| {
4572 if f.len() == count + 3 {
4573 Ok(())
4574 } else {
4575 Err(format!("line {n}: voice {what} wants {count} fields, found {}", f.len() - 3))
4576 }
4577 };
4578 let range = || format!("line {n}: voice has a number out of its range");
4579 let voice = &mut doc.voices[at];
4580 match f[2] {
4581 b"gate" => {
4582 want(6, "gate")?;
4583 let g = Gate {
4584 on: flag(f[3])?,
4585 threshold_db: float(f[4], n)?,
4586 attack_ms: float(f[5], n)?,
4587 release_ms: float(f[6], n)?,
4588 hold_ms: float(f[7], n)?,
4589 range_db: float(f[8], n)?,
4590 };
4591 if g.clamped() != Some(g) {
4592 return Err(range().into());
4593 }
4594 voice.gate = g;
4595 }
4596 b"nr" => {
4597 want(4, "nr")?;
4598 let profile = match f[6] {
4599 b"-" => Vec::new(),
4600 list => list.split(|&b| b == b',').map(|v| float(v, n)).collect::<crate::Result<Vec<f32>>>()?,
4601 };
4602 let nr = NoiseReduction { on: flag(f[3])?, strength: float(f[4], n)?, floor_db: float(f[5], n)?, profile };
4603 if nr.clamped().as_ref() != Some(&nr) {
4604 return Err(range().into());
4605 }
4606 if nr.on && nr.profile.is_empty() {
4607 return Err(format!("line {n}: voice nr is on but has no noise profile").into());
4608 }
4609 voice.nr = nr;
4610 }
4611 b"comp" => {
4612 want(8, "comp")?;
4613 let c = Compressor {
4614 on: flag(f[3])?,
4615 threshold_db: float(f[4], n)?,
4616 ratio: float(f[5], n)?,
4617 attack_ms: float(f[6], n)?,
4618 release_ms: float(f[7], n)?,
4619 knee_db: float(f[8], n)?,
4620 makeup_db: float(f[9], n)?,
4621 auto_makeup: flag(f[10])?,
4622 };
4623 if c.clamped() != Some(c) {
4624 return Err(range().into());
4625 }
4626 voice.comp = c;
4627 }
4628 b"deess" => {
4629 want(5, "deess")?;
4630 let d = DeEsser {
4631 on: flag(f[3])?,
4632 threshold_db: float(f[4], n)?,
4633 amount: float(f[5], n)?,
4634 lo_hz: float(f[6], n)?,
4635 hi_hz: float(f[7], n)?,
4636 };
4637 if d.clamped() != Some(d) {
4638 return Err(range().into());
4639 }
4640 voice.deess = d;
4641 }
4642 other => {
4643 return Err(format!("line {n}: voice names {:?}, not a processor", String::from_utf8_lossy(other)).into());
4644 }
4645 }
4646 Ok(())
4647}
4648
4649/// A clip's `<eq>` or `<color>` field: `-` (or a dialect that has no such field
4650/// at all), or a line of a table that is already declared. Refused by the name
4651/// of what it points at, so the message reads as the file does.
4652fn table_index(
4653 field: Option<&[u8]>,
4654 len: usize,
4655 what: &str,
4656 line: usize,
4657) -> crate::Result<Option<u16>> {
4658 let field = match field {
4659 None | Some(b"-") => return Ok(None),
4660 Some(field) => field,
4661 };
4662 let i = number(field, line)?;
4663 if i as usize >= len || i > u32::from(u16::MAX) {
4664 return Err(format!("line {line}: clip names {what} {i} of {len}").into());
4665 }
4666 Ok(Some(i as u16))
4667}
4668
4669/// One `<frequency>:<gain>:<Q>:<shape>` field of an eq line.
4670fn band(field: &[u8], line: usize) -> crate::Result<Band> {
4671 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
4672 if parts.len() != 4 {
4673 return Err(format!("line {line}: band wants 4 fields, found {}", parts.len()).into());
4674 }
4675 Ok(Band {
4676 freq_hz: float(parts[0], line)?,
4677 gain_db: float(parts[1], line)?,
4678 q: float(parts[2], line)?,
4679 kind: match parts[3] {
4680 b"ls" => BandKind::LowShelf,
4681 b"pk" => BandKind::Peak,
4682 b"hs" => BandKind::HighShelf,
4683 b"lc" => BandKind::LowCut,
4684 b"hc" => BandKind::HighCut,
4685 other => {
4686 return Err(format!(
4687 "line {line}: {:?} is not a band shape",
4688 String::from_utf8_lossy(other)
4689 )
4690 .into());
4691 }
4692 },
4693 })
4694}
4695
4696/// The `at:ease:values` points of an `mkeys` or `ekeys` line (`name`), in source order.
4697/// Each point holds one value per spec in `specs`, each within that spec's range, and the
4698/// rest of the key is zero. A custom bezier ease is read only from v56 on, and at most
4699/// [`MAX_TRANSFORM_KEYS`] points are read.
4700fn read_effect_keys(
4701 name: &str,
4702 points: &[&[u8]],
4703 specs: &[crate::effects::ParamSpec],
4704 n: usize,
4705 v56: bool,
4706) -> crate::Result<Vec<crate::effects::EffectKey>> {
4707 if points.len() > MAX_TRANSFORM_KEYS {
4708 return Err(format!("line {n}: {name} has more than {MAX_TRANSFORM_KEYS} keys").into());
4709 }
4710 let mut keys: Vec<crate::effects::EffectKey> = Vec::new();
4711 for point in points {
4712 let parts: Vec<&[u8]> = point.splitn(3, |&b| b == b':').collect();
4713 if parts.len() != 3 {
4714 return Err(format!("line {n}: {name} key wants at:ease:values").into());
4715 }
4716 let at = number(parts[0], n)?;
4717 let ease = KeyEase::from_token(parts[1])
4718 .filter(|e| v56 || !matches!(e, KeyEase::Bezier(_)))
4719 .ok_or_else(|| format!("line {n}: {name} ease is lin, in, out, ease, hold or a bezier curve"))?;
4720 if keys.last().is_some_and(|k| k.at >= at) {
4721 return Err(format!("line {n}: {name} keys are not in source order").into());
4722 }
4723 let v: Vec<&[u8]> = parts[2].split(|&b| b == b',').collect();
4724 if v.len() != specs.len() {
4725 return Err(format!("line {n}: {name} key wants {} values", specs.len()).into());
4726 }
4727 let mut values = [0.0f32; crate::effects::MAX_PARAMS];
4728 for (i, (x, field)) in values.iter_mut().zip(&v).enumerate() {
4729 *x = float(field, n)?;
4730 if !(specs[i].min..=specs[i].max).contains(x) {
4731 return Err(format!("line {n}: {name} {} is out of its range", specs[i].name).into());
4732 }
4733 }
4734 keys.push(crate::effects::EffectKey { at, values, ease });
4735 }
4736 Ok(keys)
4737}
4738
4739/// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity
4740/// and NaN are refused rather than carried -- they are the values a coefficient
4741/// cannot be built from, and the ones that would not compare equal to
4742/// themselves on the way back.
4743fn float(field: &[u8], line: usize) -> crate::Result<f32> {
4744 match std::str::from_utf8(field)
4745 .ok()
4746 .and_then(|s| s.parse::<f32>().ok())
4747 .filter(|f| f.is_finite())
4748 {
4749 Some(f) => Ok(f),
4750 None => Err(format!(
4751 "line {line}: {:?} is not a number",
4752 String::from_utf8_lossy(field)
4753 )
4754 .into()),
4755 }
4756}
4757
4758/// A clip's visualizer field: every bit of the byte is a flag
4759/// ([`crate::decode::VIZ_STYLE_FILL`]'s low bits, the fast bit, the ink
4760/// nibble), so a line naming one past what a byte holds is a look this
4761/// program does not have rather than a 300 that quietly loads as a 44.
4762fn flags_byte(field: &[u8], line: usize) -> crate::Result<u8> {
4763 let n = number(field, line)?;
4764 u8::try_from(n).map_err(|_| format!("line {line}: {n} is not a set of visualizer flags").into())
4765}
4766
4767fn number(field: &[u8], line: usize) -> crate::Result<u32> {
4768 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4769 Some(n) => Ok(n),
4770 None => Err(format!(
4771 "line {line}: {:?} is not a number",
4772 String::from_utf8_lossy(field)
4773 )
4774 .into()),
4775 }
4776}
4777
4778/// [`number`] for the one field wider than a `u32`: the clip's packed
4779/// visualizer look, whose strand-colour half needs the width (v23).
4780fn number64(field: &[u8], line: usize) -> crate::Result<u64> {
4781 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4782 Some(n) => Ok(n),
4783 None => Err(format!(
4784 "line {line}: {:?} is not a number",
4785 String::from_utf8_lossy(field)
4786 )
4787 .into()),
4788 }
4789}
4790
4791/// A `sub` line's window field: microseconds, which is the clock a cue is timed
4792/// in ([`crate::subtitle::Cue`]) and the one thing in this format counted in
4793/// something other than frames. Signed as the cues are, and the negative half
4794/// is refused by the never-empty check at the line, not here.
4795fn micros(field: &[u8], line: usize) -> crate::Result<i64> {
4796 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
4797 Some(n) => Ok(n),
4798 None => Err(format!(
4799 "line {line}: {:?} is not a number",
4800 String::from_utf8_lossy(field)
4801 )
4802 .into()),
4803 }
4804}
4805
4806/// A `cue` line's text: the backslash that escapes it and the two line breaks,
4807/// which are the only bytes a line cannot hold (and `\r` is spelled too, so a
4808/// text ending in one does not look like a CRLF file to a hand-editor).
4809fn escape_text(text: &str, out: &mut Vec<u8>) {
4810 for c in text.chars() {
4811 match c {
4812 '\\' => out.extend_from_slice(b"\\\\"),
4813 '\n' => out.extend_from_slice(b"\\n"),
4814 '\r' => out.extend_from_slice(b"\\r"),
4815 c => out.extend_from_slice(c.encode_utf8(&mut [0; 4]).as_bytes()),
4816 }
4817 }
4818}
4819
4820/// Undoes [`escape_text`]. Anything but the three escapes is refused by name,
4821/// so a hand-edited typo does not quietly become a different word.
4822fn unescape_text(field: &[u8], line: usize) -> crate::Result<String> {
4823 let mut out = Vec::with_capacity(field.len());
4824 let mut bytes = field.iter().copied();
4825 while let Some(b) = bytes.next() {
4826 if b != b'\\' {
4827 out.push(b);
4828 continue;
4829 }
4830 match bytes.next() {
4831 Some(b'\\') => out.push(b'\\'),
4832 Some(b'n') => out.push(b'\n'),
4833 Some(b'r') => out.push(b'\r'),
4834 _ => return Err(format!("line {line}: cue text has a bad escape").into()),
4835 }
4836 }
4837 String::from_utf8(out)
4838 .map_err(|_| -> crate::Error { format!("line {line}: cue text is not UTF-8").into() })
4839}
4840
4841/// The two bytes a line-based format cannot hold, and the escape byte itself.
4842fn escape(path: &Path, out: &mut Vec<u8>) {
4843 for &b in path.as_os_str().as_bytes() {
4844 match b {
4845 b'%' => out.extend_from_slice(b"%25"),
4846 b'\n' => out.extend_from_slice(b"%0A"),
4847 _ => out.push(b),
4848 }
4849 }
4850}
4851
4852/// Accepts any `%XX`, not just the two [`escape`] writes -- a hand-edited file
4853/// may spell a space or a quote that way, and there is no reason to refuse it.
4854fn unescape(field: &[u8], line: usize) -> crate::Result<PathBuf> {
4855 let mut out = Vec::with_capacity(field.len());
4856 let mut i = 0;
4857 while i < field.len() {
4858 if field[i] != b'%' {
4859 out.push(field[i]);
4860 i += 1;
4861 continue;
4862 }
4863 let byte = field
4864 .get(i + 1..i + 3)
4865 .and_then(|h| std::str::from_utf8(h).ok())
4866 .and_then(|h| u8::from_str_radix(h, 16).ok())
4867 .ok_or_else(|| -> crate::Error {
4868 format!("line {line}: truncated % escape in the path").into()
4869 })?;
4870 out.push(byte);
4871 i += 3;
4872 }
4873 Ok(PathBuf::from(OsString::from_vec(out)))
4874}
4875
4876#[cfg(test)]
4877mod tests {
4878 use super::*;
4879
4880 /// [`super::emit`] for a project whose mix is flat: every lane at unity, no
4881 /// limiter, no rate written. Shadows the real one for the tests that were
4882 /// written before there was a mix to write -- the dialect they are about is
4883 /// the one this emits, and a v9 file with flat settings is a v8 file bar
4884 /// its version line, which is exactly what they assert.
4885 #[allow(clippy::too_many_arguments)]
4886 fn emit(
4887 dir: &Path,
4888 sources: &[Source],
4889 lanes: &[(LaneKind, Vec<Clip>)],
4890 eq: &[EqParams],
4891 color: &[ColorParams],
4892 resolution: (u32, u32),
4893 playhead: u32,
4894 ) -> Vec<u8> {
4895 super::emit(
4896 dir,
4897 sources,
4898 lanes,
4899 &[],
4900 &[],
4901 &[],
4902 eq,
4903 color,
4904 &[],
4905 resolution,
4906 None,
4907 crate::tonemap::Preset::default(),
4908 false,
4909 true,
4910 crate::export::EncoderSeat::default(),
4911 Limiter::default(),
4912 None,
4913 playhead,
4914 )
4915 }
4916
4917 /// A subtitle track as a save hands one over: the cues are not written and
4918 /// so are not here either.
4919 fn subtitle(path: &str, track: Option<u64>) -> SubtitleTrack {
4920 SubtitleTrack {
4921 path: PathBuf::from(path),
4922 track,
4923 language: String::new(),
4924 name: String::new(),
4925 label: String::new(),
4926 cues: Vec::new(),
4927 bitmap: false,
4928 refused: None,
4929 }
4930 }
4931
4932 /// The v24 `cue` line: a retyped cue's words escape the backslash and the
4933 /// two line breaks, come back exactly, and a line that names no track it
4934 /// has, or spells an escape it does not know, is refused by name.
4935 #[test]
4936 fn cue_lines_round_trip_their_text_and_refuse_what_they_cannot_name() {
4937 let dir = PathBuf::from("/proj");
4938 let doc = parse(
4939 b"edith 24\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n\
4940 cue 0 2 a \\\\ b\\nc\\r\\nd\ncue 0 0 \n",
4941 &dir,
4942 )
4943 .expect("two cue lines parse");
4944 assert_eq!(
4945 doc.cue_edits,
4946 [(0, 2, "a \\ b\nc\r\nd".to_string()), (0, 0, String::new())]
4947 );
4948
4949 // The writer's own spelling reads back as the same text, whatever is in it.
4950 let text = "back\\slash\nnew\rline \\n is not a newline";
4951 let mut out = Vec::new();
4952 escape_text(text, &mut out);
4953 assert_eq!(unescape_text(&out, 1).expect("its own escapes"), text);
4954
4955 let refuse = |body: &[u8]| parse(body, &dir).unwrap_err().to_string();
4956 let head = b"edith 24\nsubtitle - subs.srt\n";
4957 let with = |line: &[u8]| [head.as_slice(), line].concat();
4958 assert!(refuse(&with(b"cue 1 0 x\n")).contains("names subtitle track 1 of 1"));
4959 assert!(refuse(&with(b"cue 0 0 \\q\n")).contains("bad escape"));
4960 assert!(refuse(&with(b"cue 0 0\n")).contains("without its text"));
4961 assert!(refuse(&with(b"cue 0\n")).contains("without a cue index"));
4962 assert!(
4963 refuse(b"edith 23\nsubtitle - subs.srt\ncue 0 0 x\n").contains("unknown keyword"),
4964 "a cue line before v24 is not a dialect"
4965 );
4966 }
4967
4968 /// The v10 line: which track of which file, written beside the sources and
4969 /// read back as the pair a load opens. And what a v9 file is -- one with no
4970 /// subtitles at all, which still opens and re-saves as v10.
4971 #[test]
4972 fn subtitles_round_trip_as_references_and_a_v9_file_has_none() {
4973 let dir = PathBuf::from("/proj");
4974 let (_, sources, lanes) = doc();
4975 let tracks = [
4976 subtitle("/proj/subs.srt", None),
4977 subtitle("/proj/a.mp4", Some(3)),
4978 subtitle("/elsewhere/od d name.ass", None),
4979 ];
4980 let bytes = super::emit(
4981 &dir,
4982 &sources,
4983 &lanes,
4984 &[],
4985 &[],
4986 &tracks,
4987 &[],
4988 &[],
4989 &[],
4990 (1280, 720),
4991 None,
4992 crate::tonemap::Preset::default(),
4993 false,
4994 true,
4995 crate::export::EncoderSeat::default(),
4996 Limiter::default(),
4997 None,
4998 0,
4999 );
5000 let text = String::from_utf8_lossy(&bytes);
5001 assert!(
5002 text.contains(
5003 "subtitle - subs.srt\n\
5004 subtitle 3 a.mp4\n\
5005 subtitle - /elsewhere/od d name.ass\n"
5006 ),
5007 "the path is relative where it can be, and runs to the end of its \
5008 line, spaces and all: {text}"
5009 );
5010 let back = parse(&bytes, &dir).expect("v10 parses");
5011 assert_eq!(
5012 back.subtitles,
5013 vec![
5014 (PathBuf::from("/proj/subs.srt"), None),
5015 (PathBuf::from("/proj/a.mp4"), Some(3)),
5016 (PathBuf::from("/elsewhere/od d name.ass"), None),
5017 ]
5018 );
5019
5020 // A v9 file is a project with no subtitles, and re-saving it writes v10.
5021 let v9 = b"edith 9\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5022 video 1 0 0 30 0 - - - fit 1000\n";
5023 let old = parse(v9, &dir).expect("v9 still loads");
5024 assert_eq!(old.subtitles, Vec::new());
5025 assert!(flat(&dir, &old.sources, &old.lanes, old.playhead).starts_with(b"edith 30\n"));
5026 // ...and the line itself is not a v9 line: a dialect may not be mixed.
5027 let mixed = parse(b"edith 9\nsource 0 a.mp4\nsubtitle - subs.srt\n", &dir)
5028 .unwrap_err()
5029 .to_string();
5030 assert_eq!(mixed, "line 3: unknown keyword \"subtitle\"");
5031 // A subtitle line with no path is refused, as a source with none is.
5032 for line in ["subtitle -\n", "subtitle - \n", "subtitle x subs.srt\n"] {
5033 let file = format!("edith 10\nsource 0 a.mp4\n{line}");
5034 assert!(
5035 parse(file.as_bytes(), &dir).is_err(),
5036 "{line:?} is not a subtitle line"
5037 );
5038 }
5039 }
5040
5041 /// The v33 `sublang` line: a track's language is written after the subtitle
5042 /// lines and comes back on that track. A project with no language writes no
5043 /// line and keeps its old header, and a line that names no track, has no
5044 /// language, or sits in a dialect before v33 is refused.
5045 #[test]
5046 fn sublang_lines_round_trip_and_a_project_with_none_is_unchanged() {
5047 let dir = PathBuf::from("/proj");
5048 let (_, sources, lanes) = doc();
5049 let save = |tracks: &[SubtitleTrack]| {
5050 super::emit(
5051 &dir,
5052 &sources,
5053 &lanes,
5054 &[],
5055 &[],
5056 tracks,
5057 &[],
5058 &[],
5059 &[],
5060 (1280, 720),
5061 None,
5062 crate::tonemap::Preset::default(),
5063 false,
5064 true,
5065 crate::export::EncoderSeat::default(),
5066 Limiter::default(),
5067 None,
5068 0,
5069 )
5070 };
5071 let mut eng = subtitle("/proj/subs.srt", None);
5072 eng.language = "eng".into();
5073 let mut fra = subtitle("/proj/a.mp4", Some(3));
5074 fra.language = "fra".into();
5075 let bytes = save(&[eng, fra]);
5076 let text = String::from_utf8_lossy(&bytes);
5077 assert!(text.starts_with("edith 33\n"), "a language makes it v33: {text}");
5078 assert!(
5079 text.contains("subtitle - subs.srt\nsubtitle 3 a.mp4\nsublang 0 eng\nsublang 1 fra\n"),
5080 "{text}"
5081 );
5082 let back = parse(&bytes, &dir).expect("v33 parses");
5083 assert_eq!(back.sub_langs, [(0, "eng".to_string()), (1, "fra".to_string())]);
5084
5085 // No language anywhere: no line, and the header is the one it was.
5086 let bare = save(&[subtitle("/proj/subs.srt", None)]);
5087 let text = String::from_utf8_lossy(&bare);
5088 assert!(!text.contains("sublang") && !text.starts_with("edith 33"), "{text}");
5089 assert!(parse(&bare, &dir).expect("parses").sub_langs.is_empty());
5090
5091 // A v32 file has no languages and loads as it did.
5092 let v32 = b"edith 32\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n";
5093 assert!(parse(v32, &dir).expect("v32 loads").sub_langs.is_empty());
5094
5095 // The refusals: a track that is not there, an empty language, and a
5096 // line in a dialect before v33.
5097 let head = "edith 33\nsource 0 a.mp4\nsubtitle - subs.srt\n";
5098 for line in ["sublang 1 eng\n", "sublang 0\n", "sublang x eng\n"] {
5099 assert!(
5100 parse(format!("{head}{line}").as_bytes(), &dir).is_err(),
5101 "{line:?} is not a sublang line"
5102 );
5103 }
5104 let old = b"edith 32\nsource 0 a.mp4\nsubtitle - subs.srt\nsublang 0 eng\n";
5105 assert_eq!(
5106 parse(old, &dir).unwrap_err().to_string(),
5107 "line 4: unknown keyword \"sublang\""
5108 );
5109 }
5110
5111 /// The caption's group field (v16): written only when the caption is in a
5112 /// group -- so a project nobody grouped a caption in is the same bytes it
5113 /// was in v15 -- read back as the id, and refused in an older dialect,
5114 /// which never wrote one.
5115 #[test]
5116 fn a_caption_group_round_trips_and_an_old_dialect_refuses_the_field() {
5117 let dir = PathBuf::from("/proj");
5118 let caption = |start: u32, frames: u32, link| SubClip {
5119 start,
5120 frames,
5121 track: 0,
5122 in_us: 0,
5123 out_us: i64::from(frames) * 1_000_000,
5124 link,
5125 };
5126 let lanes = vec![
5127 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(7))]),
5128 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(7))]),
5129 (LaneKind::Subtitle, Vec::new()),
5130 ];
5131 let subs = vec![
5132 vec![],
5133 vec![],
5134 vec![caption(0, 30, Some(7)), caption(40, 10, None)],
5135 ];
5136 let bytes = super::emit(
5137 &dir,
5138 &doc().1,
5139 &lanes,
5140 &[],
5141 &subs,
5142 &[subtitle("/proj/subs.srt", None)],
5143 &[],
5144 &[],
5145 &[],
5146 (1280, 720),
5147 None,
5148 crate::tonemap::Preset::default(),
5149 false,
5150 true,
5151 crate::export::EncoderSeat::default(),
5152 Limiter::default(),
5153 None,
5154 0,
5155 );
5156 let text = String::from_utf8_lossy(&bytes);
5157 assert!(
5158 text.contains("sub 1 0 30 0 0 30000000 7\n"),
5159 "the grouped caption carries its id: {text}"
5160 );
5161 assert!(
5162 text.contains("sub 1 40 10 0 0 10000000\n"),
5163 "a caption in no group writes no field: {text}"
5164 );
5165 let back = parse(&bytes, &dir).expect("v16 parses");
5166 assert_eq!(back.subs[2][0].link, Some(7));
5167 assert_eq!(back.subs[2][1].link, None);
5168
5169 // The older dialect never wrote a sixth field, and one claiming to be
5170 // it is a file this parser refuses by name.
5171 let v15 = parse(
5172 b"edith 15\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\nsubtitle - subs.srt\n\
5173 sub 1 0 30 0 0 30000000 7\n",
5174 &dir,
5175 )
5176 .unwrap_err()
5177 .to_string();
5178 assert_eq!(v15, "line 6: sub wants 5 fields, found 6");
5179 }
5180
5181 /// The v12 line: whether the project is cut on the stand-ins, written only
5182 /// when it is -- and the dialect before it, which had no stand-ins and
5183 /// whose bytes are therefore unchanged bar the version.
5184 #[test]
5185 fn the_proxy_switch_round_trips_and_a_v11_file_is_cut_on_its_films() {
5186 let dir = PathBuf::from("/proj");
5187 let (_, sources, lanes) = doc();
5188 let bytes = |proxy| {
5189 super::emit(
5190 &dir,
5191 &sources,
5192 &lanes,
5193 &[],
5194 &[],
5195 &[],
5196 &[],
5197 &[],
5198 &[],
5199 (1280, 720),
5200 None,
5201 crate::tonemap::Preset::default(),
5202 proxy,
5203 true,
5204 crate::export::EncoderSeat::default(),
5205 Limiter::default(),
5206 None,
5207 0,
5208 )
5209 };
5210 let on = bytes(true);
5211 assert!(
5212 String::from_utf8_lossy(&on).contains("proxy on\n"),
5213 "{}",
5214 String::from_utf8_lossy(&on)
5215 );
5216 assert!(parse(&on, &dir).expect("v12 parses").proxy);
5217 let off = bytes(false);
5218 assert!(
5219 !String::from_utf8_lossy(&off).contains("proxy"),
5220 "off is the line left out"
5221 );
5222 assert!(!parse(&off, &dir).expect("v12 parses").proxy);
5223
5224 // A v11 project is one cut on the films themselves, and it still loads.
5225 let v11 = b"edith 11\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5226 video 1 0 0 30 0 - - - fit 1000\n";
5227 let old = parse(v11, &dir).expect("v11 still loads");
5228 assert!(!old.proxy);
5229 assert_eq!(old.sources.len(), 1, "the rest of it came back too");
5230 // ...and the line is not a v11 line: a dialect may not be mixed.
5231 let mixed = parse(b"edith 11\nsource 0 a.mp4\nproxy on\n", &dir)
5232 .unwrap_err()
5233 .to_string();
5234 assert_eq!(mixed, "line 3: unknown keyword \"proxy\"");
5235 // Anything but on or off is a corrupt line, by name.
5236 for line in ["proxy\n", "proxy yes\n", "proxy On\n"] {
5237 let file = format!("edith 13\nsource 0 a.mp4\n{line}");
5238 assert!(
5239 parse(file.as_bytes(), &dir).is_err(),
5240 "{line:?} is not a proxy line"
5241 );
5242 }
5243 }
5244
5245 /// The v13 line: whether an import makes a stand-in by itself. Written the
5246 /// other way up from every other switch here -- on is the default and the
5247 /// line left out -- because that is what every dialect before it did, and a
5248 /// v12 file must come back doing it.
5249 #[test]
5250 fn the_auto_proxy_switch_round_trips_and_a_v12_file_makes_them_by_itself() {
5251 let dir = PathBuf::from("/proj");
5252 let (_, sources, lanes) = doc();
5253 let bytes = |proxy, auto| {
5254 super::emit(
5255 &dir,
5256 &sources,
5257 &lanes,
5258 &[],
5259 &[],
5260 &[],
5261 &[],
5262 &[],
5263 &[],
5264 (1280, 720),
5265 None,
5266 crate::tonemap::Preset::default(),
5267 proxy,
5268 auto,
5269 crate::export::EncoderSeat::default(),
5270 Limiter::default(),
5271 None,
5272 0,
5273 )
5274 };
5275 // The default is the line left out, and the two switches are two lines:
5276 // a project cut on stand-ins it does not make writes both.
5277 let on = bytes(false, true);
5278 assert!(
5279 !String::from_utf8_lossy(&on).contains("autoproxy"),
5280 "on is the line left out: {}",
5281 String::from_utf8_lossy(&on)
5282 );
5283 assert!(parse(&on, &dir).expect("v13 parses").auto_proxy);
5284 let off = bytes(true, false);
5285 let text = String::from_utf8_lossy(&off).to_string();
5286 assert!(text.contains("proxy on\nautoproxy off\n"), "{text}");
5287 let back = parse(&off, &dir).expect("v13 parses");
5288 assert!(back.proxy, "the other switch came back too");
5289 assert!(!back.auto_proxy);
5290
5291 // A v12 project made them by itself and could not be told otherwise.
5292 let v12 = b"edith 12\nplayhead 0\nresolution 1280 720\nproxy on\nsource 0 a.mp4\n\
5293 video 1 0 0 30 0 - - - fit 1000\n";
5294 let old = parse(v12, &dir).expect("v12 still loads");
5295 assert!(old.auto_proxy, "a v12 project made its stand-ins by itself");
5296 assert!(old.proxy, "the rest of it came back too");
5297 // ...and the line is not a v12 line: a dialect may not be mixed.
5298 let mixed = parse(b"edith 12\nsource 0 a.mp4\nautoproxy off\n", &dir)
5299 .unwrap_err()
5300 .to_string();
5301 assert_eq!(mixed, "line 3: unknown keyword \"autoproxy\"");
5302 // Anything but on or off is a corrupt line, by name.
5303 for line in ["autoproxy\n", "autoproxy no\n", "autoproxy Off\n"] {
5304 let file = format!("edith 13\nsource 0 a.mp4\n{line}");
5305 assert!(
5306 parse(file.as_bytes(), &dir).is_err(),
5307 "{line:?} is not an autoproxy line"
5308 );
5309 }
5310 }
5311
5312 /// The v14 line: which encoder an export writes the picture with, by name,
5313 /// read back as the very seat -- and the dialect before it, which had no
5314 /// way to say one and took whatever this machine had.
5315 #[test]
5316 fn the_encoder_seat_round_trips_by_name_and_a_v13_file_takes_the_machines() {
5317 use crate::export::EncoderSeat;
5318 let dir = PathBuf::from("/proj");
5319 let (_, sources, lanes) = doc();
5320 let bytes = |seat| {
5321 super::emit(
5322 &dir,
5323 &sources,
5324 &lanes,
5325 &[],
5326 &[],
5327 &[],
5328 &[],
5329 &[],
5330 &[],
5331 (1280, 720),
5332 None,
5333 crate::tonemap::Preset::default(),
5334 false,
5335 true,
5336 seat,
5337 Limiter::default(),
5338 None,
5339 0,
5340 )
5341 };
5342 // The default is the line left out, so a project nobody has picked a
5343 // seat for is the bytes a v13 file was bar the version line.
5344 let auto = bytes(EncoderSeat::Auto);
5345 assert!(
5346 !String::from_utf8_lossy(&auto).contains("encoder"),
5347 "auto is the line left out: {}",
5348 String::from_utf8_lossy(&auto)
5349 );
5350 assert_eq!(
5351 parse(&auto, &dir).expect("v14 parses").encoder,
5352 EncoderSeat::Auto
5353 );
5354 for seat in [EncoderSeat::Hardware, EncoderSeat::Software] {
5355 let written = bytes(seat);
5356 let text = String::from_utf8_lossy(&written).to_string();
5357 assert!(
5358 text.contains(&format!("encoder {}\n", seat.name())),
5359 "{text}"
5360 );
5361 assert_eq!(parse(&written, &dir).expect("v14 parses").encoder, seat);
5362 }
5363
5364 // A v13 project took the seat this machine had and could not be told
5365 // otherwise.
5366 let v13 = b"edith 13\nplayhead 0\nresolution 1280 720\nautoproxy off\nsource 0 a.mp4\n\
5367 video 1 0 0 30 0 - - - fit 1000\n";
5368 let old = parse(v13, &dir).expect("v13 still loads");
5369 assert_eq!(
5370 old.encoder,
5371 EncoderSeat::Auto,
5372 "a v13 project exported on whatever seat there was"
5373 );
5374 assert!(!old.auto_proxy, "the rest of it came back too");
5375 // ...and the line is not a v13 line: a dialect may not be mixed.
5376 let mixed = parse(b"edith 13\nsource 0 a.mp4\nencoder software\n", &dir)
5377 .unwrap_err()
5378 .to_string();
5379 assert_eq!(mixed, "line 3: unknown keyword \"encoder\"");
5380 // Anything but the three names is a corrupt line, by name.
5381 for line in ["encoder\n", "encoder gpu\n", "encoder Hardware\n"] {
5382 let file = format!("edith 15\nsource 0 a.mp4\n{line}");
5383 assert!(
5384 parse(file.as_bytes(), &dir).is_err(),
5385 "{line:?} is not an encoder line"
5386 );
5387 }
5388 }
5389
5390 /// The v17 line: an explicit sound rate, written only when picked and read
5391 /// back as the very number -- and a v16 file, which had no way to say one
5392 /// and meant the source's own probe, still opens with `None`.
5393 #[test]
5394 fn the_sample_rate_round_trips_and_a_v16_file_leaves_it_derived() {
5395 let dir = PathBuf::from("/proj");
5396 let (_, sources, lanes) = doc();
5397 let bytes = |rate| {
5398 super::emit(
5399 &dir,
5400 &sources,
5401 &lanes,
5402 &[],
5403 &[],
5404 &[],
5405 &[],
5406 &[],
5407 &[],
5408 (1280, 720),
5409 None,
5410 crate::tonemap::Preset::default(),
5411 false,
5412 true,
5413 crate::export::EncoderSeat::default(),
5414 Limiter::default(),
5415 rate,
5416 0,
5417 )
5418 };
5419 // Unset is the line left out, so a project nobody has chosen a rate for
5420 // is the bytes a v16 file was bar the version line.
5421 let unset = bytes(None);
5422 assert!(
5423 !String::from_utf8_lossy(&unset).contains("samplerate"),
5424 "no pick is the line left out: {}",
5425 String::from_utf8_lossy(&unset)
5426 );
5427 assert_eq!(parse(&unset, &dir).expect("v17 parses").sample_rate, None);
5428 for rate in [44_100, 48_000, 96_000] {
5429 let written = bytes(Some(rate));
5430 let text = String::from_utf8_lossy(&written).to_string();
5431 assert!(text.contains(&format!("samplerate {rate}\n")), "{text}");
5432 assert_eq!(
5433 parse(&written, &dir).expect("v17 parses").sample_rate,
5434 Some(rate)
5435 );
5436 }
5437 // A v16 project had no rate of its own to say: the field comes back
5438 // `None`, which is what "derive it from the source" already meant.
5439 let v16 = b"edith 16\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5440 video 1 0 0 30 0 - - - fit 1000\n";
5441 assert_eq!(parse(v16, &dir).expect("v16 still loads").sample_rate, None);
5442 // ...and the line is not a v16 line: a dialect may not be mixed.
5443 let mixed = parse(b"edith 16\nsource 0 a.mp4\nsamplerate 48000\n", &dir)
5444 .unwrap_err()
5445 .to_string();
5446 assert_eq!(mixed, "line 3: unknown keyword \"samplerate\"");
5447 // A number out of a sound rate's range is a corrupt line, by name.
5448 for line in ["samplerate 0\n", "samplerate 500000\n", "samplerate nope\n"] {
5449 let file = format!("edith 18\nsource 0 a.mp4\n{line}");
5450 assert!(
5451 parse(file.as_bytes(), &dir).is_err(),
5452 "{line:?} is not a sound rate line"
5453 );
5454 }
5455 }
5456
5457 /// The v11 line: the HDR rendition, written by name, read back as the very
5458 /// preset -- and the dialect before it, which had no way to say one and
5459 /// meant the published conversion.
5460 #[test]
5461 fn the_tone_map_round_trips_by_name_and_a_v10_file_is_the_reference_one() {
5462 let dir = PathBuf::from("/proj");
5463 let (_, sources, lanes) = doc();
5464 for preset in crate::tonemap::Preset::ALL {
5465 let bytes = super::emit(
5466 &dir,
5467 &sources,
5468 &lanes,
5469 &[],
5470 &[],
5471 &[],
5472 &[],
5473 &[],
5474 &[],
5475 (1280, 720),
5476 None,
5477 preset,
5478 false,
5479 true,
5480 crate::export::EncoderSeat::default(),
5481 Limiter::default(),
5482 None,
5483 0,
5484 );
5485 let text = String::from_utf8_lossy(&bytes).to_string();
5486 assert_eq!(
5487 text.contains(&format!("tonemap {}\n", preset.name())),
5488 preset != crate::tonemap::Preset::default(),
5489 "the default is the line left out: {text}"
5490 );
5491 assert_eq!(parse(&bytes, &dir).expect("v11 parses").tone, preset);
5492 }
5493
5494 // A v10 file is a project shown the published way, and re-saving it
5495 // writes v11 with nothing more in it.
5496 let v10 = b"edith 10\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5497 video 1 0 0 30 0 - - - fit 1000\n";
5498 let old = parse(v10, &dir).expect("v10 still loads");
5499 assert_eq!(old.tone, crate::tonemap::Preset::Reference);
5500 // ...and the line itself is not a v10 line: a dialect may not be mixed.
5501 let mixed = parse(b"edith 10\nsource 0 a.mp4\ntonemap vivid\n", &dir)
5502 .unwrap_err()
5503 .to_string();
5504 assert_eq!(mixed, "line 3: unknown keyword \"tonemap\"");
5505 // A rendition nobody wrote is a corrupt line, by name -- not a silent
5506 // fall back to another picture.
5507 for line in ["tonemap\n", "tonemap bright\n", "tonemap Vivid\n"] {
5508 let file = format!("edith 11\nsource 0 a.mp4\n{line}");
5509 assert!(
5510 parse(file.as_bytes(), &dir).is_err(),
5511 "{line:?} is not a tonemap line"
5512 );
5513 }
5514 }
5515
5516 fn clip(start: u32, in_frame: u32, out_frame: u32, source: usize, link: Option<u32>) -> Clip {
5517 Clip {
5518 speed_keys: Vec::new(),
5519 reversed: false,
5520 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5521 angle: Default::default(),
5522 fade_in: 0,
5523 fade_out: 0,
5524 transition_out: 0,
5525 transition_kind: Default::default(),
5526 visualizer: 0,
5527 viz_paint: 0,
5528 gain_db: 0.0,
5529 gain_keys: Vec::new(),
5530 pan: 0,
5531 transform_keys: Vec::new(),
5532 opacity_keys: Vec::new(),
5533 color_keys: Vec::new(),
5534 effects: Vec::new(),
5535 start,
5536 in_frame,
5537 out_frame,
5538 source,
5539 link,
5540 eq: None,
5541 color: None,
5542 transform: None,
5543 fit: FitPolicy::default(),
5544 speed: Speed::NORMAL,
5545 pitch: 0.0,
5546 }
5547 }
5548
5549 /// [`emit`] for a timeline that equalizes nothing, which is every case that
5550 /// predates the eq lines.
5551 fn flat(
5552 dir: &Path,
5553 sources: &[Source],
5554 lanes: &[(LaneKind, Vec<Clip>)],
5555 playhead: u32,
5556 ) -> Vec<u8> {
5557 emit(dir, sources, lanes, &[], &[], (1280, 720), playhead)
5558 }
5559
5560 /// Two sources, one under the project's own directory and one not, a clip
5561 /// from each on the video lane, and an audio lane with a gap in the middle
5562 /// -- the shape every case below starts from.
5563 fn source(path: &str, audio_stream: usize) -> Source {
5564 Source {
5565 path: PathBuf::from(path),
5566 audio_stream,
5567 ..Default::default()
5568 }
5569 }
5570
5571 /// Lanes in display order, as [`Document::lanes`] holds them.
5572 type Lanes = Vec<(LaneKind, Vec<Clip>)>;
5573
5574 /// `V1` then `A1`, the shape every dialect before v4 held.
5575 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Lanes {
5576 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
5577 }
5578
5579 fn doc() -> (PathBuf, Vec<Source>, Lanes) {
5580 (
5581 PathBuf::from("/proj"),
5582 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
5583 two(
5584 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 10, 20, 1, Some(1))],
5585 vec![clip(0, 0, 30, 0, Some(0))],
5586 ),
5587 )
5588 }
5589
5590 #[test]
5591 fn relative_and_absolute_paths_round_trip() {
5592 let (dir, sources, lanes) = doc();
5593 let bytes = flat(&dir, &sources, &lanes, 12);
5594 assert_eq!(
5595 String::from_utf8_lossy(&bytes),
5596 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
5597 source 2 /elsewhere/b.mp4\n\
5598 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\
5599 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n",
5600 "the file under the project directory is written relative to it, \
5601 each with the audio stream it plays"
5602 );
5603 let back = parse(&bytes, &dir).expect("parse");
5604 assert_eq!(back.sources, sources, "relative entries rejoin the dir");
5605 assert_eq!(
5606 back.lanes, lanes,
5607 "both lanes, in display order; the trailing gap needs no line"
5608 );
5609 assert_eq!(back.playhead, 12);
5610 // ...and emitting the parsed document reproduces the same bytes.
5611 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
5612 }
5613
5614 /// The whole of the bump: a project of any number of lanes writes and reads
5615 /// back, in display order, empty lanes and cross-lane groups included.
5616 #[test]
5617 fn any_number_of_lanes_round_trips() {
5618 let dir = PathBuf::from("/proj");
5619 let sources = vec![source("/proj/a.mp4", 0)];
5620 // V1, A1, V2, A2 in *display* order -- the interleaving a front-end
5621 // shows, not video-then-audio -- with one take grouped across V1 and A2
5622 // (no paired ord, the lanes between them empty of it) and an A1 holding
5623 // nothing at all.
5624 let lanes = vec![
5625 (LaneKind::Video, vec![clip(0, 0, 30, 0, Some(4))]),
5626 (LaneKind::Audio, Vec::new()),
5627 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
5628 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
5629 ];
5630 let bytes = flat(&dir, &sources, &lanes, 7);
5631 assert_eq!(
5632 String::from_utf8_lossy(&bytes),
5633 "edith 30\nplayhead 7\nresolution 1280 720\nsource 0 a.mp4\n\
5634 video 1 0 0 30 0 4 - - fit 1000 0 0 0 - 0 0\naudio 1\n\
5635 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",
5636 "an empty lane is a line of its own; everything else is its clips"
5637 );
5638 let back = parse(&bytes, &dir).expect("parse");
5639 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
5640 assert_eq!(back.playhead, 7);
5641 assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
5642
5643 // A lane number may not skip one of its kind: that lane was declared by
5644 // nothing, and the refusal names it.
5645 for (file, want) in [
5646 (
5647 "edith 4\nsource 0 a.mp4\nvideo 2 0 0 30 0 -\n",
5648 "line 3: lane V2 comes before V1",
5649 ),
5650 (
5651 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\naudio 3\n",
5652 "line 4: lane A3 comes before A1",
5653 ),
5654 (
5655 "edith 4\nsource 0 a.mp4\nvideo 0 0 0 30 0 -\n",
5656 "line 3: lane numbers start at 1",
5657 ),
5658 // The clip fields are still the clip fields, one lane number on.
5659 (
5660 "edith 4\nsource 0 a.mp4\nvideo 1 0 0 30 0\n",
5661 "line 3: clip wants 5 fields, found 4",
5662 ),
5663 // ...and a v4 line in a v3 file reads as the garbled clip it is.
5664 (
5665 "edith 3\nsource 0 a.mp4\nvideo 1 0 0 30 0 -\n",
5666 "line 3: clip wants 5 fields, found 6",
5667 ),
5668 ] {
5669 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
5670 }
5671 // Lanes and nothing on them is the emptied timeline, saved: a project.
5672 let empty = parse(b"edith 4\nsource 0 a.mp4\nvideo 1\naudio 1\n", &dir).expect("parse");
5673 assert!(empty.lanes.iter().all(|(_, clips)| clips.is_empty()));
5674 assert_eq!(empty.lanes.len(), 2, "and its lanes survive the round trip");
5675 }
5676
5677 /// One band, spelled the way an eq line spells it.
5678 fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
5679 Band {
5680 freq_hz,
5681 gain_db,
5682 q,
5683 kind,
5684 }
5685 }
5686
5687 /// The whole of the v5 bump: the clips name a shared equalizer table, the
5688 /// bytes are the ones documented at the top of this file, and every f32 in
5689 /// them comes back *bit* for bit -- which is what makes a re-save of a
5690 /// loaded project produce the same file rather than a drifting one.
5691 #[test]
5692 fn equalizers_round_trip_bit_exactly_and_are_shared() {
5693 let dir = PathBuf::from("/proj");
5694 let sources = vec![source("/proj/a.mp4", 0)];
5695 let eq = vec![
5696 EqParams {
5697 bands: vec![
5698 band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
5699 band_of(1000.0, 4.5, 1.0, BandKind::Peak),
5700 ],
5701 },
5702 // The awkward ones: a value needing all 24 mantissa bits, one whose
5703 // shortest spelling is exponential, a subnormal, and a negative
5704 // zero -- plus the empty cascade, which is a setting like any other.
5705 EqParams {
5706 bands: vec![band_of(
5707 16_777_215.0,
5708 -0.1,
5709 f32::MIN_POSITIVE / 3.0,
5710 BandKind::HighShelf,
5711 )],
5712 },
5713 EqParams { bands: Vec::new() },
5714 ];
5715 // Two clips share entry 0, so it is written once; one clip plays flat.
5716 let lanes = two(
5717 vec![
5718 Clip {
5719 fade_in: 0,
5720 fade_out: 0,
5721 transition_out: 0,
5722 transition_kind: Default::default(),
5723 visualizer: 0,
5724 viz_paint: 0,
5725 gain_db: 0.0,
5726 eq: Some(0),
5727 ..clip(0, 0, 30, 0, Some(0))
5728 },
5729 Clip {
5730 fade_in: 0,
5731 fade_out: 0,
5732 transition_out: 0,
5733 transition_kind: Default::default(),
5734 visualizer: 0,
5735 viz_paint: 0,
5736 gain_db: 0.0,
5737 eq: Some(1),
5738 ..clip(30, 10, 20, 0, None)
5739 },
5740 ],
5741 vec![
5742 Clip {
5743 fade_in: 0,
5744 fade_out: 0,
5745 transition_out: 0,
5746 transition_kind: Default::default(),
5747 visualizer: 0,
5748 viz_paint: 0,
5749 gain_db: 0.0,
5750 eq: Some(0),
5751 ..clip(0, 0, 30, 0, Some(0))
5752 },
5753 Clip {
5754 fade_in: 0,
5755 fade_out: 0,
5756 transition_out: 0,
5757 transition_kind: Default::default(),
5758 visualizer: 0,
5759 viz_paint: 0,
5760 gain_db: 0.0,
5761 eq: Some(2),
5762 ..clip(30, 0, 10, 0, None)
5763 },
5764 ],
5765 );
5766 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
5767 assert_eq!(
5768 String::from_utf8_lossy(&bytes),
5769 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5770 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
5771 eq 16777215.0:-0.1:3.918315e-39:hs\n\
5772 eq\n\
5773 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\
5774 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",
5775 "the table comes before the clips, and a clip names a line of it"
5776 );
5777
5778 let back = parse(&bytes, &dir).expect("parse");
5779 assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
5780 for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
5781 for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
5782 assert_eq!(
5783 (
5784 got.freq_hz.to_bits(),
5785 got.gain_db.to_bits(),
5786 got.q.to_bits(),
5787 got.kind
5788 ),
5789 (
5790 want.freq_hz.to_bits(),
5791 want.gain_db.to_bits(),
5792 want.q.to_bits(),
5793 want.kind
5794 ),
5795 "eq {i} band {b} came back as other bits"
5796 );
5797 }
5798 }
5799 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
5800 assert_eq!(
5801 emit(
5802 &dir,
5803 &back.sources,
5804 &back.lanes,
5805 &back.eq,
5806 &back.color,
5807 (1280, 720),
5808 0
5809 ),
5810 bytes
5811 );
5812 }
5813
5814 /// The whole of the v6 bump, the eq test's twin: the clips name a shared
5815 /// colour table, the bytes are the ones documented at the top of this file,
5816 /// and every f32 comes back *bit* for bit, so a re-save is the same file.
5817 #[test]
5818 fn colours_round_trip_bit_exactly_and_are_shared() {
5819 let dir = PathBuf::from("/proj");
5820 let sources = vec![source("/proj/a.mp4", 0)];
5821 let color = vec![
5822 ColorParams {
5823 brightness: 0.1,
5824 contrast: 1.2,
5825 saturation: 0.9,
5826 tint: -0.3,
5827 ..Default::default()
5828 },
5829 // The awkward ones again: all 24 mantissa bits, an exponential
5830 // spelling, a subnormal and a negative zero -- and the identity,
5831 // which is a setting like any other.
5832 ColorParams {
5833 brightness: -0.000_000_1,
5834 contrast: 16_777_215.0,
5835 saturation: f32::MIN_POSITIVE / 3.0,
5836 tint: -0.0,
5837 ..Default::default()
5838 },
5839 ColorParams::default(),
5840 ];
5841 // Two clips share entry 0, so it is written once; one clip is ungraded.
5842 let lanes = two(
5843 vec![
5844 Clip {
5845 fade_in: 0,
5846 fade_out: 0,
5847 transition_out: 0,
5848 transition_kind: Default::default(),
5849 visualizer: 0,
5850 viz_paint: 0,
5851 gain_db: 0.0,
5852 color: Some(0),
5853 fit: FitPolicy::default(),
5854 speed: Speed::NORMAL,
5855 ..clip(0, 0, 30, 0, Some(0))
5856 },
5857 Clip {
5858 fade_in: 0,
5859 fade_out: 0,
5860 transition_out: 0,
5861 transition_kind: Default::default(),
5862 visualizer: 0,
5863 viz_paint: 0,
5864 gain_db: 0.0,
5865 color: Some(1),
5866 fit: FitPolicy::default(),
5867 speed: Speed::NORMAL,
5868 ..clip(30, 10, 20, 0, None)
5869 },
5870 ],
5871 vec![
5872 Clip {
5873 fade_in: 0,
5874 fade_out: 0,
5875 transition_out: 0,
5876 transition_kind: Default::default(),
5877 visualizer: 0,
5878 viz_paint: 0,
5879 gain_db: 0.0,
5880 color: Some(0),
5881 fit: FitPolicy::default(),
5882 speed: Speed::NORMAL,
5883 ..clip(0, 0, 30, 0, Some(0))
5884 },
5885 Clip {
5886 fade_in: 0,
5887 fade_out: 0,
5888 transition_out: 0,
5889 transition_kind: Default::default(),
5890 visualizer: 0,
5891 viz_paint: 0,
5892 gain_db: 0.0,
5893 color: Some(2),
5894 fit: FitPolicy::default(),
5895 speed: Speed::NORMAL,
5896 ..clip(30, 0, 10, 0, None)
5897 },
5898 ],
5899 );
5900 let bytes = emit(&dir, &sources, &lanes, &[], &color, (1280, 720), 0);
5901 assert_eq!(
5902 String::from_utf8_lossy(&bytes),
5903 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
5904 color 0.1:1.2:0.9:-0.3\n\
5905 color -1e-7:16777215.0:3.918315e-39:-0.0\n\
5906 color 0.0:1.0:1.0:0.0\n\
5907 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\
5908 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",
5909 "the table comes before the clips, and a clip names a line of it"
5910 );
5911
5912 let back = parse(&bytes, &dir).expect("parse");
5913 assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
5914 for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
5915 assert_eq!(
5916 (
5917 got.brightness.to_bits(),
5918 got.contrast.to_bits(),
5919 got.saturation.to_bits(),
5920 got.tint.to_bits()
5921 ),
5922 (
5923 want.brightness.to_bits(),
5924 want.contrast.to_bits(),
5925 want.saturation.to_bits(),
5926 want.tint.to_bits()
5927 ),
5928 "color {i} came back as other bits"
5929 );
5930 }
5931 assert_eq!(back.color.len(), 3);
5932 assert_eq!(
5933 emit(
5934 &dir,
5935 &back.sources,
5936 &back.lanes,
5937 &back.eq,
5938 &back.color,
5939 (1280, 720),
5940 0
5941 ),
5942 bytes
5943 );
5944 }
5945
5946 /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
5947 /// intact, and re-saving it writes the new magic and a `-` colour field.
5948 #[test]
5949 fn a_v5_file_grades_nothing() {
5950 let dir = PathBuf::from("/proj");
5951 let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
5952 video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
5953 let old = parse(v5, &dir).expect("v5 parses");
5954 assert!(old.color.is_empty(), "nothing before v6 grades anything");
5955 assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
5956 assert_eq!(old.lanes[0].1[0].eq, Some(0));
5957 assert!(old.lanes[0].1[0].color.is_none());
5958 assert_eq!(
5959 String::from_utf8_lossy(&emit(
5960 &dir,
5961 &old.sources,
5962 &old.lanes,
5963 &old.eq,
5964 &old.color,
5965 (1280, 720),
5966 old.playhead
5967 )),
5968 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
5969 eq 80.0:-3.0:0.707:ls\n\
5970 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"
5971 );
5972 }
5973
5974 /// The whole of the v8 bump, the eq and colour tests' twin: a clip's rate is
5975 /// written on its own line, comes back as the very number that was set, and
5976 /// a v7 file -- which has no such field -- loads at real time and re-saves
5977 /// saying so.
5978 #[test]
5979 fn speeds_round_trip_and_a_v7_file_plays_at_real_time() {
5980 let dir = PathBuf::from("/proj");
5981 let sources = vec![Source::new("/proj/a.mp4", 0)];
5982 let speeded = |start, in_frame, out_frame, permille| Clip {
5983 speed_keys: Vec::new(),
5984 reversed: false,
5985 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5986 angle: Default::default(),
5987 fade_in: 0,
5988 fade_out: 0,
5989 transition_out: 0,
5990 transition_kind: Default::default(),
5991 visualizer: 0,
5992 viz_paint: 0,
5993 gain_db: 0.0,
5994 gain_keys: Vec::new(),
5995 pan: 0,
5996 transform_keys: Vec::new(),
5997 opacity_keys: Vec::new(),
5998 color_keys: Vec::new(),
5999 effects: Vec::new(),
6000 start,
6001 in_frame,
6002 out_frame,
6003 source: 0,
6004 link: None,
6005 eq: None,
6006 color: None,
6007 transform: None,
6008 fit: FitPolicy::default(),
6009 speed: Speed::from_permille(permille),
6010 pitch: 0.0,
6011 };
6012 // 30 source frames at 2x is 15 timeline frames, which is where the
6013 // second clip starts -- the file writes the source range and the rate,
6014 // and the length on the timeline is derived from the two.
6015 let lanes = vec![
6016 (
6017 LaneKind::Video,
6018 vec![speeded(0, 0, 30, 2000), speeded(15, 30, 40, 250)],
6019 ),
6020 (LaneKind::Audio, vec![speeded(0, 0, 30, 2000)]),
6021 ];
6022 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6023 assert_eq!(
6024 String::from_utf8_lossy(&bytes),
6025 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6026 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\
6027 audio 1 0 0 30 0 - - - fit 2000 0 0 0 - 0 0\n",
6028 "the rate is the clip line's last field, in thousandths"
6029 );
6030 let back = parse(&bytes, &dir).expect("parse");
6031 assert_eq!(back.lanes, lanes, "every clip keeps the rate it named");
6032
6033 // ...and the dialect before it, which had no rate to name.
6034 let v7 = b"edith 7\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6035 video 1 0 0 30 0 0 - - fit\naudio 1 0 0 30 0 0 - - fit\n";
6036 let old = parse(v7, &dir).expect("v7 parses");
6037 assert!(
6038 old.lanes
6039 .iter()
6040 .flat_map(|(_, clips)| clips)
6041 .all(|c| c.speed == Speed::NORMAL),
6042 "nothing before v8 plays at anything but real time"
6043 );
6044 assert_eq!(
6045 String::from_utf8_lossy(&emit(
6046 &dir,
6047 &old.sources,
6048 &old.lanes,
6049 &old.eq,
6050 &old.color,
6051 (1280, 720),
6052 old.playhead
6053 )),
6054 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6055 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"
6056 );
6057 // A rate outside what the editor can set is a corrupt line, by name.
6058 let bad = b"edith 8\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 9000\n";
6059 assert_eq!(
6060 parse(bad, &dir).unwrap_err().to_string(),
6061 "line 3: speed 9000 is outside 250-4000 thousandths"
6062 );
6063 }
6064
6065 #[test]
6066 fn a_v17_file_loads_with_zero_fades_and_fades_round_trip_bit_exactly() {
6067 let dir = PathBuf::from("/proj");
6068 // The v17 dialect: nine clip fields, the last the speed -- no fade
6069 // pair after it at all, not even zeroes.
6070 let v17 = b"edith 17\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6071 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
6072 let old = parse(v17, &dir).expect("v17 parses");
6073 assert!(
6074 old.lanes
6075 .iter()
6076 .flat_map(|(_, clips)| clips)
6077 .all(|c| c.fade_in == 0 && c.fade_out == 0),
6078 "nothing before v18 had a fade to name"
6079 );
6080
6081 // ...and the dialect that does: nonzero fades on both edges, written
6082 // and read back as the very numbers.
6083 let sources = vec![Source::new("/proj/a.mp4", 0)];
6084 let faded = Clip {
6085 speed_keys: Vec::new(),
6086 reversed: false,
6087 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6088 angle: Default::default(),
6089 fade_in: 5,
6090 fade_out: 7,
6091 transition_out: 0,
6092 transition_kind: Default::default(),
6093 visualizer: 0,
6094 viz_paint: 0,
6095 gain_db: 0.0,
6096 gain_keys: Vec::new(),
6097 pan: 0,
6098 transform_keys: Vec::new(),
6099 opacity_keys: Vec::new(),
6100 color_keys: Vec::new(),
6101 effects: Vec::new(),
6102 start: 0,
6103 in_frame: 0,
6104 out_frame: 30,
6105 source: 0,
6106 link: None,
6107 eq: None,
6108 color: None,
6109 transform: None,
6110 fit: FitPolicy::default(),
6111 speed: Speed::NORMAL,
6112 pitch: 0.0,
6113 };
6114 let lanes = vec![(LaneKind::Video, vec![faded])];
6115 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6116 assert_eq!(
6117 String::from_utf8_lossy(&bytes),
6118 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6119 video 1 0 0 30 0 - - - fit 1000 5 7 0 - 0 0\n",
6120 "the fades are the clip line's last two fields"
6121 );
6122 let back = parse(&bytes, &dir).expect("parse");
6123 assert_eq!(
6124 back.lanes, lanes,
6125 "the fades round trip as the very numbers"
6126 );
6127 }
6128
6129 /// The whole of the v19 bump, the fade test's twin: a clip's dissolve into
6130 /// its successor is written as the clip line's own last field, comes back
6131 /// as the very number that was set, and a v18 file -- which has no such
6132 /// field -- loads with every clip's [`Clip::transition_out`] at zero and
6133 /// re-saves saying so.
6134 #[test]
6135 fn a_v18_file_loads_with_no_transition_and_transitions_round_trip_bit_exactly() {
6136 let dir = PathBuf::from("/proj");
6137 // The v18 dialect: eleven clip fields, the last the fade-out -- no
6138 // transition field after it at all, not even a zero.
6139 let v18 = b"edith 18\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6140 video 1 0 0 30 0 - - - fit 1000 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0\n";
6141 let old = parse(v18, &dir).expect("v18 parses");
6142 assert!(
6143 old.lanes
6144 .iter()
6145 .flat_map(|(_, clips)| clips)
6146 .all(|c| c.transition_out == 0),
6147 "nothing before v19 had a dissolve to name"
6148 );
6149
6150 // ...and the dialect that does: a nonzero dissolve, written and read
6151 // back as the very number.
6152 let sources = vec![Source::new("/proj/a.mp4", 0)];
6153 let dissolving = Clip {
6154 speed_keys: Vec::new(),
6155 reversed: false,
6156 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6157 angle: Default::default(),
6158 fade_in: 0,
6159 fade_out: 0,
6160 transition_out: 9,
6161 transition_kind: Default::default(),
6162 visualizer: 0,
6163 viz_paint: 0,
6164 gain_db: 0.0,
6165 gain_keys: Vec::new(),
6166 pan: 0,
6167 transform_keys: Vec::new(),
6168 opacity_keys: Vec::new(),
6169 color_keys: Vec::new(),
6170 effects: Vec::new(),
6171 start: 0,
6172 in_frame: 0,
6173 out_frame: 30,
6174 source: 0,
6175 link: None,
6176 eq: None,
6177 color: None,
6178 transform: None,
6179 fit: FitPolicy::default(),
6180 speed: Speed::NORMAL,
6181 pitch: 0.0,
6182 };
6183 let lanes = vec![(LaneKind::Video, vec![dissolving])];
6184 let bytes = emit(&dir, &sources, &lanes, &[], &[], (1280, 720), 0);
6185 assert_eq!(
6186 String::from_utf8_lossy(&bytes),
6187 "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6188 video 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n",
6189 "the dissolve is the clip line's own last field"
6190 );
6191 let back = parse(&bytes, &dir).expect("parse");
6192 assert_eq!(
6193 back.lanes, lanes,
6194 "the dissolve round trips as the very number"
6195 );
6196 }
6197
6198 /// The clip's packed look (v23): a chosen strand colour rides in the
6199 /// field's own bytes under the top bit and comes back bit-exact, a v22
6200 /// file's 32-bit value is the low half of that field with no strand
6201 /// colour, and a file older than the field itself is the zero it always
6202 /// was.
6203 #[test]
6204 fn a_strand_colour_round_trips_and_a_v22_look_stays_32_bit() {
6205 use crate::decode::{
6206 VIZ_PAINT_AZURE, viz_hue_ui, viz_sat_ui, viz_strand_set, with_viz_paint_strand_hue,
6207 with_viz_paint_strand_sat,
6208 };
6209 let (dir, sources, lanes) = doc();
6210 let mut painted = lanes.clone();
6211 // Azure, its dual half a chosen green rather than the automatic
6212 // complement of the clip's own hue.
6213 let chosen = with_viz_paint_strand_sat(with_viz_paint_strand_hue(VIZ_PAINT_AZURE, 64), 200);
6214 assert!(viz_strand_set(chosen));
6215 painted[0].1[0].viz_paint = chosen;
6216 let bytes = flat(&dir, &sources, &painted, 0);
6217 assert!(
6218 bytes.starts_with(b"edith 30\n"),
6219 "a project with a strand colour saves as v23: {}",
6220 String::from_utf8_lossy(&bytes)
6221 );
6222 let back = parse(&bytes, &dir).expect("v23 parses");
6223 assert_eq!(back.lanes, painted, "the look round-trips bit-exactly");
6224
6225 // A v22 file's field is a u32: the value lands in the low half
6226 // untouched, and a strand colour it cannot carry reads as auto.
6227 let look = VIZ_PAINT_AZURE as u32;
6228 let v22 = format!(
6229 "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6230 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 {look}\n"
6231 );
6232 let old = parse(v22.as_bytes(), &dir).expect("v22 still loads");
6233 let paint = old.lanes[0].1[0].viz_paint;
6234 assert_eq!(paint, u64::from(look), "the low half is the v22 value");
6235 assert!(!viz_strand_set(paint), "a v22 look chose no strand colour");
6236 assert_eq!(viz_hue_ui(paint), 150);
6237 assert_eq!(viz_sat_ui(paint), 160);
6238 // ...and a file older than the field is the zero that means the
6239 // azure default, as it was before the field was widened.
6240 let v21 = b"edith 21\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6241 video 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0\n";
6242 let older = parse(v21, &dir).expect("v21 still loads");
6243 assert_eq!(older.lanes[0].1[0].viz_paint, 0);
6244 }
6245
6246 /// A v19 file is a v20 one that places no clip anywhere but its fit
6247 /// policy's own spot: it loads with every clip's [`Clip::transform`] at
6248 /// `None`, which is what a v19 file's missing field still means.
6249 #[test]
6250 fn a_v19_file_loads_untransformed() {
6251 let dir = PathBuf::from("/proj");
6252 // The v19 dialect: twelve clip fields, the last the transition -- no
6253 // transform field after it at all, not even a `-`.
6254 let v19 = b"edith 19\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6255 video 1 0 0 30 0 - - - fit 1000 0 0 0\naudio 1 0 0 30 0 - - - fit 1000 0 0 0\n";
6256 let old = parse(v19, &dir).expect("v19 parses");
6257 assert!(old.transform.is_empty(), "nothing before v20 has a table");
6258 assert!(
6259 old.lanes
6260 .iter()
6261 .flat_map(|(_, clips)| clips)
6262 .all(|c| c.transform.is_none()),
6263 "nothing before v20 had a placement to name"
6264 );
6265 }
6266
6267 /// [`colours_round_trip_bit_exactly_and_are_shared`]'s twin: two clips
6268 /// sharing one transform table entry write it once, and both bytes and
6269 /// values come back bit-exact.
6270 #[test]
6271 fn transforms_round_trip_bit_exactly_and_are_shared() {
6272 let dir = PathBuf::from("/proj");
6273 let sources = vec![source("/proj/a.mp4", 0)];
6274 let transform = vec![
6275 TransformParams {
6276 pos_x: 0.1,
6277 pos_y: -0.2,
6278 scale: 1.5,
6279 rotate: 90.0,
6280 crop_l: 0.1,
6281 crop_r: 0.0,
6282 crop_t: 0.0,
6283 crop_b: 0.05,
6284 opacity: 0.25,
6285 },
6286 // The awkward ones again: all 24 mantissa bits, an exponential
6287 // spelling, a subnormal and a negative zero -- and the identity,
6288 // which is a setting like any other.
6289 TransformParams {
6290 pos_x: -0.000_000_1,
6291 pos_y: 16_777_215.0,
6292 scale: f32::MIN_POSITIVE / 3.0,
6293 rotate: -0.0,
6294 crop_l: 0.0,
6295 crop_r: 0.0,
6296 crop_t: 0.0,
6297 crop_b: 0.0,
6298 opacity: 1.0,
6299 },
6300 TransformParams::default(),
6301 ];
6302 // Two clips share entry 0, so it is written once; one clip is untransformed.
6303 let lanes = two(
6304 vec![
6305 Clip {
6306 fade_in: 0,
6307 fade_out: 0,
6308 transition_out: 0,
6309 transition_kind: Default::default(),
6310 visualizer: 0,
6311 viz_paint: 0,
6312 gain_db: 0.0,
6313 transform: Some(0),
6314 fit: FitPolicy::default(),
6315 speed: Speed::NORMAL,
6316 ..clip(0, 0, 30, 0, Some(0))
6317 },
6318 Clip {
6319 fade_in: 0,
6320 fade_out: 0,
6321 transition_out: 0,
6322 transition_kind: Default::default(),
6323 visualizer: 0,
6324 viz_paint: 0,
6325 gain_db: 0.0,
6326 transform: Some(1),
6327 fit: FitPolicy::default(),
6328 speed: Speed::NORMAL,
6329 ..clip(30, 10, 20, 0, None)
6330 },
6331 ],
6332 vec![
6333 Clip {
6334 fade_in: 0,
6335 fade_out: 0,
6336 transition_out: 0,
6337 transition_kind: Default::default(),
6338 visualizer: 0,
6339 viz_paint: 0,
6340 gain_db: 0.0,
6341 transform: Some(0),
6342 fit: FitPolicy::default(),
6343 speed: Speed::NORMAL,
6344 ..clip(0, 0, 30, 0, Some(0))
6345 },
6346 Clip {
6347 fade_in: 0,
6348 fade_out: 0,
6349 transition_out: 0,
6350 transition_kind: Default::default(),
6351 visualizer: 0,
6352 viz_paint: 0,
6353 gain_db: 0.0,
6354 transform: Some(2),
6355 fit: FitPolicy::default(),
6356 speed: Speed::NORMAL,
6357 ..clip(30, 0, 10, 0, None)
6358 },
6359 ],
6360 );
6361 let bytes = super::emit(
6362 &dir,
6363 &sources,
6364 &lanes,
6365 &[],
6366 &[],
6367 &[],
6368 &[],
6369 &[],
6370 &transform,
6371 (1280, 720),
6372 None,
6373 crate::tonemap::Preset::default(),
6374 false,
6375 true,
6376 crate::export::EncoderSeat::default(),
6377 Limiter::default(),
6378 None,
6379 0,
6380 );
6381 assert_eq!(
6382 String::from_utf8_lossy(&bytes),
6383 "edith 31\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
6384 transform 0.1:-0.2:1.5:90.0:0.1:0.0:0.0:0.05:0.25\n\
6385 transform -1e-7:16777215.0:3.918315e-39:-0.0:0.0:0.0:0.0:0.0\n\
6386 transform 0.0:0.0:1.0:0.0:0.0:0.0:0.0:0.0\n\
6387 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\
6388 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",
6389 "the table comes before the clips, and a clip names a line of it"
6390 );
6391
6392 let back = parse(&bytes, &dir).expect("parse");
6393 assert_eq!(back.lanes, lanes, "every clip keeps the transform it named");
6394 for (i, (got, want)) in back.transform.iter().zip(&transform).enumerate() {
6395 assert_eq!(
6396 (
6397 got.pos_x.to_bits(),
6398 got.pos_y.to_bits(),
6399 got.scale.to_bits(),
6400 got.rotate.to_bits(),
6401 got.crop_l.to_bits(),
6402 got.crop_r.to_bits(),
6403 got.crop_t.to_bits(),
6404 got.crop_b.to_bits(),
6405 got.opacity.to_bits(),
6406 ),
6407 (
6408 want.pos_x.to_bits(),
6409 want.pos_y.to_bits(),
6410 want.scale.to_bits(),
6411 want.rotate.to_bits(),
6412 want.crop_l.to_bits(),
6413 want.crop_r.to_bits(),
6414 want.crop_t.to_bits(),
6415 want.crop_b.to_bits(),
6416 want.opacity.to_bits(),
6417 ),
6418 "transform {i} came back as other bits"
6419 );
6420 }
6421 assert_eq!(back.transform.len(), 3);
6422 }
6423
6424 /// The whole of the v9 bump, the speed test's twin: the mix a project was
6425 /// left at -- every track's own volume and the master limiter -- plus the
6426 /// rate it was cut at, all written, all read back as the very numbers, and
6427 /// a v8 file (which has none of them) loading flat and unlimited.
6428 #[test]
6429 fn the_mix_and_the_rate_round_trip_and_a_v8_file_is_flat() {
6430 let dir = PathBuf::from("/proj");
6431 let sources = vec![Source::new("/proj/a.mp4", 0)];
6432 let lanes = vec![
6433 (LaneKind::Video, vec![clip(0, 0, 30, 0, None)]),
6434 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
6435 // A second audio track, turned down: the gain lines are per lane,
6436 // so the two must not run into one another.
6437 (LaneKind::Audio, vec![clip(0, 0, 30, 0, None)]),
6438 ];
6439 let limiter = Limiter {
6440 ceiling_db: -1.5,
6441 on: true,
6442 };
6443 let bytes = super::emit(
6444 &dir,
6445 &sources,
6446 &lanes,
6447 &[0.0, 3.0, -6.5],
6448 &[],
6449 &[],
6450 &[],
6451 &[],
6452 &[],
6453 (1280, 720),
6454 Some(23.976023976023978),
6455 crate::tonemap::Preset::default(),
6456 false,
6457 true,
6458 crate::export::EncoderSeat::default(),
6459 limiter,
6460 None,
6461 0,
6462 );
6463 assert_eq!(
6464 String::from_utf8_lossy(&bytes),
6465 "edith 30\nplayhead 0\nresolution 1280 720\nfps 23.976023976023978\n\
6466 limiter -1.5 on\nsource 0 a.mp4\n\
6467 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\
6468 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
6469 gain audio 1 3.0\ngain audio 2 -6.5\n",
6470 "the mix is lines of its own, the gains after the lanes they name"
6471 );
6472 let back = parse(&bytes, &dir).expect("parse");
6473 assert_eq!(back.lanes, lanes);
6474 assert_eq!(back.gains, vec![0.0, 3.0, -6.5], "one per lane, in order");
6475 assert_eq!(back.limiter, limiter);
6476 assert_eq!(back.fps, Some(23.976023976023978), "bit-exact, not 23.976");
6477
6478 // ...and the dialect before it, which carried none of the three: a v8
6479 // file mixes flat, limits nothing, and says nothing about its rate.
6480 let v8 = b"edith 8\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6481 video 1 0 0 30 0 - - - fit 1000\naudio 1 0 0 30 0 - - - fit 1000\n";
6482 let old = parse(v8, &dir).expect("v8 parses");
6483 assert_eq!(old.gains, vec![0.0, 0.0], "one per lane, all at unity");
6484 assert_eq!(old.limiter, Limiter::default());
6485 assert_eq!(old.fps, None);
6486 // A v9 file may leave all three out too, and means the same thing.
6487 assert_eq!(
6488 String::from_utf8_lossy(&emit(
6489 &dir,
6490 &old.sources,
6491 &old.lanes,
6492 &old.eq,
6493 &old.color,
6494 (1280, 720),
6495 old.playhead
6496 )),
6497 "edith 30\nplayhead 3\nresolution 1280 720\nsource 0 a.mp4\n\
6498 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"
6499 );
6500
6501 // Each of the three refuses by name, on its own line.
6502 for (text, want) in [
6503 (
6504 "edith 9\nfps nope\nsource 0 a.mp4\n",
6505 "line 2: \"nope\" is not a frame rate",
6506 ),
6507 (
6508 "edith 9\nlimiter -1.0 maybe\nsource 0 a.mp4\n",
6509 "line 2: limiter is on or off, not \"maybe\"",
6510 ),
6511 (
6512 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain audio 1 -3.0\n",
6513 "line 4: gain names a lane that is not there",
6514 ),
6515 (
6516 "edith 9\nsource 0 a.mp4\nvideo 1 0 0 30 0 - - - fit 1000\ngain lane 1 -3.0\n",
6517 "line 4: gain names \"lane\", not a lane kind",
6518 ),
6519 ] {
6520 assert_eq!(
6521 parse(text.as_bytes(), &dir).unwrap_err().to_string(),
6522 want,
6523 "{text:?}"
6524 );
6525 }
6526 // A hand-written ceiling nothing could limit at is clamped, not taken.
6527 let loud = parse(b"edith 9\nlimiter 12.0 on\nsource 0 a.mp4\n", &dir).expect("parses");
6528 assert_eq!(loud.limiter.ceiling_db, Limiter::MAX_DB);
6529 }
6530
6531 /// The refusals the colour grammar adds, each naming its line.
6532 #[test]
6533 fn a_malformed_colour_names_its_line() {
6534 let dir = PathBuf::from("/proj");
6535 let head = "edith 6\nsource 0 a.mp4\n";
6536 // v6, deliberately: the colour grammar is the same one v7 inherits, and
6537 // a v6 clip line is one field shorter.
6538 for (file, want) in [
6539 (
6540 format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
6541 "line 3: color wants 4 fields, found 3",
6542 ),
6543 (
6544 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"),
6545 "line 3: color wants 1 fields, found 2",
6546 ),
6547 (
6548 format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
6549 "line 3: \"warm\" is not a number",
6550 ),
6551 // The two values the format cannot write and read back as itself.
6552 (
6553 format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
6554 "line 3: \"inf\" is not a number",
6555 ),
6556 (
6557 format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
6558 "line 3: \"NaN\" is not a number",
6559 ),
6560 (
6561 format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
6562 "line 4: clip names color 1 of 1",
6563 ),
6564 (
6565 format!("{head}video 1 0 0 5 0 - - 0\n"),
6566 "line 3: clip names color 0 of 0",
6567 ),
6568 // A clip's colour field is not optional in v6, and the table has to
6569 // be declared before the clip that names it.
6570 (
6571 format!("{head}video 1 0 0 5 0 - -\n"),
6572 "line 3: clip wants 7 fields, found 6",
6573 ),
6574 (
6575 format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
6576 "line 4: color after a clip",
6577 ),
6578 // ...and a colour line in a file that predates them is a corrupt one.
6579 (
6580 "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
6581 "line 3: unknown keyword \"color\"",
6582 ),
6583 ] {
6584 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
6585 }
6586 }
6587
6588 /// The cut shapes are two more spellings of the same band grammar: they
6589 /// round-trip bit-exactly like the others, and a cut's gain is written as
6590 /// it was given even though the filter ignores it.
6591 #[test]
6592 fn cut_bands_round_trip_as_lc_and_hc() {
6593 let dir = PathBuf::from("/proj");
6594 let sources = vec![source("/proj/a.mp4", 0)];
6595 let eq = vec![EqParams {
6596 bands: vec![
6597 band_of(80.0, 0.0, 0.707, BandKind::LowCut),
6598 band_of(12_000.0, -6.5, 0.5, BandKind::HighCut),
6599 ],
6600 }];
6601 let lanes = two(vec![clip(0, 0, 30, 0, Some(0))], Vec::new());
6602 let bytes = emit(&dir, &sources, &lanes, &eq, &[], (1280, 720), 0);
6603 assert!(
6604 String::from_utf8_lossy(&bytes).contains("eq 80.0:0.0:0.707:lc 12000.0:-6.5:0.5:hc\n"),
6605 "the cut shapes are spelled lc and hc"
6606 );
6607
6608 let back = parse(&bytes, &dir).expect("parse");
6609 assert_eq!(back.eq, eq, "both cut bands come back as they went in");
6610 assert_eq!(back.lanes, lanes);
6611 }
6612
6613 /// The refusals the eq grammar adds, each naming its line.
6614 #[test]
6615 fn a_malformed_equalizer_names_its_line() {
6616 let dir = PathBuf::from("/proj");
6617 let head = "edith 5\nsource 0 a.mp4\n";
6618 for (file, want) in [
6619 (
6620 format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
6621 "line 3: band wants 4 fields, found 3",
6622 ),
6623 (
6624 format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
6625 "line 3: \"notch\" is not a band shape",
6626 ),
6627 (
6628 format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
6629 "line 3: \"wide\" is not a number",
6630 ),
6631 // Neither of the two values a coefficient cannot be built from, and
6632 // NaN would not even compare equal to itself on the way back.
6633 (
6634 format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
6635 "line 3: \"inf\" is not a number",
6636 ),
6637 (
6638 format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
6639 "line 3: \"NaN\" is not a number",
6640 ),
6641 (
6642 format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
6643 "line 4: clip names eq 1 of 1",
6644 ),
6645 (
6646 format!("{head}video 1 0 0 5 0 - 0\n"),
6647 "line 3: clip names eq 0 of 0",
6648 ),
6649 // A clip's eq field is not optional in v5, and the table has to be
6650 // declared before the clip that names it.
6651 (
6652 format!("{head}video 1 0 0 5 0 -\n"),
6653 "line 3: clip wants 6 fields, found 5",
6654 ),
6655 (
6656 format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
6657 "line 4: eq after a clip",
6658 ),
6659 // ...and an eq line in a file that predates them is a corrupt file.
6660 (
6661 "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
6662 "line 3: unknown keyword \"eq\"",
6663 ),
6664 ] {
6665 assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
6666 }
6667 }
6668
6669 /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
6670 /// and re-saving it writes the new magic, the `-` in every clip's eq field,
6671 /// and not one byte else.
6672 #[test]
6673 fn a_v4_file_equalizes_nothing() {
6674 let dir = PathBuf::from("/proj");
6675 let (_, sources, lanes) = doc();
6676 let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
6677 video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
6678 let old = parse(v4, &dir).expect("v4 parses");
6679 assert_eq!(
6680 (&old.sources, &old.lanes, old.playhead),
6681 (&sources, &lanes, 12)
6682 );
6683 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
6684 assert_eq!(
6685 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
6686 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
6687 source 2 /elsewhere/b.mp4\n\
6688 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\
6689 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n"
6690 );
6691 // An empty lane's line is still the whole of that lane, eq or no eq.
6692 let empty = parse(
6693 b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
6694 &dir,
6695 )
6696 .expect("parse");
6697 assert!(empty.lanes[1].1.is_empty());
6698 }
6699
6700 /// The other half of the compatibility promise: a v3 file is a v4 one
6701 /// without the lane numbers, and a v2 file names no audio stream and means
6702 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
6703 /// they always were, and saving either writes v5 with nothing else changed.
6704 #[test]
6705 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
6706 let dir = PathBuf::from("/proj");
6707 let (_, _, lanes) = doc();
6708 let v3 = b"edith 3\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
6709 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
6710 let old = parse(v3, &dir).expect("v3 parses");
6711 assert_eq!(
6712 (&old.sources, &old.lanes, old.playhead),
6713 (
6714 &vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 2)],
6715 &lanes,
6716 12
6717 ),
6718 "a v3 file loads as exactly the state its v5 twin does"
6719 );
6720 // ...and re-saved it *is* that twin: the magic and a lane number per
6721 // clip line, and not one byte else.
6722 assert_eq!(
6723 flat(&dir, &old.sources, &old.lanes, old.playhead),
6724 flat(&dir, &old.sources, &lanes, 12),
6725 );
6726
6727 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
6728 video 0 0 30 0 0\nvideo 30 10 20 1 1\naudio 0 0 30 0 0\n";
6729 let back = parse(v2, &dir).expect("v2 parses");
6730 assert_eq!(
6731 back.sources,
6732 vec![source("/proj/a.mp4", 0), source("/elsewhere/b.mp4", 0)],
6733 );
6734 assert_eq!(back.lanes, lanes);
6735
6736 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
6737 assert_eq!(
6738 String::from_utf8_lossy(&v5),
6739 "edith 30\nplayhead 12\nresolution 1280 720\nsource 0 a.mp4\n\
6740 source 0 /elsewhere/b.mp4\n\
6741 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\
6742 audio 1 0 0 30 0 0 - - fit 1000 0 0 0 - 0 0\n",
6743 "a re-saved v2 project differs only by its version, the lane \
6744 numbers, the streams it always meant and an equalizer it has none of"
6745 );
6746 let again = parse(&v5, &dir).expect("v5 parses");
6747 assert_eq!(again.sources, back.sources);
6748 }
6749
6750 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
6751 /// lanes, and saving it again writes v5.
6752 #[test]
6753 fn a_v1_file_loads_as_two_grouped_lanes() {
6754 let dir = PathBuf::from("/proj");
6755 let v1 = b"edith 1\nplayhead 5\nsource a.mp4\nclip 0 30 0\nclip 40 60 0\n";
6756 let back = parse(v1, &dir).expect("v1 parses");
6757 assert_eq!(
6758 back.lanes[0].1,
6759 vec![clip(0, 0, 30, 0, Some(0)), clip(30, 40, 60, 0, Some(1))],
6760 "v1 clips queue up: the second starts where the first ended"
6761 );
6762 assert_eq!(
6763 back.lanes,
6764 two(back.lanes[0].1.clone(), back.lanes[0].1.clone()),
6765 "one take per clip, on both lanes"
6766 );
6767 assert_eq!(back.playhead, 5);
6768 // Saved again it is the current version, which round-trips to the
6769 // same document.
6770 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
6771 assert!(v5.starts_with(b"edith 30\n"));
6772 let again = parse(&v5, &dir).expect("v5 parses");
6773 assert_eq!(again.lanes, back.lanes);
6774 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
6775 for (bytes, want) in [
6776 (
6777 &b"edith 1\nsource a.mp4\nvideo 0 0 30 0 -\n"[..],
6778 "line 3: unknown keyword \"video\"",
6779 ),
6780 (
6781 b"edith 2\nsource a.mp4\nclip 0 30 0\n",
6782 "line 3: unknown keyword \"clip\"",
6783 ),
6784 ] {
6785 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
6786 }
6787 }
6788
6789 /// A gap is the absence of a line, so a lane's placements must arrive in
6790 /// order and never overlap -- the invariant the whole model rests on.
6791 #[test]
6792 fn a_lane_out_of_order_or_overlapping_is_refused() {
6793 let dir = PathBuf::from("/proj");
6794 for bytes in [
6795 &b"edith 2\nsource a.mp4\nvideo 30 0 30 0 -\nvideo 0 0 30 0 -\n"[..],
6796 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\nvideo 10 0 30 0 -\n",
6797 ] {
6798 let err = parse(bytes, &dir).unwrap_err().to_string();
6799 assert!(err.starts_with("line 4: clip at "), "{err}");
6800 }
6801 // The lanes are independent, so a video line never crowds an audio one.
6802 assert!(
6803 parse(
6804 b"edith 2\nsource a.mp4\nvideo 0 0 30 0 -\naudio 0 0 30 0 -\n",
6805 &dir
6806 )
6807 .is_ok()
6808 );
6809 // ...and a lane may be empty as long as the other one is not.
6810 let only_audio = parse(b"edith 2\nsource a.mp4\naudio 0 0 30 0 -\n", &dir).expect("parse");
6811 assert!(only_audio.lanes[0].1.is_empty(), "V1 is there and empty");
6812 }
6813
6814 /// A `start` near the top of `u32` used to make `Clip::end` panic in debug
6815 /// and wrap in release, and a wrapped end passes the overlap check --
6816 /// crafted numbers must be refused by name, in both dialects.
6817 #[test]
6818 fn a_clip_whose_end_overflows_is_refused() {
6819 let dir = PathBuf::from("/proj");
6820 for bytes in [
6821 &b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\naudio 0 0 30 0 -\n"[..],
6822 // Two of them: the second would land *before* the first once wrapped.
6823 b"edith 2\nsource a.mp4\nvideo 4294967290 0 30 0 -\nvideo 4294967295 0 30 0 -\n",
6824 // v1 has no `start` field, but its queue reaches the same ceiling.
6825 b"edith 1\nsource a.mp4\nclip 0 4294967295 0\nclip 0 4294967295 0\n",
6826 ] {
6827 let err = parse(bytes, &dir).unwrap_err().to_string();
6828 assert!(
6829 err.contains("runs past the last frame there is"),
6830 "not refused by name: {err}"
6831 );
6832 }
6833 }
6834
6835 /// The relocatability promise, from the two directions a project path
6836 /// reaches [`save`] non-canonical: a bare filename (`cd dir && edith
6837 /// clip.mp4`, whose parent is `""`) and a directory reached through a
6838 /// symlink. Both used to emit absolute source lines.
6839 #[test]
6840 fn a_non_canonical_project_path_still_writes_relative_sources() {
6841 assert_eq!(
6842 project_dir(Path::new("a.edith")),
6843 std::env::current_dir().expect("cwd"),
6844 "a bare filename is saved into the working directory"
6845 );
6846
6847 let dir = crate::scratch::Scratch::dir("ve_edith_link");
6848 std::fs::create_dir_all(dir.join("real")).expect("scratch dir");
6849 std::os::unix::fs::symlink(dir.join("real"), dir.join("link")).expect("symlink");
6850 let source = dir.join("real/a.mp4");
6851 let path = dir.join("link/p.edith");
6852
6853 let one = [clip(0, 0, 30, 0, None)];
6854 let entry = Source {
6855 path: source,
6856 audio_stream: 1, ..Default::default()
6857 };
6858 save(
6859 &path,
6860 &[entry],
6861 &two(one.to_vec(), one.to_vec()),
6862 &[],
6863 &[],
6864 &[],
6865 &[],
6866 &[],
6867 &[],
6868 (1280, 720),
6869 None,
6870 crate::tonemap::Preset::default(),
6871 false,
6872 true,
6873 crate::export::EncoderSeat::default(),
6874 Limiter::default(),
6875 None,
6876 0,
6877 )
6878 .expect("save");
6879 let bytes = std::fs::read(&path).expect("read back");
6880 assert_eq!(
6881 String::from_utf8_lossy(&bytes),
6882 "edith 30\nplayhead 0\nresolution 1280 720\nsource 1 a.mp4\n\
6883 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"
6884 );
6885 // Loading rejoins the *given* directory, so the file is reached by the
6886 // way the project was opened -- the same file, through the link, still
6887 // playing the stream it was saved on.
6888 assert_eq!(
6889 load(&path).expect("load").sources,
6890 vec![Source {
6891 path: dir.join("link/a.mp4"),
6892 audio_stream: 1, ..Default::default()
6893 }]
6894 );
6895 std::fs::remove_dir_all(&dir).expect("cleanup");
6896 }
6897
6898 #[test]
6899 fn escapes_survive_the_bytes_json_would_not() {
6900 let dir = PathBuf::from("/proj");
6901 // A newline and a percent in a filename, plus a non-UTF-8 byte.
6902 let nasty = Source {
6903 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
6904 audio_stream: 0, ..Default::default()
6905 };
6906 let bytes = flat(
6907 &dir,
6908 std::slice::from_ref(&nasty),
6909 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
6910 0,
6911 );
6912 assert_eq!(
6913 bytes.iter().filter(|&&b| b == b'\n').count(),
6914 6,
6915 "the escaped newline must not become a line break: magic, playhead, \
6916 resolution, source, the clip, and the empty audio lane's own line"
6917 );
6918 let back = parse(&bytes, &dir).expect("parse");
6919 // The spaces in it are the reason the stream field leads rather than
6920 // trails: everything after the first one is path.
6921 assert_eq!(back.sources, vec![nasty]);
6922 }
6923
6924 /// A `flags` line names its lane the way a gain does and carries only the
6925 /// switches its kind of lane can have. A lane with none has no line, so a
6926 /// v23 file -- which has no such line -- parses with every switch clear, and
6927 /// one that carries the line before v24 is an unknown keyword.
6928 #[test]
6929 fn lane_switches_parse_by_kind_and_a_v23_file_has_none() {
6930 let dir = PathBuf::from("/proj");
6931 let doc = parse(
6932 b"edith 24\nvideo 1\naudio 1\nsub 1\nflags video 1 hidden locked\nflags audio 1 muted\nflags sub 1 hidden\n",
6933 &dir,
6934 )
6935 .expect("a v24 file with switches parses");
6936 assert_eq!(
6937 doc.flags,
6938 vec![
6939 LaneFlags {
6940 hidden: true,
6941 muted: false,
6942 locked: true,
6943 pan: 0.0,
6944 },
6945 LaneFlags {
6946 hidden: false,
6947 muted: true,
6948 locked: false,
6949 pan: 0.0,
6950 },
6951 LaneFlags {
6952 hidden: true,
6953 muted: false,
6954 locked: false,
6955 pan: 0.0,
6956 },
6957 ]
6958 );
6959
6960 let plain = parse(b"edith 24\nvideo 1\naudio 1\n", &dir).expect("no switches");
6961 assert_eq!(plain.flags, vec![LaneFlags::default(); 2]);
6962 let old = parse(b"edith 23\nvideo 1\naudio 1\n", &dir).expect("a v23 file loads");
6963 assert_eq!(
6964 old.flags,
6965 vec![LaneFlags::default(); 2],
6966 "every switch clear"
6967 );
6968
6969 let refuse = |body: &[u8]| parse(body, &dir).unwrap_err().to_string();
6970 assert!(
6971 refuse(b"edith 24\nvideo 1\nflags video 1 hidden hidden\n").contains("twice"),
6972 "a switch named twice"
6973 );
6974 assert!(
6975 refuse(b"edith 24\naudio 1\nflags audio 1 hidden\n").contains("cannot be set"),
6976 "a hidden audio lane"
6977 );
6978 assert!(
6979 refuse(b"edith 24\nvideo 1\nflags video 1 muted\n").contains("cannot be set"),
6980 "a muted video lane"
6981 );
6982 assert!(
6983 refuse(b"edith 24\nvideo 1\nflags video 2 hidden\n").contains("not there"),
6984 "a lane that is not there"
6985 );
6986 assert!(
6987 refuse(b"edith 24\nvideo 1\nflags video 1\n").contains("no switch"),
6988 "a line with no switch"
6989 );
6990 assert!(
6991 refuse(b"edith 23\nvideo 1\nflags video 1 hidden\n").contains("unknown keyword"),
6992 "a flags line before v24 is not a dialect"
6993 );
6994 }
6995
6996 #[test]
6997 fn a_duck_line_round_trips_and_is_bounded_by_name() {
6998 let dir = PathBuf::from("/proj");
6999 let head = "edith 25\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7000 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7001 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7002 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7003 let ok = parse(
7004 format!("{head}duck audio 2 1 -12.0 -40.0 80.0 400.0\n").as_bytes(),
7005 &dir,
7006 )
7007 .expect("a duck of A2 under A1 parses");
7008 assert_eq!(
7009 ok.ducks,
7010 vec![
7011 vec![],
7012 vec![],
7013 vec![crate::duck::Duck {
7014 under: 0,
7015 depth_db: -12.0,
7016 threshold_db: -40.0,
7017 attack_ms: 80.0,
7018 release_ms: 400.0,
7019 }]
7020 ],
7021 "one list per lane, the key named 0-based in the struct"
7022 );
7023 let refuse = |line: &str| {
7024 parse(format!("{head}{line}\n").as_bytes(), &dir)
7025 .unwrap_err()
7026 .to_string()
7027 };
7028 assert!(refuse("duck audio 2 2 -12.0 -40.0 80.0 400.0").contains("not another audio lane"));
7029 assert!(refuse("duck audio 2 3 -12.0 -40.0 80.0 400.0").contains("not another audio lane"));
7030 assert!(refuse("duck audio 2 0 -12.0 -40.0 80.0 400.0").contains("lane 0"));
7031 assert!(refuse("duck audio 2 1 -41.0 -40.0 80.0 400.0").contains("out of its range"));
7032 assert!(refuse("duck audio 2 1 -12.0 -40.0 0.0 400.0").contains("out of its range"));
7033 assert!(refuse("duck video 1 1 -12.0 -40.0 80.0 400.0").contains("not an audio lane"));
7034 // A dialect before v25 has no ducks, so the same line is an unknown one.
7035 let v24 = format!(
7036 "{}duck audio 2 1 -12.0 -40.0 80.0 400.0\n",
7037 head.replacen("edith 25", "edith 24", 1)
7038 );
7039 assert!(
7040 parse(v24.as_bytes(), &dir)
7041 .unwrap_err()
7042 .to_string()
7043 .contains("unknown keyword"),
7044 "a v24 file cannot carry a duck"
7045 );
7046 // ...and a v24 file without one still loads, with every lane unducked.
7047 let old = parse(head.replacen("edith 25", "edith 24", 1).as_bytes(), &dir)
7048 .expect("v24 still loads");
7049 assert!(old.ducks.iter().all(Vec::is_empty));
7050 }
7051
7052 /// The v42 `effect` lines: a clip's whole stack round-trips in order, switch and
7053 /// every value included, through the same `save_flagged` every save takes; a project
7054 /// with no effect keeps its older header; a v41 file refuses the line; a bad line is
7055 /// refused by name.
7056 #[test]
7057 fn effect_lines_round_trip_in_v42_and_older_files_refuse_them() {
7058 use crate::effects::{Effect, EffectKind};
7059 let dir = std::env::temp_dir().join(format!("edith-effects-{}", std::process::id()));
7060 std::fs::create_dir_all(&dir).unwrap();
7061 let path = dir.join("fx.edith");
7062 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7063 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
7064 save_flagged(
7065 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7066 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7067 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7068 )
7069 .expect("saves");
7070 std::fs::read_to_string(&path).unwrap()
7071 };
7072 let plain = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7073 let before = save(&plain);
7074 assert!(!before.starts_with("edith 42") && !before.contains("effect"), "{before}");
7075 let mut lanes = plain.clone();
7076 let mut blur = Effect::new(EffectKind::Blur);
7077 blur.set("radius", 12.25).unwrap();
7078 let mut key = Effect::new(EffectKind::ChromaKey);
7079 key.on = false;
7080 key.set("tolerance", 0.123_456_7).unwrap();
7081 let stack = vec![Effect::new(EffectKind::Vignette), blur, key, Effect::new(EffectKind::EllipseMask)];
7082 lanes[0].1[0].effects = stack.clone();
7083 let text = save(&lanes);
7084 assert!(text.starts_with("edith 42\n"), "an effect makes it v42: {text}");
7085 assert!(text.contains("\neffect video 1 0 blur 1 12.25\n"), "{text}");
7086 assert!(text.contains("\neffect video 1 0 chroma_key 0 0 255 0 0.1234567 0.1 0.5\n"), "{text}");
7087 let back = load(&path).expect("v42 loads");
7088 assert_eq!(back.lanes[0].1[0].effects, stack, "order, switches and values survive");
7089 assert_eq!(save(&back.lanes), text, "saved again: the same bytes");
7090 lanes[0].1[0].effects.clear();
7091 assert_eq!(save(&lanes), before, "no effect: the bytes it was");
7092 std::fs::remove_dir_all(&dir).ok();
7093
7094 let dir = PathBuf::from("/proj");
7095 let video_head = "edith 42\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7096 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";
7097 let doc = parse(format!("{video_head}effect video 1 0 sharpen 1 0.5\n").as_bytes(), &dir).expect("parses");
7098 assert_eq!(doc.lanes[0].1[0].effects[0].get("amount"), Some(0.5));
7099 let refuse = |line: &str| parse(format!("{video_head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7100 assert!(refuse("effect video 1 0 sparkle 1 0.5").contains("not one"));
7101 assert!(refuse("effect video 1 0 sharpen 2 0.5").contains("not 0 or 1"));
7102 assert!(refuse("effect video 1 0 sharpen 1 9").contains("out of its range"));
7103 assert!(refuse("effect video 1 0 vignette 1 0.5").contains("wants 2 values"));
7104 assert!(refuse("effect video 1 4 sharpen 1 0.5").contains("does not have"));
7105 assert!(refuse("effect audio 1 0 sharpen 1 0.5").contains("wants a video clip"));
7106 assert!(refuse("effect video 2 0 sharpen 1 0.5").contains("not there"));
7107 let v41 = video_head.replacen("edith 42", "edith 41", 1);
7108 let err = parse(format!("{v41}effect video 1 0 sharpen 1 0.5\n").as_bytes(), &dir).unwrap_err().to_string();
7109 assert!(err.contains("unknown keyword \"effect\""), "{err}");
7110 }
7111
7112 /// The v50 pan lines: a clip pan and a lane pan round-trip, a project with neither keeps its
7113 /// header and its bytes, and an out-of-range or unknown-lane pan is refused by name.
7114 #[test]
7115 fn pan_lines_round_trip_in_v50() {
7116 let dir = std::env::temp_dir().join(format!("edith-pan-{}", std::process::id()));
7117 std::fs::create_dir_all(&dir).unwrap();
7118 let path = dir.join("pan.edith");
7119 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7120 let save = |lanes: &[(LaneKind, Vec<Clip>)], flags: &[LaneFlags]| {
7121 save_flagged(
7122 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7123 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7124 Limiter::default(), None, 0, flags, &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7125 )
7126 .expect("saves");
7127 std::fs::read_to_string(&path).unwrap()
7128 };
7129 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))]);
7130 let before = save(&plain, &[]);
7131 assert!(!before.contains("pan"), "{before}");
7132 let mut lanes = plain.clone();
7133 lanes[1].1[1].pan = -25;
7134 let flags = [LaneFlags::default(), LaneFlags { pan: 0.5, locked: true, ..LaneFlags::default() }];
7135 let text = save(&lanes, &flags);
7136 assert!(text.starts_with("edith 50\n"), "{text}");
7137 assert!(text.contains("\nlanepan audio 1 0.5\n") && text.contains("\nclippan audio 1 1 -0.25\n"), "{text}");
7138 let back = load(&path).expect("v50 loads");
7139 assert_eq!(back.lanes[1].1[1].pan, -25);
7140 assert_eq!(back.lanes[1].1[0].pan, 0);
7141 assert_eq!(back.flags[1].pan, 0.5);
7142 assert!(back.flags[1].locked, "the switches stay");
7143 assert_eq!(save(&back.lanes, &back.flags), text, "saved again: the same bytes");
7144 let dirp = PathBuf::from("/proj");
7145 let head = "edith 50\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7146 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";
7147 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7148 assert!(refuse("clippan audio 1 0 2").contains("out of its range"));
7149 assert!(refuse("clippan audio 1 4 0.5").contains("does not have"));
7150 assert!(refuse("lanepan audio 3 0.5").contains("not there"));
7151 assert!(refuse("lanepan video 1 0.5").contains("not an audio lane"));
7152 let old = head.replacen("edith 50", "edith 49", 1);
7153 let err = parse(format!("{old}lanepan audio 1 0.5\n").as_bytes(), &dirp).unwrap_err().to_string();
7154 assert!(err.contains("unknown keyword"), "{err}");
7155 std::fs::remove_dir_all(&dir).ok();
7156 }
7157
7158
7159 /// A custom bezier ease is a v56 word: a v56 file loads it and a v55 file naming one is refused.
7160 #[test]
7161 fn bezier_ease_is_a_v56_word() {
7162 let dirp = PathBuf::from("/proj");
7163 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7164 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7165 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";
7166 let doc = parse(format!("edith 56\n{head}{line}").as_bytes(), &dirp).expect("a v56 file loads");
7167 let bezier = crate::transform::Bezier::new(0.42, 0.0, 0.58, 1.0).unwrap();
7168 assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Bezier(bezier));
7169 let err = parse(format!("edith 55\n{head}{line}").as_bytes(), &dirp).unwrap_err().to_string();
7170 assert!(err.contains("tkeys ease"), "{err}");
7171 }
7172
7173 /// The v55 pitch lines: a clip's semitones round-trip and a project with none is the bytes a
7174 /// v51 one was; an out-of-range, unknown-lane or unknown-clip pitch is refused by name, and a
7175 /// pitch line under an older header is refused as unknown.
7176 #[test]
7177 fn pitch_lines_round_trip_in_v55() {
7178 let dir = std::env::temp_dir().join(format!("edith-pitch-{}", std::process::id()));
7179 std::fs::create_dir_all(&dir).unwrap();
7180 let path = dir.join("pitch.edith");
7181 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7182 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
7183 save_flagged(
7184 &path, &src, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7185 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7186 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7187 )
7188 .expect("saves");
7189 std::fs::read_to_string(&path).unwrap()
7190 };
7191 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))]);
7192 let before = save(&plain);
7193 assert!(!before.contains("pitch"), "{before}");
7194 assert!(!before.starts_with("edith 55"), "{before}");
7195 let mut lanes = plain.clone();
7196 lanes[1].1[1].pitch = -7.0;
7197 let text = save(&lanes);
7198 assert!(text.starts_with("edith 55\n"), "{text}");
7199 assert!(text.contains("\npitch audio 1 1 -7\n"), "{text}");
7200 let back = load(&path).expect("v55 loads");
7201 assert_eq!(back.lanes[1].1[1].pitch, -7.0);
7202 assert_eq!(back.lanes[1].1[0].pitch, 0.0);
7203 assert_eq!(save(&back.lanes), text, "saved again: the same bytes");
7204 let dirp = PathBuf::from("/proj");
7205 let head = "edith 55\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7206 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";
7207 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7208 assert!(refuse("pitch audio 1 0 13").contains("out of its range"));
7209 assert!(refuse("pitch audio 1 0 1.5").contains("out of its range"));
7210 assert!(refuse("pitch audio 1 4 3").contains("does not have"));
7211 assert!(refuse("pitch audio 3 0 3").contains("not there"));
7212 assert!(refuse("pitch video 1 0 3").contains("not an audio lane"));
7213 let old = head.replacen("edith 55", "edith 51", 1);
7214 let err = parse(format!("{old}pitch audio 1 0 3\n").as_bytes(), &dirp).unwrap_err().to_string();
7215 assert!(err.contains("unknown keyword"), "{err}");
7216 std::fs::remove_dir_all(&dir).ok();
7217 }
7218
7219 /// The v51 library lines: bins, filed sources and starred ones round-trip; a project with
7220 /// none keeps its v50 bytes; the lines are refused in v50 and bad ones by name.
7221 #[test]
7222 fn library_lines_round_trip_with_effect_keys_in_v56() {
7223 use crate::project::Bin;
7224 let dir = std::env::temp_dir().join(format!("edith-bins-{}", std::process::id()));
7225 std::fs::create_dir_all(&dir).unwrap();
7226 let path = dir.join("bins.edith");
7227 let mut src = vec![
7228 Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() },
7229 Source { path: dir.join("b.mp4"), audio_stream: 0, ..Default::default() },
7230 ];
7231 let mut lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7232 let mut mask = crate::effects::Effect::new(crate::effects::EffectKind::EllipseMask);
7233 mask.keys = vec![crate::effects::EffectKey {
7234 at: 0, values: [0.5, 0.5, 0.4, 0.4, 0.02, 0.0], ease: KeyEase::Linear,
7235 }];
7236 lanes[0].1[0].effects = vec![mask];
7237 let save = |src: &[Source], bins: &[Bin]| {
7238 let main = encode_flagged(
7239 &dir, src, &lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7240 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7241 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7242 );
7243 let bytes = noted(binned(main, src, bins), "Two cuts", STILL_DEFAULT_SECS, None, crate::speech::DeviceChoice::Auto);
7244 std::fs::write(&path, &bytes).unwrap();
7245 String::from_utf8(bytes).unwrap()
7246 };
7247 let plain = save(&src, &[]);
7248 assert!(plain.starts_with("edith 45\n") || !plain.starts_with("edith 51"), "{plain}");
7249 assert!(!plain.contains("bin") && !plain.contains("srcfav"), "{plain}");
7250 let bins = vec![
7251 Bin { id: 1, parent: 0, name: "Interviews \"A\"".into() },
7252 Bin { id: 3, parent: 1, name: "B roll".into() },
7253 ];
7254 src[0].bin = 3;
7255 src[1].fav = true;
7256 src[1].bin = 1;
7257 let text = save(&src, &bins);
7258 // An effect key is v56, and the library and the notes lines keep it there.
7259 assert!(text.starts_with("edith 56\n"), "{text}");
7260 assert!(text.contains("\nsrcbin 0 3\n") && text.contains("\nsrcfav 1\n"), "{text}");
7261 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}");
7262 let back = load(&path).expect("v56 loads");
7263 assert_eq!(back.notes, "Two cuts");
7264 assert_eq!(back.bins, bins);
7265 assert_eq!((back.sources[0].bin, back.sources[0].fav), (3, false));
7266 assert_eq!((back.sources[1].bin, back.sources[1].fav), (1, true));
7267 assert_eq!(save(&back.sources, &back.bins), text, "saved again: the same bytes");
7268 let dirp = PathBuf::from("/proj");
7269 let head = "edith 51\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7270 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";
7271 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7272 assert!(refuse("bin 1 0").contains("wants an id"));
7273 assert!(refuse("bin 0 0 x").contains("not a new id"));
7274 assert!(refuse("bin 1 0 x\nbin 1 0 y").contains("not a new id"));
7275 assert!(refuse("bin 2 1 x").contains("not a top-level bin"));
7276 assert!(refuse("bin 1 0 x\nbin 2 0 X").contains("two bins named"));
7277 assert!(refuse("bin 1 0 x\nbin 2 1 y\nbin 3 2 z").contains("not a top-level bin"));
7278 assert!(refuse("srcbin 0 9").contains("not defined"));
7279 assert!(refuse("bin 1 0 x\nsrcbin 4 1").contains("does not have"));
7280 assert!(refuse("srcfav 7").contains("does not have"));
7281 let old = head.replacen("edith 51", "edith 50", 1);
7282 for line in ["bin 1 0 x", "srcfav 0"] {
7283 let err = parse(format!("{old}{line}\n").as_bytes(), &dirp).unwrap_err().to_string();
7284 assert!(err.contains("unknown keyword"), "{err}");
7285 }
7286 std::fs::remove_dir_all(&dir).ok();
7287 }
7288
7289 /// The v41 `voice` lines: every processor of an audio lane (the noise profile included)
7290 /// round-trips bit for bit; a lane with no voice setting writes none, so a project nobody
7291 /// has cleaned keeps its older header and its exact bytes; a v40 file loads with every
7292 /// processor off and refuses the lines; a number out of range is refused by name.
7293 /// The v43 look lines: wheels, curves and a LUT path (relative inside the
7294 /// project folder) round trip bit-exactly; a grade without a look writes none
7295 /// and stays under its old header; a missing LUT still loads; bad lines are
7296 /// refused by name.
7297 #[test]
7298 fn look_lines_round_trip_in_v43() {
7299 use crate::color::{Curve, Look, Wheels};
7300 let dir = std::env::temp_dir().join(format!("edith-look-{}", std::process::id()));
7301 std::fs::create_dir_all(dir.join("luts")).unwrap();
7302 let cube = dir.join("luts/warm look.cube");
7303 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();
7304 let path = dir.join("look.edith");
7305 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7306 let lanes = two(
7307 vec![Clip { color: Some(0), ..clip(0, 0, 30, 0, Some(0)) }, Clip { color: Some(1), ..clip(30, 0, 30, 0, Some(0)) }],
7308 vec![clip(0, 0, 60, 0, Some(0))],
7309 );
7310 let look = Look {
7311 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] },
7312 curves: [
7313 Curve::new(&[[0.25, 0.2], [0.75, 0.8]]).unwrap(),
7314 Curve::default(),
7315 Curve::new(&[[0.0, 0.1], [0.5, 0.5], [1.0, 0.95]]).unwrap(),
7316 Curve::default(),
7317 ],
7318 lut: Some(crate::cube::LutRef::open(&cube)),
7319 lut_mix: 0.7,
7320 };
7321 let color = vec![ColorParams { contrast: 1.1, look, ..Default::default() }, ColorParams { tint: 0.2, ..Default::default() }];
7322 let save = |color: &[ColorParams]| {
7323 save_flagged(
7324 &path, &src, &lanes, &[], &[], &[], &[], color, &[], (1280, 720), Some(30.0),
7325 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7326 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
7327 )
7328 .expect("saves");
7329 std::fs::read_to_string(&path).unwrap()
7330 };
7331 let text = save(&color);
7332 assert!(text.starts_with("edith 43\n"), "a look makes it v43: {text}");
7333 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}");
7334 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}");
7335 assert!(text.contains("\nlut 0 0.7 luts/warm look.cube\n"), "relative inside the folder: {text}");
7336 assert!(!text.contains("curve 1") && !text.contains("lut 1"), "no look, no lines");
7337 let back = load(&path).expect("v43 loads");
7338 assert_eq!(back.color, color, "every number survives");
7339 assert_eq!(save(&back.color), text, "a re-save is the same file");
7340 // No look: the old header and no look line.
7341 let plain = save(&[color[1], color[1]]);
7342 assert!(plain.starts_with("edith 3") && !plain.contains("wheels") && !plain.contains("\nlut "), "{plain}");
7343 // A missing LUT loads, and says why it cannot be used.
7344 let gone = text.replace("luts/warm look.cube", "luts/gone.cube");
7345 std::fs::write(&path, &gone).unwrap();
7346 let doc = load(&path).expect("a missing LUT still loads");
7347 let lut = doc.color[0].look.lut.expect("named");
7348 assert!(lut.problem().expect("missing").contains("cannot read"));
7349 std::fs::remove_dir_all(&dir).ok();
7350
7351 let head = "edith 43\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\n\
7352 video 1 0 0 30 0 - - 0 fit 1000 0 0 0 - 0 0\n";
7353 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7354 assert!(refuse("wheels 1 0:0:0:0 0:0:0:0 0:0:0:0").contains("names color 1"));
7355 assert!(refuse("wheels 0 2:0:0:0 0:0:0:0 0:0:0:0").contains("outside -1..1"));
7356 assert!(refuse("wheels 0 0:0:0 0:0:0:0 0:0:0:0").contains("4 values"));
7357 assert!(refuse("curve 0 cyan 0.1:0.2").contains("not master"));
7358 assert!(refuse("curve 0 red 0.5:0.2,0.4:0.3").contains("strictly increase"));
7359 assert!(refuse("curve 0 red 0.5").contains("<x>:<y>"));
7360 assert!(refuse("lut 0 1.5 a.cube").contains("0..=1"));
7361 assert!(refuse("lut 0 1.0").contains("<mix> <path>"));
7362 for old in ["edith 42", "edith 41"] {
7363 let older = head.replacen("edith 43", old, 1);
7364 assert!(parse(format!("{older}lut 0 1.0 a.cube\n").as_bytes(), &dir).is_err(), "a {old} file has no lut line");
7365 }
7366 }
7367
7368 #[test]
7369 fn voice_lines_round_trip_in_v41_and_older_files_load_with_them_off() {
7370 use crate::voice::{PROFILE_BANDS, Strength};
7371 let dir = std::env::temp_dir().join(format!("edith-voice-{}", std::process::id()));
7372 std::fs::create_dir_all(&dir).unwrap();
7373 let path = dir.join("voice.edith");
7374 let src = vec![Source { path: dir.join("a.mp4"), audio_stream: 0, ..Default::default() }];
7375 let lanes = two(vec![clip(0, 0, 30, 0, Some(0))], vec![clip(0, 0, 30, 0, Some(0))]);
7376 let profile: Vec<f32> = (0..PROFILE_BANDS).map(|b| -80.0 + b as f32 * 0.1).collect();
7377 let fx = VoiceFx::clean_voice(Strength::Strong, profile, Some(-52.0));
7378 let save = |voices: &[VoiceFx]| {
7379 save_flagged(
7380 &path, &src, &lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(30.0),
7381 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7382 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), voices, &[],
7383 )
7384 .expect("saves");
7385 std::fs::read_to_string(&path).unwrap()
7386 };
7387 let text = save(&[VoiceFx::default(), fx.clone()]);
7388 assert!(text.starts_with("edith 41\n"), "a voice makes it v41: {text}");
7389 for kind in ["gate", "nr", "comp", "deess"] {
7390 assert!(text.contains(&format!("\nvoice audio 1 {kind} 1 ")), "{kind}: {text}");
7391 }
7392 let back = load(&path).expect("v41 loads");
7393 assert_eq!(back.voices, vec![VoiceFx::default(), fx.clone()], "every number and the profile survive");
7394 // Saved again from what was loaded: the same bytes.
7395 let again = save(&back.voices);
7396 assert_eq!(again, text);
7397 // Only what differs from the default is written, and a lane with nothing writes no line.
7398 let comp_only = VoiceFx { comp: Compressor { on: true, ..Compressor::DEFAULT }, ..Default::default() };
7399 let text = save(&[VoiceFx::default(), comp_only.clone()]);
7400 assert_eq!(text.matches("\nvoice ").count(), 1, "{text}");
7401 assert_eq!(load(&path).unwrap().voices[1], comp_only);
7402 // Nothing set: not v41 and no voice line -- the bytes a v40 save wrote.
7403 let plain = save(&[VoiceFx::default(), VoiceFx::default()]);
7404 assert!(!plain.contains("voice") && plain.starts_with("edith 3") && !plain.starts_with("edith 41"), "{plain}");
7405 assert_eq!(save(&[]), plain, "no list is the same as a list of defaults");
7406 std::fs::remove_file(&path).ok();
7407
7408 let head = "edith 41\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7409 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";
7410 let refuse = |line: &str| parse(format!("{head}{line}\n").as_bytes(), &dir).unwrap_err().to_string();
7411 assert!(refuse("voice audio 1 gate 1 -45.0 2.0 150.0 60.0 5.0").contains("out of its range"));
7412 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"));
7413 assert!(refuse("voice audio 1 nr 1 0.6 -18.0 -").contains("no noise profile"));
7414 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");
7415 assert!(refuse("voice audio 1 gate 2 -45.0 2.0 150.0 60.0 -18.0").contains("not 0 or 1"));
7416 assert!(refuse("voice audio 1 gate 1 -45.0 2.0").contains("wants 6 fields"));
7417 assert!(refuse("voice audio 1 reverb 1").contains("not a processor"));
7418 assert!(refuse("voice audio 2 gate 1 -45.0 2.0 150.0 60.0 -18.0").contains("not there"));
7419 assert!(refuse("voice video 1 gate 1 -45.0 2.0 150.0 60.0 -18.0").contains("not an audio lane"));
7420 // A v40 file carries none, and the same line in one is an unknown keyword.
7421 let v40 = head.replacen("edith 41", "edith 40", 1);
7422 let err = parse(format!("{v40}voice audio 1 gate 1 -45.0 2.0 150.0 60.0 -18.0\n").as_bytes(), &dir)
7423 .unwrap_err()
7424 .to_string();
7425 assert!(err.contains("unknown keyword"), "{err}");
7426 let old = parse(v40.as_bytes(), &dir).expect("v40 still loads");
7427 assert!(old.voices.iter().all(|v| !v.is_active()) && old.voices.len() == 2);
7428 std::fs::remove_dir_all(&dir).ok();
7429 }
7430
7431 #[test]
7432 fn a_lane_ducked_under_two_keys_round_trips_in_v30() {
7433 let dir = PathBuf::from("/proj");
7434 let head = "edith 30\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7435 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7436 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7437 audio 2 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
7438 audio 3 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
7439 let two = format!(
7440 "{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"
7441 );
7442 let ok = parse(two.as_bytes(), &dir).expect("two keys for A3 parse");
7443 assert_eq!(ok.ducks[3].len(), 2, "both ducks kept, in file order");
7444 assert_eq!(ok.ducks[3][0].under, 0);
7445 assert_eq!(ok.ducks[3][1].under, 1);
7446 let refuse = |text: String| parse(text.as_bytes(), &dir).unwrap_err().to_string();
7447 assert!(
7448 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"))
7449 .contains("same key twice")
7450 );
7451 // A v29 file cannot hold two for one lane: refused by name, not dropped.
7452 let v29 = format!(
7453 "{}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",
7454 head.replacen("edith 30", "edith 29", 1)
7455 );
7456 assert!(refuse(v29).contains("names a lane twice"));
7457 }
7458
7459 #[test]
7460 fn a_wrong_first_line_is_refused_by_name() {
7461 let dir = PathBuf::from("/proj");
7462 let err = parse(b"edith 999\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
7463 .unwrap_err()
7464 .to_string();
7465 assert_eq!(err, "line 1: unsupported version 999");
7466 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
7467 assert_eq!(
7468 parse(junk, &dir).unwrap_err().to_string(),
7469 "line 1: not an edith file"
7470 );
7471 }
7472 }
7473
7474 /// The v34 `chapter` line: a project's chapters are saved in frame order and
7475 /// come back as they were, and a project with none is still a v33-or-older
7476 /// file. A v33 file loads with no chapters, and a chapter line in one is refused.
7477 #[test]
7478 fn chapters_round_trip_and_a_v33_file_loads_without_them() {
7479 use crate::project::Chapter;
7480 let dir = std::env::temp_dir().join(format!("edith-chapters-{}", std::process::id()));
7481 std::fs::create_dir_all(&dir).unwrap();
7482 let path = dir.join("chapters.edith");
7483 let chapters = vec![
7484 Chapter { frame: 0, title: "Intro".into() },
7485 Chapter { frame: 1500, title: "Setup: 100% \\ done".into() },
7486 ];
7487 save_flagged(
7488 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7489 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7490 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &chapters, &[], &CaptionStyle::default(), &[], &[],
7491 )
7492 .expect("a project with chapters saves");
7493 let text = std::fs::read_to_string(&path).unwrap();
7494 assert!(text.starts_with("edith 34\n"), "chapters make it v34: {text}");
7495 assert!(text.contains("\nchapter 0 Intro\nchapter 1500 "), "frame order, one line each: {text}");
7496 let back = load(&path).expect("v34 loads");
7497 assert_eq!(back.chapters, chapters);
7498 std::fs::remove_file(&path).ok();
7499
7500 // A project with no chapters keeps the header it always had.
7501 let bare = b"edith 33\nplayhead 0\nsource 0 a.mp4\n";
7502 let old = parse(bare, &dir).expect("a v33 file loads");
7503 assert!(old.chapters.is_empty());
7504 let mixed = parse(b"edith 33\nsource 0 a.mp4\nchapter 0 Intro\n", &dir)
7505 .unwrap_err()
7506 .to_string();
7507 assert_eq!(mixed, "line 3: unknown keyword \"chapter\"");
7508 // Out of order, a name with none, and a frame that is not a frame are refused.
7509 for line in ["chapter 10 B\nchapter 5 A\n", "chapter 5 \n", "chapter x Intro\n"] {
7510 let file = format!("edith 34\nsource 0 a.mp4\n{line}");
7511 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7512 }
7513 std::fs::remove_dir(&dir).ok();
7514 }
7515
7516 /// The v36 `marker` and `marknote` lines: markers (point and range, with and without a
7517 /// note, two on one frame) round-trip and make the file v36; a v35 file loads with none
7518 /// and refuses the lines; a project with no marker keeps its older header.
7519 #[test]
7520 fn markers_round_trip_and_a_v35_file_loads_without_them() {
7521 use crate::project::{Marker, MarkerColor};
7522 let dir = std::env::temp_dir().join(format!("edith-markers-{}", std::process::id()));
7523 std::fs::create_dir_all(&dir).unwrap();
7524 let path = dir.join("markers.edith");
7525 let mk = |frame, length, name: &str, note: &str, color| Marker { frame, length, name: name.into(), note: note.into(), color };
7526 let markers = vec![
7527 mk(0, 0, "Intro", "", MarkerColor::Blue),
7528 mk(100, 50, "Fix: 100% \\ the cut", "line one\nline two", MarkerColor::Red),
7529 mk(100, 0, "Same frame", "", MarkerColor::Purple),
7530 mk(900, 0, "Late", "has a note", MarkerColor::Green),
7531 ];
7532 let save = |markers: &[Marker]| {
7533 save_flagged(
7534 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7535 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7536 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], markers, &CaptionStyle::default(), &[], &[],
7537 )
7538 .expect("saves");
7539 };
7540 save(&markers);
7541 let text = std::fs::read_to_string(&path).unwrap();
7542 assert!(text.starts_with("edith 36\n"), "markers make it v36: {text}");
7543 assert!(text.contains("\nmarker 0 0 blue Intro\nmarker 100 50 red "), "{text}");
7544 assert!(text.contains("\nmarknote 1 line one\\nline two\nmarknote 3 has a note\n"), "{text}");
7545 assert_eq!(load(&path).expect("v36 loads").markers, markers);
7546 save(&[]);
7547 let text = std::fs::read_to_string(&path).unwrap();
7548 assert!(!text.starts_with("edith 36") && !text.contains("marker"), "no markers, an older file: {text}");
7549 std::fs::remove_file(&path).ok();
7550
7551 let old = parse(b"edith 35\nplayhead 0\nsource 0 a.mp4\n", &dir).expect("a v35 file loads");
7552 assert!(old.markers.is_empty());
7553 let mixed = parse(b"edith 35\nsource 0 a.mp4\nmarker 0 0 red A\n", &dir).unwrap_err().to_string();
7554 assert_eq!(mixed, "line 3: unknown keyword \"marker\"");
7555 for line in [
7556 "marker 10 0 red B\nmarker 5 0 red A\n",
7557 "marker 5 0 red \n",
7558 "marker 5 0 pink A\n",
7559 "marker x 0 red A\n",
7560 "marknote 0 hi\n",
7561 ] {
7562 let file = format!("edith 36\nsource 0 a.mp4\n{line}");
7563 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7564 }
7565 std::fs::remove_dir(&dir).ok();
7566 }
7567
7568 /// The v40 `capstyle` line: an animated caption style round-trips and makes the file v40;
7569 /// the default style writes no line and keeps the older header; a v36 file loads as the
7570 /// default and a v39 file refuses the line; a bad line is refused by name.
7571 /// The v40 `cuewords` lines: word times round-trip through the text, a cue without any
7572 /// writes no line, and a v39 file refuses the line.
7573 #[test]
7574 fn cue_word_times_round_trip_through_the_lines() {
7575 let dir = PathBuf::from("/proj");
7576 let cue = |text: &str, words: Vec<(i64, i64, String)>| crate::subtitle::Cue {
7577 start_us: 0,
7578 end_us: 3_000_000,
7579 text: text.into(),
7580 image: None,
7581 words,
7582 karaoke: Vec::new(),
7583 };
7584 let mut track = crate::subtitle::open(Path::new("/nonexistent.srt"), None);
7585 track.cues = vec![
7586 cue("plain", vec![]),
7587 cue("two words", vec![(0, 1_000_000, "two".into()), (1_000_000, 2_500_000, "words".into())]),
7588 ];
7589 let lines = String::from_utf8(cue_word_lines(&[track])).unwrap();
7590 assert_eq!(lines, "cuewords 0 1 0 1000000 two 1000000 2500000 words\n");
7591 let file = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{lines}");
7592 let doc = parse(file.as_bytes(), &dir).expect("v40 parses");
7593 assert_eq!(
7594 doc.cue_words,
7595 vec![(0, 1, vec![(0, 1_000_000, "two".to_string()), (1_000_000, 2_500_000, "words".to_string())])]
7596 );
7597 let old = file.replacen("edith 40", "edith 39", 1);
7598 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("unknown keyword"));
7599 for bad in ["cuewords 0 1 0 5\n", "cuewords 9 1 0 5 a\n", "cuewords 0 1 x 5 a\n"] {
7600 let f = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{bad}");
7601 assert!(parse(f.as_bytes(), &dir).is_err(), "{bad:?} is refused");
7602 }
7603 }
7604
7605 /// The whole project loop for word times: a track with uneven word times is written as
7606 /// `cuewords` lines, read back and attached to a freshly loaded project, and the cue then
7607 /// answers with the same uneven times -- until its text is retyped, which drops them.
7608 #[test]
7609 fn a_projects_cue_word_times_survive_the_file_and_die_with_a_text_edit() {
7610 let words = vec![(0, 200_000, "so".to_string()), (200_000, 2_600_000, "extraordinary".to_string())];
7611 let make = |words: Vec<(i64, i64, String)>| {
7612 let mut track = crate::subtitle::open(Path::new("/nonexistent.srt"), None);
7613 track.cues = vec![crate::subtitle::Cue {
7614 start_us: 0,
7615 end_us: 3_000_000,
7616 text: "So extraordinary".into(),
7617 image: None,
7618 words,
7619 karaoke: Vec::new(),
7620 }];
7621 track
7622 };
7623 let mut project = crate::Project::single("/proj/a.mp4", 150);
7624 assert!(project.add_subtitles(&make(words.clone())));
7625 let lines = String::from_utf8(cue_word_lines(project.subtitles())).unwrap();
7626 let file = format!("edith 40\nsource 0 a.mp4\nsubtitle - x.srt\n{lines}");
7627 let doc = parse(file.as_bytes(), &PathBuf::from("/proj")).expect("the file parses");
7628
7629 let mut loaded = crate::Project::single("/proj/a.mp4", 150);
7630 assert!(loaded.add_subtitles(&make(Vec::new())));
7631 assert!(loaded.subtitles()[0].cues[0].real_words().is_none(), "the SRT alone has no word times");
7632 let mut loaded = loaded.with_cue_words(&doc.cue_words);
7633 assert_eq!(loaded.subtitles()[0].cues[0].real_words(), Some(&words[..]), "the uneven times are back");
7634 assert!(loaded.set_cue_text(0, 0, "Something else"));
7635 assert!(loaded.subtitles()[0].cues[0].real_words().is_none(), "retyped words have no times");
7636 }
7637
7638 #[test]
7639 fn the_caption_style_round_trips_and_a_v36_file_loads_as_static() {
7640 use crate::captionanim::CaptionAnim;
7641 let dir = std::env::temp_dir().join(format!("edith-capstyle-{}", std::process::id()));
7642 std::fs::create_dir_all(&dir).unwrap();
7643 let path = dir.join("capstyle.edith");
7644 let save = |cs: &CaptionStyle| {
7645 save_flagged(
7646 &path, &[], &[], &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
7647 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
7648 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], cs, &[], &[],
7649 )
7650 .expect("saves");
7651 };
7652 let style = CaptionStyle {
7653 anim: CaptionAnim::Karaoke,
7654 highlight: [0x12, 0xab, 0xff],
7655 hl_box: true,
7656 uppercase: true,
7657 words_per_line: 3,
7658 };
7659 save(&style);
7660 let text = std::fs::read_to_string(&path).unwrap();
7661 assert!(text.starts_with("edith 40\n"), "{text}");
7662 assert!(text.contains("\ncapstyle karaoke 12abff 1 1 3\n"), "{text}");
7663 assert_eq!(load(&path).expect("v40 loads").caption_style, style);
7664 // The default is no line and an older header: the bytes an older build wrote.
7665 save(&CaptionStyle::default());
7666 let text = std::fs::read_to_string(&path).unwrap();
7667 assert!(!text.contains("capstyle") && !text.starts_with("edith 40"), "{text}");
7668 assert_eq!(load(&path).unwrap().caption_style, CaptionStyle::default());
7669 let old = parse(b"edith 36\nplayhead 0\nsource 0 a.mp4\n", &dir).expect("a v36 file loads");
7670 assert_eq!(old.caption_style, CaptionStyle::default());
7671 let mixed = parse(b"edith 39\nsource 0 a.mp4\ncapstyle pop ffd600 0 0 0\n", &dir)
7672 .unwrap_err()
7673 .to_string();
7674 assert_eq!(mixed, "line 3: unknown keyword \"capstyle\"");
7675 for line in [
7676 "capstyle spin ffd600 0 0 0",
7677 "capstyle pop ffd60 0 0 0",
7678 "capstyle pop ffd600 2 0 0",
7679 "capstyle pop ffd600 0 0 99",
7680 "capstyle pop ffd600 0 0",
7681 ] {
7682 let file = format!("edith 40\nsource 0 a.mp4\n{line}\n");
7683 assert!(parse(file.as_bytes(), &dir).is_err(), "{line:?} is refused");
7684 }
7685 std::fs::remove_file(&path).ok();
7686 std::fs::remove_dir(&dir).ok();
7687 }
7688
7689 /// Crafted files that declare more than any editor writes get a clear error,
7690 /// never an allocation or a hang.
7691 #[test]
7692 fn crafted_tables_over_the_caps_are_refused() {
7693 let dir = PathBuf::from("/proj");
7694 let head = "edith 40\nsource 0 a.mp4\n";
7695 let bands = vec!["1000.0:0.0:1.0:pk"; MAX_EQ_BANDS + 1].join(" ");
7696 let words = "0 1 w ".repeat(MAX_CUE_WORDS + 1);
7697 let order = (0..=MAX_SEQUENCES).map(|i| i.to_string()).collect::<Vec<_>>().join(" ");
7698 for (file, what) in [
7699 (format!("{head}eq {bands}\n"), "equalizer"),
7700 (format!("{head}cuewords 0 0 {}\n", words.trim_end()), "cuewords"),
7701 (format!("edith 45\nsource 0 a.mp4\nseqorder {order}\n"), "seqorder"),
7702 ] {
7703 let err = parse(file.as_bytes(), &dir).expect_err(what).to_string();
7704 assert!(err.contains("at most") || err.contains("more than"), "{what}: {err}");
7705 }
7706 // And a table of exactly the cap still opens.
7707 let ok = vec!["1000.0:0.0:1.0:pk"; MAX_EQ_BANDS].join(" ");
7708 assert!(parse(format!("{head}eq {ok}\n").as_bytes(), &dir).is_ok());
7709 // A project whose lists run past the cap is refused as a whole.
7710 let mut many = String::from("edith 40\nsource 0 a.mp4\n");
7711 for i in 0..=MAX_LIST_ENTRIES {
7712 many.push_str(&format!("chapter {i} c\n"));
7713 }
7714 let err = parse(many.as_bytes(), &dir).unwrap_err().to_string();
7715 assert!(err.contains("at most"), "{err}");
7716 }
7717
7718 #[test]
7719 fn the_newest_version_is_the_magic_line_the_writer_emits() {
7720 assert_eq!(MAGIC, format!("edith {NEWEST_VERSION}").as_bytes());
7721 }
7722
7723 #[test]
7724 fn malformed_lines_name_their_line_number() {
7725 let dir = PathBuf::from("/proj");
7726 let cases: [(&[u8], &str); 10] = [
7727 // v3 wants the stream before the path, and a path after it.
7728 (
7729 b"edith 3\nsource a.mp4\nvideo 0 0 5 0 -\n",
7730 "line 2: \"a.mp4\" is not a number",
7731 ),
7732 (
7733 b"edith 3\nsource 0\nvideo 0 0 5 0 -\n",
7734 "line 2: source without a path",
7735 ),
7736 (
7737 b"edith 1\nsource a.mp4\nclip 0 5\n",
7738 "line 3: clip wants 3 fields, found 2",
7739 ),
7740 (
7741 b"edith 1\nsource a.mp4\nclip 0 five 0\n",
7742 "line 3: \"five\" is not a number",
7743 ),
7744 (
7745 b"edith 1\nsource a.mp4\nclip 5 5 0\n",
7746 "line 3: clip [5, 5) is empty",
7747 ),
7748 (
7749 b"edith 1\nsource a.mp4\nclip 7 5 0\n",
7750 "line 3: clip [7, 5) is empty",
7751 ),
7752 (
7753 b"edith 1\nsource a.mp4\nclip 0 5 1\n",
7754 "line 3: clip names source 1 of 1",
7755 ),
7756 (
7757 b"edith 1\nsource a.mp4\nclip 0 5 0\nsource b.mp4\n",
7758 "line 4: source after a clip",
7759 ),
7760 (
7761 b"edith 1\nsource a.mp4\n\nclip 0 5 0\n",
7762 "line 3: unknown keyword \"\"",
7763 ),
7764 (
7765 b"edith 1\nsource a.mp4\nplayhead 3\nclip 0 5 0\n",
7766 "line 3: playhead belongs once, before the sources",
7767 ),
7768 ];
7769 for (bytes, want) in cases {
7770 assert_eq!(parse(bytes, &dir).unwrap_err().to_string(), want);
7771 }
7772 }
7773
7774 /// The emptied timeline writes and reads back: every lane declared, no clip
7775 /// on any of them, and the source that gave the project its frame rate still
7776 /// named. Nothing about the format changes for it -- an empty lane already
7777 /// had a line of its own.
7778 #[test]
7779 fn a_project_without_clips_round_trips() {
7780 let dir = PathBuf::from("/proj");
7781 let source = Source {
7782 path: PathBuf::from("/proj/a.mp4"),
7783 audio_stream: 0, ..Default::default()
7784 };
7785 let bytes = flat(
7786 &dir,
7787 std::slice::from_ref(&source),
7788 &two(Vec::new(), Vec::new()),
7789 0,
7790 );
7791 let back = parse(&bytes, &dir).expect("an emptied timeline is a project");
7792 assert_eq!(back.sources, vec![source]);
7793 assert_eq!(back.lanes, two(Vec::new(), Vec::new()));
7794 assert_eq!(back.playhead, 0);
7795 // Older dialects, where the two lanes are implied rather than declared.
7796 assert_eq!(
7797 parse(b"edith 1\nsource a.mp4\n", &dir).expect("v1").lanes,
7798 two(Vec::new(), Vec::new())
7799 );
7800 assert!(
7801 parse(b"edith 1\n", &dir)
7802 .expect("a project of nothing")
7803 .sources
7804 .is_empty()
7805 );
7806 }
7807
7808 /// Every truncation of a good file either parses or refuses; none panics.
7809 #[test]
7810 fn truncations_never_panic() {
7811 let (dir, sources, lanes) = doc();
7812 let bytes = flat(&dir, &sources, &lanes, 12);
7813 for cut in 0..bytes.len() {
7814 let _ = parse(&bytes[..cut], &dir);
7815 // ...and the same file with a byte lopped off the front, which
7816 // shifts every field into the wrong place.
7817 let _ = parse(&bytes[cut..], &dir);
7818 }
7819 // A % escape at the very end of a line has nothing to consume.
7820 assert_eq!(
7821 parse(b"edith 1\nsource a%\nclip 0 5 0\n", &dir)
7822 .unwrap_err()
7823 .to_string(),
7824 "line 2: truncated % escape in the path"
7825 );
7826 }
7827
7828 /// A clip's visualizer field is a whole byte of flags, and a line naming one
7829 /// past it used to be truncated into a look nobody chose (`300` loaded as
7830 /// `44`, with the fast bit and the ink nibble both wrong). It is refused by
7831 /// name now, like the resolution's bound, the sample rate's range, the tone
7832 /// map and the encoder seat beside it.
7833 #[test]
7834 fn a_visualizer_byte_past_a_byte_is_refused_and_the_legal_ones_still_load() {
7835 // The door the parser reads that field through: the low bits are the
7836 // style, bit 3 the fast flag and the high nibble the ink, so every value a
7837 // byte holds is a look and 256 and up is not one.
7838 assert_eq!(flags_byte(b"0", 1).expect("zero is the plain look"), 0);
7839 assert_eq!(flags_byte(b"255", 1).expect("the whole byte is flags"), 255);
7840 let refused = flags_byte(b"300", 9).expect_err("300 is not a byte of flags");
7841 assert_eq!(
7842 refused.to_string(),
7843 "line 9: 300 is not a set of visualizer flags"
7844 );
7845 }
7846
7847 /// ...and the same field through the parser, on a document of the newest
7848 /// dialect: the legal byte is what lands in the clip, the illegal one is the
7849 /// refusal above rather than a truncation.
7850 #[test]
7851 fn a_clip_line_whose_visualizer_is_past_a_byte_loses_the_whole_load() {
7852 let dir = PathBuf::from("/proj");
7853 let line = |flags: &str| {
7854 format!(
7855 "edith 22\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
7856 video 1 0 0 30 0 - - - fit 1000 0 0 0 - {flags} 0\n"
7857 )
7858 };
7859 let doc = parse(line("12").as_bytes(), &dir).expect("12 is a look");
7860 // The keyword is the saver's own for this dialect, so a mismatch here would
7861 // be this test's line and not the field it is about.
7862 assert_eq!(doc.lanes[0].1[0].visualizer, 12);
7863 let refused = parse(line("300").as_bytes(), &dir).expect_err("300 is not a look");
7864 assert!(
7865 refused
7866 .to_string()
7867 .contains("is not a set of visualizer flags"),
7868 "{refused}"
7869 );
7870 }
7871}
7872
7873#[cfg(test)]
7874mod title_tests {
7875 use super::*;
7876
7877 fn sample() -> Vec<Title> {
7878 vec![
7879 Title {
7880 start: 0,
7881 frames: 90,
7882 text: "Episode 17\n100% \\ done".into(),
7883 style: TextStyle {
7884 size: 80,
7885 outline: Outline::Thick,
7886 boxed: false,
7887 place: Place::Centre,
7888 ..TextStyle::default()
7889 },
7890 fade_in: 10,
7891 fade_out: 5,
7892 in_anim: TitleAnim::None,
7893 out_anim: TitleAnim::None,
7894 anim_frames: 0,
7895 keys: Vec::new(),
7896 },
7897 Title {
7898 start: 60,
7899 frames: 120,
7900 text: "Jane Doe \u{2014} Engineer".into(),
7901 style: TextStyle::default(),
7902 fade_in: 0,
7903 fade_out: 0,
7904 in_anim: Default::default(),
7905 out_anim: Default::default(),
7906 anim_frames: 0,
7907 keys: Vec::new(),
7908 },
7909 ]
7910 }
7911
7912 fn styled() -> Vec<Title> {
7913 let mut t = sample();
7914 t[1].style = TextStyle {
7915 hplace: HPlace::Left,
7916 align: Align::Right,
7917 weight: Weight::Bold,
7918 ink: [255, 204, 0],
7919 box_color: [10, 20, 30, 200],
7920 ..TextStyle::default()
7921 };
7922 t
7923 }
7924
7925 #[test]
7926 fn a_title_look_round_trips_and_only_a_styled_one_writes_a_line() {
7927 // Default looks write no `titlestyle` line at all.
7928 assert!(!String::from_utf8(title_lines(&sample())).unwrap().contains("titlestyle"));
7929 let titles = styled();
7930 let body = title_lines(&titles);
7931 let text = String::from_utf8(body.clone()).unwrap();
7932 assert_eq!(text.matches("titlestyle").count(), 1);
7933 assert!(text.contains("titlestyle 1 left right bold ffcc00 0a141ec8\n"), "{text}");
7934 let mut bytes = b"edith 49\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7935 bytes.extend_from_slice(&body);
7936 let doc = parse(&bytes, Path::new(".")).expect("a v49 file with a title look parses");
7937 assert_eq!(doc.titles, titles);
7938 let mut again = b"edith 49\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7939 again.extend_from_slice(&title_lines(&doc.titles));
7940 assert_eq!(again, bytes);
7941 }
7942
7943 #[test]
7944 fn a_title_look_is_a_v49_line_and_a_bad_one_is_refused_by_name() {
7945 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");
7946 let ok = format!("{}titlestyle 0 left left bold ffffff 000000ff\n", head(49));
7947 assert!(parse(ok.as_bytes(), Path::new(".")).is_ok());
7948 let old = format!("{}titlestyle 0 left left bold ffffff 000000ff\n", head(48));
7949 assert!(parse(old.as_bytes(), Path::new(".")).is_err(), "titlestyle is not a v48 line");
7950 // A v48 file with plain titles still loads, with the default look.
7951 let doc = parse(head(48).as_bytes(), Path::new(".")).unwrap();
7952 assert_eq!(doc.titles[0].style, TextStyle { boxed: true, ..TextStyle::default() });
7953 for line in [
7954 "titlestyle 0 middle left bold ffffff 000000ff",
7955 "titlestyle 0 left up bold ffffff 000000ff",
7956 "titlestyle 0 left left heavy ffffff 000000ff",
7957 "titlestyle 0 left left bold fff 000000ff",
7958 "titlestyle 0 left left bold ffffff 000000",
7959 "titlestyle 5 left left bold ffffff 000000ff",
7960 ] {
7961 let text = format!("{}{line}\n", head(49));
7962 assert!(parse(text.as_bytes(), Path::new(".")).is_err(), "{line}");
7963 }
7964 }
7965
7966 #[test]
7967 fn title_lines_round_trip_through_the_loader_with_escapes() {
7968 let titles = sample();
7969 let mut bytes = b"edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7970 bytes.extend_from_slice(&title_lines(&titles));
7971 let doc = parse(&bytes, Path::new(".")).expect("a v26 file with titles parses");
7972 assert_eq!(doc.titles, titles);
7973 // Written and read again, the same bytes come back.
7974 let mut again = b"edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n".to_vec();
7975 again.extend_from_slice(&title_lines(&doc.titles));
7976 assert_eq!(again, bytes);
7977 }
7978
7979 #[test]
7980 fn a_v25_file_has_no_titles_and_loads() {
7981 let v25 = b"edith 25\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n";
7982 let doc = parse(v25, Path::new(".")).expect("v25 still loads");
7983 assert!(doc.titles.is_empty());
7984 let as_v25 = b"edith 25\nplayhead 0\nsource 0 a.mp4\ntitle 0 10 0 0 50 none 0 bottom hi\n";
7985 assert!(
7986 parse(as_v25, Path::new(".")).is_err(),
7987 "title is not a v25 line"
7988 );
7989 }
7990
7991 #[test]
7992 fn a_title_line_outside_its_range_is_refused_by_name() {
7993 let head = "edith 28\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n";
7994 for line in [
7995 "title 0 0 0 0 50 none 0 bottom hi",
7996 "title 0 10 0 0 9 none 0 bottom hi",
7997 "title 0 10 0 0 50 wavy 0 bottom hi",
7998 "title 0 10 0 0 50 none 2 bottom hi",
7999 "title 0 10 0 0 50 none 0 middle hi",
8000 "title 0 10 11 0 50 none 0 bottom hi",
8001 "title 0 10 0 0 50 none 0 bottom",
8002 ] {
8003 let body = format!("{head}{line}\n");
8004 assert!(
8005 parse(body.as_bytes(), Path::new(".")).is_err(),
8006 "{line} was accepted"
8007 );
8008 }
8009 }
8010}
8011
8012#[cfg(test)]
8013mod clip_gain_tests {
8014 use super::*;
8015
8016 /// A v26 file loads, every clip at unity; a `clipgain` line in one is a
8017 /// line the dialect does not have, so it is refused by number.
8018 #[test]
8019 fn a_v26_file_loads_at_unity_and_refuses_a_clipgain_line() {
8020 let dir = PathBuf::from("/proj");
8021 let old = b"edith 26\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8022 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8023 let doc = parse(old, &dir).expect("a v26 file still loads");
8024 assert_eq!(doc.lanes[0].1[0].gain_db, 0.0);
8025 let with = b"edith 26\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8026 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\nclipgain audio 1 0 -6\n";
8027 let err = parse(with, &dir).unwrap_err().to_string();
8028 assert!(err.contains("line 6"), "{err}");
8029 }
8030
8031 /// The writer's own bytes: a gained clip gets a `clipgain` line after its
8032 /// lanes, unity clips get none, and the value comes back exactly.
8033 #[test]
8034 fn clip_gain_lines_are_written_only_off_unity_and_round_trip() {
8035 let dir = PathBuf::from("/proj");
8036 let clip = |gain_db: f32| Clip {
8037 speed_keys: Vec::new(),
8038 reversed: false,
8039 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
8040 angle: Default::default(),
8041 gain_keys: Vec::new(),
8042 pan: 0,
8043 transform_keys: Vec::new(),
8044 opacity_keys: Vec::new(),
8045 color_keys: Vec::new(),
8046 effects: Vec::new(),
8047 start: 0,
8048 in_frame: 0,
8049 out_frame: 30,
8050 source: 0,
8051 link: None,
8052 eq: None,
8053 color: None,
8054 transform: None,
8055 fit: FitPolicy::default(),
8056 speed: Speed::NORMAL,
8057 fade_in: 0,
8058 fade_out: 0,
8059 transition_out: 0,
8060 transition_kind: Default::default(),
8061 visualizer: 0,
8062 viz_paint: 0,
8063 gain_db,
8064 pitch: 0.0,
8065 };
8066 let lanes = vec![
8067 (LaneKind::Video, vec![clip(0.0)]),
8068 (LaneKind::Audio, vec![clip(-6.5), clip(0.0)]),
8069 ];
8070 let bytes = clip_gain_lines(&lanes);
8071 assert_eq!(bytes, b"clipgain audio 1 0 -6.5\n".to_vec());
8072 let mut text = b"edith 27\nplayhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8073 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8074 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8075 audio 1 30 0 30 0 - - - fit 1000 0 0 0 - 0 0\n"
8076 .to_vec();
8077 text.extend_from_slice(&bytes);
8078 let doc = parse(&text, &dir).expect("a v27 file with a clip gain parses");
8079 assert_eq!(doc.lanes[1].1[0].gain_db, -6.5);
8080 assert_eq!(doc.lanes[1].1[1].gain_db, 0.0);
8081 }
8082}
8083
8084#[cfg(test)]
8085mod gain_key_tests {
8086 use super::*;
8087
8088 const HEAD: &str = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8089 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8090
8091 /// A v27 file loads with every clip's envelope empty, and a `gainkeys` line
8092 /// in one is a line the dialect does not have, so it is refused by number.
8093 #[test]
8094 fn a_v27_file_loads_flat_and_refuses_a_gainkeys_line() {
8095 let dir = PathBuf::from("/proj");
8096 let old = format!("edith 27\n{HEAD}");
8097 let doc = parse(old.as_bytes(), &dir).expect("a v27 file still loads");
8098 assert!(doc.lanes[0].1[0].gain_keys.is_empty());
8099 let with = format!("edith 27\n{HEAD}gainkeys audio 1 0 0:-6\n");
8100 let err = parse(with.as_bytes(), &dir).unwrap_err().to_string();
8101 assert!(err.contains("line 6"), "{err}");
8102 }
8103
8104 /// The writer's own bytes: a clip with points gets one `gainkeys` line after
8105 /// its lanes, a clip without gets none, and the points come back exactly.
8106 #[test]
8107 fn gain_key_lines_are_written_only_with_points_and_round_trip() {
8108 let dir = PathBuf::from("/proj");
8109 let mut text = format!("edith 28\n{HEAD}").into_bytes();
8110 text.extend_from_slice(b"gainkeys audio 1 0 0:0 30:-20 45:-6.5\n");
8111 let doc = parse(&text, &dir).expect("a v28 file with an envelope parses");
8112 let keys = &doc.lanes[0].1[0].gain_keys;
8113 assert_eq!(
8114 keys,
8115 &[
8116 GainKey::new(0, 0.0),
8117 GainKey::new(30, -20.0),
8118 GainKey::new(45, -6.5),
8119 ]
8120 );
8121 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8122 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8123 let bytes = gain_key_lines(&lanes);
8124 assert_eq!(bytes, b"gainkeys audio 1 0 0:0 30:-20 45:-6.5\n".to_vec());
8125 let again = parse(
8126 &[format!("edith 28\n{HEAD}").as_bytes(), &bytes].concat(),
8127 &dir,
8128 )
8129 .expect("the writer's own line parses");
8130 assert_eq!(again.lanes[0].1[0].gain_keys, *keys);
8131 }
8132
8133 /// A ramp can make a clip shorter than its constant footprint, which the lines before
8134 /// its `speedkeys` still show: the next clip, placed against the ramp's length, loads;
8135 /// one that really overlaps the ramped footprint is refused.
8136 #[test]
8137 fn a_clip_placed_against_a_shorter_ramp_loads_and_a_real_overlap_does_not() {
8138 let dir = PathBuf::from("/proj");
8139 let next = |start: u32| {
8140 format!("audio 1 {start} 0 30 0 - - - fit 1000 0 0 0 - 0 0\n")
8141 };
8142 let ok = format!("edith 35\n{HEAD}{}speedkeys audio 1 0 0:1000 30:2000\n", next(22));
8143 let doc = parse(ok.as_bytes(), &dir).expect("the ramp is 22 frames, the next clip starts at 22");
8144 assert_eq!(doc.lanes[0].1.len(), 2);
8145 let bad = format!("edith 35\n{HEAD}{}speedkeys audio 1 0 0:1000 30:2000\n", next(21));
8146 assert!(parse(bad.as_bytes(), &dir).is_err(), "21 is inside the ramped clip");
8147 }
8148
8149 /// A `speedkeys` line is a v35 clip's ramp: it reads back as the keys, its footprint
8150 /// is the ramp's, and the writer's own line reads back to the same keys. A clip with no
8151 /// keys writes no line.
8152 #[test]
8153 fn speedkeys_lines_round_trip_and_a_clip_without_a_ramp_writes_none() {
8154 let dir = PathBuf::from("/proj");
8155 let text = format!("edith 35\n{HEAD}speedkeys audio 1 0 0:1000 30:2000\n");
8156 let doc = parse(text.as_bytes(), &dir).expect("a v35 file with a ramp parses");
8157 let clip = &doc.lanes[0].1[0];
8158 assert_eq!(
8159 clip.speed_keys,
8160 vec![
8161 SpeedKey { at: 0, speed: Speed::NORMAL },
8162 SpeedKey { at: 30, speed: Speed::from_permille(2000) },
8163 ]
8164 );
8165 // 30 source frames at a rate that climbs from 1x to 2x: 22 timeline frames.
8166 assert_eq!(clip.frames(), 22);
8167 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8168 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8169 assert_eq!(speed_key_lines(&lanes), b"speedkeys audio 1 0 0:1000 30:2000\n".to_vec());
8170 let mut plain = lanes.clone();
8171 plain[0].1[0].speed_keys.clear();
8172 assert!(speed_key_lines(&plain).is_empty(), "no ramp, no line");
8173 let again = parse(
8174 &[format!("edith 35\n{HEAD}").as_bytes(), &speed_key_lines(&lanes)].concat(),
8175 &dir,
8176 )
8177 .expect("the writer's own line parses");
8178 assert_eq!(again.lanes[0].1[0].speed_keys, clip.speed_keys);
8179 }
8180
8181 /// A `transition` line (v37) names how a clip's dissolve is drawn: every kind's name
8182 /// reads back as the kind, the writer's own lines parse, a clip with the default writes
8183 /// none, and an older file (no line) means a dissolve.
8184 #[test]
8185 fn transition_lines_round_trip_every_kind_and_old_files_dissolve() {
8186 let dir = PathBuf::from("/proj");
8187 let head = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8188 video 1 0 0 30 0 - - - fit 1000 0 0 9 - 0 0\n";
8189 let old = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("v35 parses");
8190 assert_eq!(old.lanes[0].1[0].transition_kind, TransitionKind::Dissolve);
8191 let mut kinds = Vec::new();
8192 for shape in TransitionKind::SHAPES {
8193 match shape.dir() {
8194 Some(_) => kinds.extend(crate::transitions::Dir::ALL.map(|d| shape.with_dir(d))),
8195 None => kinds.push(shape),
8196 }
8197 }
8198 for kind in kinds {
8199 let mut lanes: Vec<(LaneKind, Vec<Clip>)> = old.lanes.clone();
8200 lanes[0].1[0].transition_kind = kind;
8201 let lines = transition_lines(&lanes);
8202 if kind == TransitionKind::Dissolve {
8203 assert!(lines.is_empty(), "the default writes no line");
8204 }
8205 let text = [format!("edith 37\n{head}").as_bytes(), &lines].concat();
8206 let back = parse(&text, &dir).unwrap_or_else(|e| panic!("{}: {e}", kind.name()));
8207 assert_eq!(back.lanes[0].1[0].transition_kind, kind);
8208 }
8209 for bad in ["transition video 1 0 swirl\n", "transition video 1 4 zoom\n", "transition video 2 0 zoom\n"] {
8210 let err = parse(format!("edith 37\n{head}{bad}").as_bytes(), &dir).unwrap_err().to_string();
8211 assert!(err.contains("line 6"), "{bad}: {err}");
8212 }
8213 for old in [35, 36] {
8214 let file = format!("edith {old}\n{head}transition video 1 0 zoom\n");
8215 assert!(parse(file.as_bytes(), &dir).is_err(), "a v{old} reader has no such line");
8216 }
8217 }
8218
8219 /// The writer emits the highest version a project needs: markers alone are v36, a
8220 /// transition kind makes it v37 (markers and all, which round-trip together), only
8221 /// dissolves and no markers fall back to the older header, and a v36 file still loads.
8222 #[test]
8223 fn the_header_is_the_highest_version_needed_and_v36_and_v37_round_trip() {
8224 use crate::project::{Marker, MarkerColor};
8225 let dir = std::env::temp_dir().join(format!("edith-v37-{}", std::process::id()));
8226 std::fs::create_dir_all(&dir).unwrap();
8227 let path = dir.join("v37.edith");
8228 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";
8229 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8230 let sources = doc.sources;
8231 let mut lanes = doc.lanes;
8232 let markers = vec![Marker { frame: 12, length: 0, name: "Beat".into(), note: "a note".into(), color: MarkerColor::Blue }];
8233 let save_styled = |lanes: &[(LaneKind, Vec<Clip>)], markers: &[Marker], cs: &CaptionStyle| {
8234 save_flagged(
8235 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8236 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8237 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], markers, cs, &[], &[],
8238 )
8239 .expect("saves");
8240 std::fs::read_to_string(&path).unwrap()
8241 };
8242 let save = |lanes: &[(LaneKind, Vec<Clip>)], markers: &[Marker]| {
8243 save_styled(lanes, markers, &CaptionStyle::default())
8244 };
8245 assert!(save(&lanes, &markers).starts_with("edith 36\n"), "markers alone are v36");
8246 lanes[0].1[0].transition_kind = TransitionKind::Zoom;
8247 let text = save(&lanes, &markers);
8248 assert!(text.starts_with("edith 37\n"), "a transition makes it v37: {text}");
8249 let back = load(&path).expect("v37 loads");
8250 assert_eq!(back.markers, markers);
8251 assert_eq!(back.lanes[0].1[0].transition_kind, TransitionKind::Zoom);
8252 let text = save(&lanes, &[]);
8253 assert!(text.starts_with("edith 37\n") && text.contains("transition "), "{text}");
8254 lanes[0].1[0].reversed = true;
8255 let text = save(&lanes, &markers);
8256 assert!(text.starts_with("edith 38\n") && text.contains("reverse video 1 0"), "a reversed clip makes it v38: {text}");
8257 let back = load(&path).expect("v38 loads");
8258 assert!(back.lanes[0].1[0].reversed && back.markers == markers);
8259 assert_eq!(back.lanes[0].1[0].transition_kind, TransitionKind::Zoom);
8260 lanes[0].1[0].opacity_keys = vec![OpacityKey { at: 0, opacity: 0.5, ease: KeyEase::Hold }];
8261 let text = save(&lanes, &markers);
8262 assert!(text.starts_with("edith 39\n") && text.contains("okeys video 1 0"), "an animation makes it v39: {text}");
8263 let back = load(&path).expect("v39 loads");
8264 assert!(back.lanes[0].1[0].reversed && back.markers == markers);
8265 assert_eq!(back.lanes[0].1[0].opacity_keys.len(), 1);
8266 // ...and a project caption style on top of all of it makes it v40.
8267 let style = CaptionStyle { anim: crate::captionanim::CaptionAnim::Pop, ..CaptionStyle::default() };
8268 let text = save_styled(&lanes, &markers, &style);
8269 assert!(text.starts_with("edith 40\n") && text.contains("\ncapstyle pop "), "a caption style makes it v40: {text}");
8270 let back = load(&path).expect("v40 loads");
8271 assert!(back.lanes[0].1[0].reversed && back.markers == markers && back.caption_style == style);
8272 assert_eq!(back.lanes[0].1[0].opacity_keys.len(), 1);
8273 lanes[0].1[0].opacity_keys.clear();
8274 lanes[0].1[0].reversed = false;
8275 lanes[0].1[0].transition_kind = TransitionKind::Dissolve;
8276 let text = save(&lanes, &[]);
8277 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}");
8278 let v36 = parse(b"edith 36\nplayhead 0\nsource 0 a.mp4\nmarker 0 0 red A\n", &dir).expect("a v36 file loads");
8279 assert_eq!(v36.markers.len(), 1);
8280 std::fs::remove_dir_all(&dir).ok();
8281 }
8282
8283 /// `lanename` and `deint` lines are v46: both round-trip, a project with neither keeps
8284 /// its older header and exact bytes, an older header refuses them and bad ones are
8285 /// refused by line.
8286 #[test]
8287 fn lane_names_and_deinterlace_round_trip_in_v46_and_without_them_the_bytes_are_unchanged() {
8288 let dir = std::env::temp_dir().join(format!("edith-v46-{}", std::process::id()));
8289 std::fs::create_dir_all(&dir).unwrap();
8290 let path = dir.join("v46.edith");
8291 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";
8292 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8293 let sources = doc.sources;
8294 let mut lanes = doc.lanes;
8295 let n = lanes.len();
8296 let save = |lanes: &[(LaneKind, Vec<Clip>)], names: &[String]| {
8297 save_flagged(
8298 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8299 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8300 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], names,
8301 )
8302 .expect("saves");
8303 std::fs::read_to_string(&path).unwrap()
8304 };
8305 let blank = vec![String::new(); n];
8306 let plain = save(&lanes, &blank);
8307 assert!(!plain.contains("lanename") && !plain.contains("deint") && !plain.starts_with("edith 46"), "{plain}");
8308 let mut names = blank.clone();
8309 names[0] = "Main \\ cam".into();
8310 let text = save(&lanes, &names);
8311 assert!(text.starts_with("edith 46\n") && text.contains("\nlanename video 1 Main \\\\ cam\n"), "{text}");
8312 assert_eq!(load(&path).expect("v46 loads").names[0], "Main \\ cam");
8313 assert_eq!(save(&lanes, &blank), plain, "no names is the bytes it was");
8314 lanes[0].1[0].deinterlace = Deinterlace::Field;
8315 let text = save(&lanes, &blank);
8316 assert!(text.starts_with("edith 46\n") && text.contains("\ndeint video 1 0 field\n"), "{text}");
8317 assert_eq!(load(&path).unwrap().lanes[0].1[0].deinterlace, Deinterlace::Field);
8318 for older in ["edith 45", "edith 44"] {
8319 for line in ["lanename video 1 X\n", "deint video 1 0 off\n"] {
8320 let old = format!("{older}\n{head}{line}");
8321 assert!(parse(old.as_bytes(), &dir).is_err(), "{older} refuses {line:?}");
8322 }
8323 }
8324 for (line, why) in [
8325 ("lanename video 1 \n", "1 to"),
8326 ("lanename video 3 X\n", "not there"),
8327 ("lanename tape 1 X\n", "not a lane kind"),
8328 ("deint video 1 0 weave\n", "frame, field or off"),
8329 ("deint video 1 4 off\n", "does not have"),
8330 ] {
8331 let err = parse(format!("edith 46\n{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8332 assert!(err.contains(why) && err.contains("line"), "{line:?}: {err}");
8333 }
8334 let long = "x".repeat(crate::project::MAX_LANE_NAME_CHARS + 1);
8335 assert!(parse(format!("edith 46\n{head}lanename video 1 {long}\n").as_bytes(), &dir).is_err());
8336 std::fs::remove_file(&path).ok();
8337 std::fs::remove_dir(&dir).ok();
8338 }
8339
8340 /// A `stab` line is a v44 clip's stabilisation: it round-trips through a save, a
8341 /// project with no stabilised clip keeps its older header and its exact bytes, an
8342 /// older file refuses the line and a bad one is refused by its line number.
8343 #[test]
8344 fn stab_lines_round_trip_in_v44_and_without_one_the_bytes_are_unchanged() {
8345 let dir = std::env::temp_dir().join(format!("edith-stab-{}", std::process::id()));
8346 std::fs::create_dir_all(&dir).unwrap();
8347 let path = dir.join("v44.edith");
8348 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";
8349 let doc = parse(format!("edith 35\n{head}").as_bytes(), &dir).expect("parses");
8350 let sources = doc.sources;
8351 let mut lanes = doc.lanes;
8352 let save = |lanes: &[(LaneKind, Vec<Clip>)]| {
8353 save_flagged(
8354 &path, &sources, lanes, &[], &[], &[], &[], &[], &[], (1280, 720), Some(25.0),
8355 crate::tonemap::Preset::default(), false, true, crate::export::EncoderSeat::default(),
8356 Limiter::default(), None, 0, &[], &[], &[], &[], &[], &[], &[], &CaptionStyle::default(), &[], &[],
8357 )
8358 .expect("saves");
8359 std::fs::read_to_string(&path).unwrap()
8360 };
8361 let plain = save(&lanes);
8362 assert!(!plain.contains("stab") && !plain.starts_with("edith 44"), "{plain}");
8363 let st = crate::stabilise::Stabilise::new(0.75, crate::stabilise::Crop::Full);
8364 lanes[0].1[0].stabilise = Some(st);
8365 let text = save(&lanes);
8366 assert!(text.starts_with("edith 44\n") && text.contains("\nstab video 1 0 0.75 full\n"), "{text}");
8367 assert_eq!(load(&path).expect("v44 loads").lanes[0].1[0].stabilise, Some(st));
8368 lanes[0].1[0].stabilise = None;
8369 assert_eq!(save(&lanes), plain, "off again is the bytes it was");
8370 for older in ["edith 43", "edith 42", "edith 41"] {
8371 let old = format!("{older}\n{head}stab video 1 0 0.5 zoom\n");
8372 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("stab"), "{older} has no stab line");
8373 }
8374 for (line, why) in [
8375 ("stab video 1 0 0.5\n", "wants a video clip"),
8376 ("stab video 1 0 1.5 zoom\n", "from 0 to 1"),
8377 ("stab video 1 0 0.5 tilt\n", "zoom or full"),
8378 ("stab video 1 4 0.5 zoom\n", "which the lane does not have"),
8379 ] {
8380 let err = parse(format!("edith 44\n{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8381 assert!(err.contains(why) && err.starts_with("line "), "{line:?}: {err}");
8382 }
8383 std::fs::remove_dir_all(&dir).ok();
8384 }
8385
8386 /// A `reverse` line is a v38 clip's direction: it reads back as `reversed`, the
8387 /// writer's own line reads back the same, a project with none is written under
8388 /// the v35 header it always was, and an older file or a bad line is refused by
8389 /// its line number.
8390 #[test]
8391 fn reverse_lines_round_trip_and_older_files_and_bad_lines_are_refused() {
8392 let dir = PathBuf::from("/proj");
8393 let text = format!("edith 38\n{HEAD}reverse audio 1 0\n");
8394 let doc = parse(text.as_bytes(), &dir).expect("a v38 file with a reversed clip parses");
8395 assert!(doc.lanes[0].1[0].reversed);
8396 let lanes: Vec<(LaneKind, Vec<Clip>)> =
8397 doc.lanes.iter().map(|(k, c)| (*k, c.clone())).collect();
8398 assert_eq!(reverse_lines(&lanes), b"reverse audio 1 0\n".to_vec());
8399 let mut plain = lanes.clone();
8400 plain[0].1[0].reversed = false;
8401 assert!(reverse_lines(&plain).is_empty(), "forward, no line");
8402 let again = parse(
8403 &[format!("edith 38\n{HEAD}").as_bytes(), &reverse_lines(&lanes)].concat(),
8404 &dir,
8405 )
8406 .expect("the writer's own line parses");
8407 assert!(again.lanes[0].1[0].reversed);
8408 // A v37 file (or older) has no such line.
8409 for old in [35, 37] {
8410 let file = format!("edith {old}\n{HEAD}reverse audio 1 0\n");
8411 let err = parse(file.as_bytes(), &dir).unwrap_err().to_string();
8412 assert!(err.contains("reverse"), "v{old}: {err}");
8413 }
8414 let head = format!("edith 38\n{HEAD}");
8415 for (line, why) in [
8416 ("reverse audio 1\n", "wants a lane and a clip"),
8417 ("reverse subtitle 1 0\n", "not a lane kind"),
8418 ("reverse audio 9 0\n", "a lane that is not there"),
8419 ("reverse audio 1 5\n", "which the lane does not have"),
8420 ] {
8421 let err = parse(format!("{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8422 assert!(err.contains(why) && err.starts_with("line "), "{line:?}: {err}");
8423 }
8424 }
8425
8426 /// A v34 file has no `speedkeys` line, and a bad ramp is refused by its line: a speed
8427 /// out of range, keys out of frame order, a key without a speed, or more than the cap.
8428 #[test]
8429 fn a_v34_file_refuses_a_speedkeys_line_and_a_bad_ramp_is_refused() {
8430 let dir = PathBuf::from("/proj");
8431 let v34 = format!("edith 34\n{HEAD}speedkeys audio 1 0 0:1000 30:2000\n");
8432 let err = parse(v34.as_bytes(), &dir).unwrap_err().to_string();
8433 assert!(err.contains("speedkeys"), "{err}");
8434 let head = format!("edith 35\n{HEAD}");
8435 let too_many: String = (0..65).map(|i| format!(" {i}:1000")).collect();
8436 for line in [
8437 &format!("speedkeys audio 1 0{too_many}\n")[..],
8438 "speedkeys audio 1 0 0:9000\n",
8439 "speedkeys audio 1 0 30:1000 0:1000\n",
8440 "speedkeys audio 1 0 0\n",
8441 ] {
8442 let err = parse(format!("{head}{line}").as_bytes(), &dir).unwrap_err().to_string();
8443 assert!(err.contains("line 6"), "{line}: {err}");
8444 }
8445 }
8446
8447 /// A point out of source order, one out of range, or a clip with more than
8448 /// the cap are all refused by line; the dialect keeps the invariants.
8449 #[test]
8450 fn a_bad_gainkeys_line_is_refused() {
8451 let dir = PathBuf::from("/proj");
8452 let head = format!("edith 28\n{HEAD}");
8453 for line in [
8454 "gainkeys audio 1 0 30:-6 0:0\n",
8455 "gainkeys audio 1 0 0:-90\n",
8456 "gainkeys audio 1 0 0\n",
8457 "gainkeys audio 1 0 0 0x\n",
8458 ] {
8459 let text = format!("{head}{line}");
8460 let err = parse(text.as_bytes(), &dir).unwrap_err().to_string();
8461 assert!(err.contains("line 6"), "{line}: {err}");
8462 }
8463 let many: String = (0..=MAX_GAIN_KEYS as u32)
8464 .map(|i| format!(" {i}:0"))
8465 .collect();
8466 let text = format!("{head}gainkeys audio 1 0 0{many}\n");
8467 let err = parse(text.as_bytes(), &dir).unwrap_err().to_string();
8468 assert!(err.contains("more than"), "{err}");
8469 }
8470}
8471
8472#[cfg(test)]
8473mod animation_key_tests {
8474 use super::*;
8475
8476 const HEAD: &str = "playhead 0\nresolution 1280 720\nsource 0 a.mp4\n\
8477 video 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n\
8478 audio 1 0 0 30 0 - - - fit 1000 0 0 0 - 0 0\n";
8479
8480 /// A v35 file written before the easings existed still loads, every key linear
8481 /// (or the `ease` it said), and resaving it does not change a key.
8482 #[test]
8483 fn a_v35_file_upgrades_with_its_keys_linear_and_resaves_as_v32_bytes() {
8484 let dir = PathBuf::from("/proj");
8485 let text = format!(
8486 "edith 35\n{HEAD}gainkeys audio 1 0 0:0 20:-6.5\n\
8487 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"
8488 );
8489 let doc = parse(text.as_bytes(), &dir).expect("a v35 file loads");
8490 let clips = &doc.lanes[1].1;
8491 assert_eq!(clips[0].gain_keys, [GainKey::new(0, 0.0), GainKey::new(20, -6.5)]);
8492 assert_eq!(doc.lanes[0].1[0].transform_keys[1].ease, KeyEase::Ease);
8493 assert!(doc.lanes[0].1[0].opacity_keys.is_empty() && doc.lanes[0].1[0].color_keys.is_empty());
8494 // The writers' lines for those clips are the bytes the file had.
8495 assert_eq!(gain_key_lines(&doc.lanes), b"gainkeys audio 1 0 0:0 20:-6.5\n".to_vec());
8496 assert_eq!(
8497 tkey_lines(&doc.lanes),
8498 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()
8499 );
8500 assert!(doc.lanes.iter().all(|(_, clips)| !clips.iter().any(needs_v39)), "still not a v39 project");
8501 assert!(opacity_key_lines(&doc.lanes).is_empty() && color_key_lines(&doc.lanes).is_empty());
8502 }
8503
8504 /// The v39 lines read back, in range and in order, and an older dialect has
8505 /// no such lines (nor the new easings) and says so by line number.
8506 #[test]
8507 fn v39_reads_okeys_ckeys_and_eased_points_and_older_dialects_refuse_them() {
8508 let dir = PathBuf::from("/proj");
8509 let new = format!(
8510 "edith 39\n{HEAD}okeys video 1 0 0:in:0 10:hold:0.5 20:lin:1\n\
8511 ckeys video 1 0 0:out:-0.5,1,1,0 20:ease:0.5,2,0,0.25\n\
8512 gainkeys audio 1 0 0:0:out 20:-6.5:hold 30:-3\n\
8513 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"
8514 );
8515 let doc = parse(new.as_bytes(), &dir).expect("a v39 file loads");
8516 let v = &doc.lanes[0].1[0];
8517 assert_eq!(v.opacity_keys.len(), 3);
8518 assert_eq!(v.opacity_keys[0].ease, KeyEase::EaseIn);
8519 assert_eq!(v.opacity_keys[1], OpacityKey { at: 10, opacity: 0.5, ease: KeyEase::Hold });
8520 assert_eq!(v.color_keys[0].ease, KeyEase::EaseOut);
8521 assert_eq!(v.color_keys[1].params.contrast, 2.0);
8522 assert_eq!(v.transform_keys[1].ease, KeyEase::Hold);
8523 let g = &doc.lanes[1].1[0].gain_keys;
8524 assert_eq!((g[0].ease, g[1].ease, g[2].ease), (KeyEase::EaseOut, KeyEase::Hold, KeyEase::Linear));
8525 // ...and writing them gives the same lines back.
8526 assert_eq!(
8527 opacity_key_lines(&doc.lanes),
8528 b"okeys video 1 0 0:in:0 10:hold:0.5 20:lin:1\n".to_vec()
8529 );
8530 assert_eq!(
8531 color_key_lines(&doc.lanes),
8532 b"ckeys video 1 0 0:out:-0.5,1,1,0 20:ease:0.5,2,0,0.25\n".to_vec()
8533 );
8534 assert_eq!(gain_key_lines(&doc.lanes), b"gainkeys audio 1 0 0:0:out 20:-6.5:hold 30:-3\n".to_vec());
8535
8536 // A v35 reader has none of it.
8537 let old = format!("edith 35\n{HEAD}okeys video 1 0 0:lin:0\n");
8538 assert!(parse(old.as_bytes(), &dir).unwrap_err().to_string().contains("line 7"));
8539 // ...and so has a v38 one.
8540 let old = format!("edith 38\n{HEAD}okeys video 1 0 0:lin:0\n");
8541 assert!(parse(old.as_bytes(), &dir).is_err(), "a v38 reader has no okeys line");
8542 let old = format!("edith 35\n{HEAD}tkeys video 1 0 0:hold:0,0,1,0,0,0,0,0,1\n");
8543 assert!(parse(old.as_bytes(), &dir).is_err(), "a hold ease is not a v35 word");
8544 }
8545
8546 #[test]
8547 fn bad_okeys_and_ckeys_lines_are_refused() {
8548 let dir = PathBuf::from("/proj");
8549 for bad in [
8550 "okeys video 1 0 0:lin:1.5", // opacity out of range
8551 "okeys video 1 0 5:lin:0 5:lin:1", // two at one frame
8552 "okeys video 1 0 9:lin:0 5:lin:1", // not in source order
8553 "okeys video 1 0 0:wobble:1", // unknown ease
8554 "okeys audio 1 0 0:lin:1", // not a video lane
8555 "okeys video 1 3 0:lin:1", // no such clip
8556 "ckeys video 1 0 0:lin:2,1,1,0", // brightness out of range
8557 "ckeys video 1 0 0:lin:0,1,1", // three values
8558 "ckeys video 1 0 0:lin:0,3,1,0", // contrast out of range
8559 ] {
8560 let text = format!("edith 39\n{HEAD}{bad}\n");
8561 assert!(parse(text.as_bytes(), &dir).is_err(), "{bad}");
8562 }
8563 }
8564}