forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbdcc2fbTahinli3 months ago176 commits

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