forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7cb30bfTahinli2 months ago908 commits

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