forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB5530fbdTahinli3 months ago209 commits

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