forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB33ee2baTahinli2 months ago960 commits

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