forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2b647eaTahinli3 months ago190 commits

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