forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB6dae2b4Tahinli3 months ago555 commits

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