forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB892f813Tahinli3 months ago398 commits

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