forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

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