diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 6211b10..cac41c9 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -3460,6 +3460,7 @@ mod tests { source, link: None, eq: None, + color: None, } } @@ -3650,6 +3651,7 @@ mod tests { source: 0, link: None, eq: None, + color: None, }; assert_eq!(clip.end(), 90); // Cut splits from inside only: neither edge has anything to split off. diff --git a/crates/engine/src/edith.rs b/crates/engine/src/edith.rs index 8936d18..7c8876e 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,14 +1,15 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 5 +//! edith 6 //! playhead 90 //! source 0 test_av.mp4 //! source 1 /elsewhere/test_av2.mp4 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk -//! video 1 0 0 120 0 0 0 -//! audio 1 0 0 120 0 0 0 -//! video 2 120 0 120 1 - - +//! color 0.1:1.2:0.9:-0.3 +//! video 1 0 0 120 0 0 0 0 +//! audio 1 0 0 120 0 0 0 - +//! video 2 120 0 120 1 - - - //! audio 2 //! ``` //! @@ -26,29 +27,35 @@ //! setting like any other. The numbers are printed to round trip bit-exactly; //! anything not finite is refused, here and at [`crate::Project::set_eq`]. //! -//! A lane line is ` `: -//! which lane the clip is on -- its kind and its 1-based number among the lanes -//! of that kind, the [`crate::project::Lane::label`] a header column shows -- -//! then where the clip sits on the timeline, the half-open source range it -//! plays, the file it plays from, its group id, and the eq line it plays -//! through (`-` for neither). Timeline placement is explicit, so a *gap* is -//! simply a stretch no line covers -- there is nothing to write for one, and -//! nothing that can disagree about its length. +//! A colour line is `color :::` +//! ([`crate::color::ColorParams`]), named by position exactly as an eq line is +//! -- the first colour line is color 0 -- printed and refused by the same rules. +//! +//! A lane line is ` +//! `: which lane the clip is on -- its kind and its 1-based number among +//! the lanes of that kind, the [`crate::project::Lane::label`] a header column +//! shows -- then where the clip sits on the timeline, the half-open source range +//! it plays, the file it plays from, its group id, the eq line it plays through +//! and the colour line it is graded by (`-` for none of them). Timeline +//! placement is explicit, so a *gap* is simply a stretch no line covers -- there +//! is nothing to write for one, and nothing that can disagree about its length. //! //! A lane is declared by the clips on it, in the order the lanes are displayed //! in; a lane holding *nothing* has a bare ` ` line instead, which //! is the only way an empty lane could still be there on the way back. A lane //! number may not skip one of its kind. //! -//! **Version 4** was this without the eq lines and without the clip's eq field. -//! **Version 3** was that without the lane number, and held one video lane and -//! one audio lane, no more. **Version 2** wrote `source ` as well, which -//! is this file's stream 0 -- one per file, whichever audio track came first. -//! **Version 1** wrote that and one lane, queued end to end: `clip -//! `. All four still load -- a v1 file's clips are laid out +//! **Version 5** was this without the colour lines and without the clip's colour +//! field. **Version 4** was that without the eq lines and without the clip's eq +//! field. **Version 3** was that without the lane number, and held one video +//! lane and one audio lane, no more. **Version 2** wrote `source ` as +//! well, which is this file's stream 0 -- one per file, whichever audio track +//! came first. **Version 1** wrote that and one lane, queued end to end: `clip +//! `. All five still load -- a v1 file's clips are laid out //! cumulatively and copied onto both lanes as one group each, which is exactly -//! what a v1 timeline meant, and an older file simply equalizes nothing -- and -//! saving any of them writes v5. An older reader refuses a newer file by name. +//! what a v1 timeline meant, and an older file simply equalizes and grades +//! nothing -- and saving any of them writes v6. An older reader refuses a newer +//! file by name. //! //! Text because an edit list is a few integers and a path, and a path is //! *bytes* on this platform -- a JSON string would have to lossily decode one. @@ -74,12 +81,14 @@ use std::io::Write; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::path::{Path, PathBuf}; +use crate::color::ColorParams; use crate::eq::{Band, BandKind, EqParams}; use crate::project::{Clip, Lane, LaneKind, Source}; /// What [`save`] writes. Read support goes back to `edith 1`; see the module /// docs for what those dialects looked like. -const MAGIC: &[u8] = b"edith 5"; +const MAGIC: &[u8] = b"edith 6"; +const MAGIC_V5: &[u8] = b"edith 5"; const MAGIC_V4: &[u8] = b"edith 4"; const MAGIC_V3: &[u8] = b"edith 3"; const MAGIC_V2: &[u8] = b"edith 2"; @@ -99,16 +108,20 @@ pub struct Document { /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for /// every dialect before v5. pub eq: Vec, + /// The colour table [`Clip::color`] indexes into, in file order. Empty for + /// every dialect before v6. + pub color: Vec, pub playhead: u32, } -/// Writes the project to `path`, atomically. `sources` and `eq` should already -/// be orphan-free ([`crate::Project::without_orphan_sources`]). +/// Writes the project to `path`, atomically. `sources`, `eq` and `color` should +/// already be orphan-free ([`crate::Project::without_orphan_sources`]). pub fn save( path: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], eq: &[EqParams], + color: &[ColorParams], playhead: u32, ) -> crate::Result<()> { let dir = project_dir(path); @@ -121,7 +134,7 @@ pub fn save( // the second one puts the name itself there. let result = std::fs::File::create(&part) .and_then(|mut f| { - f.write_all(&emit(&dir, sources, lanes, eq, playhead))?; + f.write_all(&emit(&dir, sources, lanes, eq, color, playhead))?; f.sync_all() }) .and_then(|()| std::fs::rename(&part, path)) @@ -156,6 +169,7 @@ fn emit( sources: &[Source], lanes: &[(LaneKind, Vec)], eq: &[EqParams], + color: &[ColorParams], playhead: u32, ) -> Vec { let mut out = Vec::new(); @@ -186,6 +200,16 @@ fn emit( } out.push(b'\n'); } + // ...and the colour table, for the same reason and by the same rules. + for p in color { + out.extend_from_slice( + format!( + "color {:?}:{:?}:{:?}:{:?}\n", + p.brightness, p.contrast, p.saturation, p.tint + ) + .as_bytes(), + ); + } // Lane by lane rather than interleaved by time: a lane reads as a list, the // parser gets its sortedness check for free from the order it is in, and // the lanes come back out in the order they are displayed in. @@ -209,9 +233,10 @@ fn emit( for c in clips { let link = c.link.map_or("-".to_string(), |l| l.to_string()); let eq = c.eq.map_or("-".to_string(), |e| e.to_string()); + let color = c.color.map_or("-".to_string(), |e| e.to_string()); out.extend_from_slice( format!( - "{keyword} {ord} {} {} {} {} {link} {eq}\n", + "{keyword} {ord} {} {} {} {} {link} {eq} {color}\n", c.start, c.in_frame, c.out_frame, c.source ) .as_bytes(), @@ -231,8 +256,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { // The dialects that wrote a source line without its stream field. Reading // one is the whole of what "an old project still opens" means here. let streamless = v1 || first == MAGIC_V2; - // The one that carries equalizer settings... - let v5 = first == MAGIC; + // The one that carries colour grades... + let v6 = first == MAGIC; + // ...the ones that carry equalizer settings... + let v5 = v6 || first == MAGIC_V5; // ...and the ones that number their lanes. Every older one held two. let numbered = v5 || first == MAGIC_V4; if !numbered && !streamless && first != MAGIC_V3 { @@ -252,8 +279,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { } else { vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())] }, - // Nothing before v5 equalizes anything. + // Nothing before v5 equalizes anything, and nothing before v6 grades. eq: Vec::new(), + color: Vec::new(), playhead: 0, }; let mut playhead_seen = false; @@ -324,6 +352,24 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { }; doc.eq.push(EqParams { bands }); } + b"color" if v6 => { + if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { + return Err(format!("line {n}: color after a clip").into()); + } + let f = fields(rest, 1, "color", n)?; + let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect(); + if parts.len() != 4 { + return Err( + format!("line {n}: color wants 4 fields, found {}", parts.len()).into(), + ); + } + doc.color.push(ColorParams { + brightness: float(parts[0], n)?, + contrast: float(parts[1], n)?, + saturation: float(parts[2], n)?, + tint: float(parts[3], n)?, + }); + } // v1: one lane, no placement, no groups. Every clip becomes one // grouped video+audio pair laid where the queue reached, which is // what the file always meant. @@ -337,6 +383,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { source: number(f[2], n)? as usize, link: Some(doc.lanes[0].1.len() as u32), eq: None, + color: None, }, &doc, n, @@ -366,8 +413,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { if numbered && rest.is_empty() { continue; } - // v5 grew the eq field; every older dialect ends at the link. - let f = fields(rest, if v5 { 6 } else { 5 }, "clip", n)?; + // v6 grew the colour field and v5 the eq one; every older + // dialect ends at the link. + let want = 5 + usize::from(v5) + usize::from(v6); + let f = fields(rest, want, "clip", n)?; let clip = check( Clip { start: number(f[0], n)?, @@ -378,20 +427,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { b"-" => None, field => Some(number(field, n)?), }, - eq: match f.get(5).copied() { - None | Some(b"-") => None, - Some(field) => { - let i = number(field, n)?; - if i as usize >= doc.eq.len() || i > u32::from(u16::MAX) { - return Err(format!( - "line {n}: clip names eq {i} of {}", - doc.eq.len() - ) - .into()); - } - Some(i as u16) - } - }, + eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?, + color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?, }, &doc, n, @@ -507,6 +544,26 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result { Ok(clip) } +/// A clip's `` or `` field: `-` (or a dialect that has no such field +/// at all), or a line of a table that is already declared. Refused by the name +/// of what it points at, so the message reads as the file does. +fn table_index( + field: Option<&[u8]>, + len: usize, + what: &str, + line: usize, +) -> crate::Result> { + let field = match field { + None | Some(b"-") => return Ok(None), + Some(field) => field, + }; + let i = number(field, line)?; + if i as usize >= len || i > u32::from(u16::MAX) { + return Err(format!("line {line}: clip names {what} {i} of {len}").into()); + } + Ok(Some(i as u16)) +} + /// One `:::` field of an eq line. fn band(field: &[u8], line: usize) -> crate::Result { let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect(); @@ -609,6 +666,7 @@ mod tests { source, link, eq: None, + color: None, } } @@ -620,7 +678,7 @@ mod tests { lanes: &[(LaneKind, Vec)], playhead: u32, ) -> Vec { - emit(dir, sources, lanes, &[], playhead) + emit(dir, sources, lanes, &[], &[], playhead) } /// Two sources, one under the project's own directory and one not, a clip @@ -658,8 +716,8 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 5\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 -\nvideo 1 30 10 20 1 1 -\naudio 1 0 0 30 0 0 -\n", + "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\ + video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n", "the file under the project directory is written relative to it, \ each with the audio stream it plays" ); @@ -693,8 +751,8 @@ mod tests { let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 5\nplayhead 7\nsource 0 a.mp4\n\ - video 1 0 0 30 0 4 -\naudio 1\nvideo 2 40 0 10 0 - -\naudio 2 0 0 30 0 4 -\n", + "edith 6\nplayhead 7\nsource 0 a.mp4\n\ + video 1 0 0 30 0 4 - -\naudio 1\nvideo 2 40 0 10 0 - - -\naudio 2 0 0 30 0 4 - -\n", "an empty lane is a line of its own; everything else is its clips" ); let back = parse(&bytes, &dir).expect("parse"); @@ -800,15 +858,15 @@ mod tests { }, ], ); - let bytes = emit(&dir, &sources, &lanes, &eq, 0); + let bytes = emit(&dir, &sources, &lanes, &eq, &[], 0); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 5\nplayhead 0\nsource 0 a.mp4\n\ + "edith 6\nplayhead 0\nsource 0 a.mp4\n\ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ eq 16777215.0:-0.1:3.918315e-39:hs\n\ eq\n\ - video 1 0 0 30 0 0 0\nvideo 1 30 10 20 0 - 1\n\ - audio 1 0 0 30 0 0 0\naudio 1 30 0 10 0 - 2\n", + video 1 0 0 30 0 0 0 -\nvideo 1 30 10 20 0 - 1 -\n\ + audio 1 0 0 30 0 0 0 -\naudio 1 30 0 10 0 - 2 -\n", "the table comes before the clips, and a clip names a line of it" ); @@ -834,7 +892,177 @@ mod tests { } } assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own"); - assert_eq!(emit(&dir, &back.sources, &back.lanes, &back.eq, 0), bytes); + assert_eq!( + emit(&dir, &back.sources, &back.lanes, &back.eq, &back.color, 0), + bytes + ); + } + + /// The whole of the v6 bump, the eq test's twin: the clips name a shared + /// colour table, the bytes are the ones documented at the top of this file, + /// and every f32 comes back *bit* for bit, so a re-save is the same file. + #[test] + fn colours_round_trip_bit_exactly_and_are_shared() { + let dir = PathBuf::from("/proj"); + let sources = vec![source("/proj/a.mp4", 0)]; + let color = vec![ + ColorParams { + brightness: 0.1, + contrast: 1.2, + saturation: 0.9, + tint: -0.3, + }, + // The awkward ones again: all 24 mantissa bits, an exponential + // spelling, a subnormal and a negative zero -- and the identity, + // which is a setting like any other. + ColorParams { + brightness: -0.000_000_1, + contrast: 16_777_215.0, + saturation: f32::MIN_POSITIVE / 3.0, + tint: -0.0, + }, + ColorParams::default(), + ]; + // Two clips share entry 0, so it is written once; one clip is ungraded. + let lanes = two( + vec![ + Clip { + color: Some(0), + ..clip(0, 0, 30, 0, Some(0)) + }, + Clip { + color: Some(1), + ..clip(30, 10, 20, 0, None) + }, + ], + vec![ + Clip { + color: Some(0), + ..clip(0, 0, 30, 0, Some(0)) + }, + Clip { + color: Some(2), + ..clip(30, 0, 10, 0, None) + }, + ], + ); + let bytes = emit(&dir, &sources, &lanes, &[], &color, 0); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 6\nplayhead 0\nsource 0 a.mp4\n\ + color 0.1:1.2:0.9:-0.3\n\ + color -1e-7:16777215.0:3.918315e-39:-0.0\n\ + color 0.0:1.0:1.0:0.0\n\ + video 1 0 0 30 0 0 - 0\nvideo 1 30 10 20 0 - - 1\n\ + audio 1 0 0 30 0 0 - 0\naudio 1 30 0 10 0 - - 2\n", + "the table comes before the clips, and a clip names a line of it" + ); + + let back = parse(&bytes, &dir).expect("parse"); + assert_eq!(back.lanes, lanes, "every clip keeps the colour it named"); + for (i, (got, want)) in back.color.iter().zip(&color).enumerate() { + assert_eq!( + ( + got.brightness.to_bits(), + got.contrast.to_bits(), + got.saturation.to_bits(), + got.tint.to_bits() + ), + ( + want.brightness.to_bits(), + want.contrast.to_bits(), + want.saturation.to_bits(), + want.tint.to_bits() + ), + "color {i} came back as other bits" + ); + } + assert_eq!(back.color.len(), 3); + assert_eq!( + emit(&dir, &back.sources, &back.lanes, &back.eq, &back.color, 0), + bytes + ); + } + + /// A v5 file is a v6 one that grades nothing: it loads with its equalizers + /// intact, and re-saving it writes the new magic and a `-` colour field. + #[test] + fn a_v5_file_grades_nothing() { + let dir = PathBuf::from("/proj"); + let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\ + video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n"; + let old = parse(v5, &dir).expect("v5 parses"); + assert!(old.color.is_empty(), "nothing before v6 grades anything"); + assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched"); + assert_eq!(old.lanes[0].1[0].eq, Some(0)); + assert!(old.lanes[0].1[0].color.is_none()); + assert_eq!( + String::from_utf8_lossy(&emit( + &dir, + &old.sources, + &old.lanes, + &old.eq, + &old.color, + old.playhead + )), + "edith 6\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\ + video 1 0 0 30 0 0 0 -\naudio 1 0 0 30 0 0 - -\n" + ); + } + + /// The refusals the colour grammar adds, each naming its line. + #[test] + fn a_malformed_colour_names_its_line() { + let dir = PathBuf::from("/proj"); + let head = "edith 6\nsource 0 a.mp4\n"; + for (file, want) in [ + ( + format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"), + "line 3: color wants 4 fields, found 3", + ), + ( + 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"), + "line 3: color wants 1 fields, found 2", + ), + ( + format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"), + "line 3: \"warm\" is not a number", + ), + // The two values the format cannot write and read back as itself. + ( + format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"), + "line 3: \"inf\" is not a number", + ), + ( + format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"), + "line 3: \"NaN\" is not a number", + ), + ( + format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"), + "line 4: clip names color 1 of 1", + ), + ( + format!("{head}video 1 0 0 5 0 - - 0\n"), + "line 3: clip names color 0 of 0", + ), + // A clip's colour field is not optional in v6, and the table has to + // be declared before the clip that names it. + ( + format!("{head}video 1 0 0 5 0 - -\n"), + "line 3: clip wants 7 fields, found 6", + ), + ( + format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"), + "line 4: color after a clip", + ), + // ...and a colour line in a file that predates them is a corrupt one. + ( + "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(), + "line 3: unknown keyword \"color\"", + ), + ] { + assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want); + } } /// The refusals the eq grammar adds, each naming its line. @@ -910,8 +1138,8 @@ mod tests { assert!(old.eq.is_empty(), "nothing before v5 equalizes anything"); assert_eq!( String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)), - "edith 5\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 -\nvideo 1 30 10 20 1 1 -\naudio 1 0 0 30 0 0 -\n" + "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\ + video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n" ); // An empty lane's line is still the whole of that lane, eq or no eq. let empty = parse( @@ -961,8 +1189,8 @@ mod tests { let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( String::from_utf8_lossy(&v5), - "edith 5\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\ - video 1 0 0 30 0 0 -\nvideo 1 30 10 20 1 1 -\naudio 1 0 0 30 0 0 -\n", + "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\ + video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n", "a re-saved v2 project differs only by its version, the lane \ numbers, the streams it always meant and an equalizer it has none of" ); @@ -990,7 +1218,7 @@ mod tests { assert_eq!(back.playhead, 5); // Saved again it is v5, and that round-trips to the same document. let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v5.starts_with(b"edith 5\n")); + assert!(v5.starts_with(b"edith 6\n")); let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.lanes, back.lanes); // A dialect may not be mixed: lane lines under v1, `clip` under v2. @@ -1079,11 +1307,19 @@ mod tests { path: source, audio_stream: 1, }; - save(&path, &[entry], &two(one.to_vec(), one.to_vec()), &[], 0).expect("save"); + save( + &path, + &[entry], + &two(one.to_vec(), one.to_vec()), + &[], + &[], + 0, + ) + .expect("save"); let bytes = std::fs::read(&path).expect("read back"); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 5\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 - -\naudio 1 0 0 30 0 - -\n" + "edith 6\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 - - -\naudio 1 0 0 30 0 - - -\n" ); // Loading rejoins the *given* directory, so the file is reached by the // way the project was opened -- the same file, through the link, still @@ -1127,10 +1363,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 6\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 7\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 6"); + assert_eq!(err, "line 1: unsupported version 7"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 8be25fc..ab62dbd 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -246,7 +246,7 @@ impl PlaybackSession { } let playhead = doc.playhead; - let project = Project::from_parts(doc.sources, doc.lanes, doc.eq)?; + let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?; let span = project.composite_span_at(0).expect("never empty"); // Last, because it is the one thing here that cannot be taken back: the // feeder thread outlives the `Audio` value (it holds its own clones) and @@ -300,10 +300,10 @@ impl PlaybackSession { /// [`crate::edith`]). Sources no clip plays from are left out, and the /// playhead is saved with it so a reopened project resumes where it stood. pub fn save_project(&self, path: &Path) -> crate::Result<()> { - let (sources, lanes, eq) = self.project.without_orphan_sources(); + let (sources, lanes, eq, color) = self.project.without_orphan_sources(); let playhead = secs_to_frame(self.now(), self.meta.frame_rate) .min(self.project.timeline_frames().saturating_sub(1)); - crate::edith::save(path, &sources, &lanes, &eq, playhead) + crate::edith::save(path, &sources, &lanes, &eq, &color, playhead) } /// The next decoded frame, its `index` rewritten from a source frame to a @@ -538,6 +538,7 @@ impl PlaybackSession { source, link: None, eq: None, + color: None, }; // Which lane a source may land on is decided here and only here, so a // front-end never has to make the same call twice: a file with no @@ -645,6 +646,7 @@ impl PlaybackSession { source, link: None, eq: None, + color: None, }, ); // Same reason as a video import: the running audio worker's segment diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index db9659a..f82e3a4 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -55,9 +55,16 @@ //! index the clip had. Only a *save* prunes the table //! ([`Project::without_orphan_sources`]), for the reason an undone import //! leaves its source entry behind: an index handed out is an index forever. +//! +//! Its colour grade is a third such table ([`Clip::color`], +//! [`Project::set_color`]) and behaves in every way like the equalizer one -- +//! shared by equal settings, inherited by both halves of a split, pruned only at +//! a save. An index rather than the four floats themselves for the same reason: +//! twenty clips graded alike name one entry, and the file writes it once. use std::path::{Path, PathBuf}; +use crate::color::ColorParams; use crate::eq::EqParams; /// A half-open `[in_frame, out_frame)` range of frames of source @@ -83,6 +90,11 @@ pub struct Clip { /// plain assignment. The table is append-only within a session, so an index /// on a clipboard clip or inside an undo snapshot can never dangle. pub eq: Option, + /// Index into the project's colour table + /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that + /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same + /// promises: `Copy`, append-only within a session, never dangling. + pub color: Option, } impl Clip { @@ -214,9 +226,15 @@ impl Span { } /// What a save writes and a load takes back: the sources, every lane in -/// display order with its kind, and the equalizer table their clips index into -/// -- [`Project::without_orphan_sources`] out, [`Project::from_parts`] in. -pub type Parts = (Vec, Vec<(LaneKind, Vec)>, Vec); +/// display order with its kind, and the equalizer and colour tables their clips +/// index into -- [`Project::without_orphan_sources`] out, +/// [`Project::from_parts`] in. +pub type Parts = ( + Vec, + Vec<(LaneKind, Vec)>, + Vec, + Vec, +); /// The edit list plus its undo history. #[derive(Clone, Debug)] @@ -228,6 +246,8 @@ pub struct Project { lanes: Vec, /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into. eq: Vec, + /// The same, for [`Clip::color`]. + color: Vec, /// Snapshots pushed *before* each successful edit; `undo` pops one. The /// whole lane list, so adding a lane undoes as well. history: Vec>, @@ -249,6 +269,7 @@ impl Project { source: 0, link: Some(0), eq: None, + color: None, }; Self { // A file is opened on its first audio stream: nothing has picked @@ -256,6 +277,7 @@ impl Project { sources: vec![Source::new(path, 0)], lanes: LaneData::two_lanes(vec![clip], vec![clip]), eq: Vec::new(), + color: Vec::new(), history: Vec::new(), next_link: 1, } @@ -268,17 +290,22 @@ impl Project { /// [`Project::undo`] is `false` until the first edit of the new session. /// This is the one door untrusted parts come in through, so every invariant /// every other constructor keeps is checked here, by name and in release: - /// every lane empty, an empty clip, a clip naming a source (or an equalizer) - /// that is not there, a clip whose end overflows, a lane that is unsorted or - /// self-overlapping, and the grouping rules of [`Clip::link`] below. + /// every lane empty, an empty clip, a clip naming a source (or an equalizer, + /// or a colour) that is not there, a clip whose end overflows, a lane that is + /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`] + /// below. pub fn from_parts( sources: Vec, lanes: Vec<(LaneKind, Vec)>, eq: Vec, + color: Vec, ) -> crate::Result { if let Some(bad) = eq.iter().position(|p| !finite(p)) { return Err(format!("eq {bad} holds a band that is not a finite number").into()); } + if let Some(bad) = color.iter().position(|p| !color_finite(p)) { + return Err(format!("color {bad} holds a value that is not a finite number").into()); + } if lanes.iter().all(|(_, clips)| clips.is_empty()) { return Err("every lane is empty: that is not a project".into()); } @@ -321,6 +348,15 @@ impl Project { ) .into()); } + if c.color.is_some_and(|i| usize::from(i) >= color.len()) { + return Err(format!( + "{name} clip at {} names color {} of {}", + c.start, + c.color.unwrap_or_default(), + color.len() + ) + .into()); + } } if !sorted_disjoint(&data.clips) { return Err(format!("the {name} lane is out of order or overlaps itself").into()); @@ -342,6 +378,7 @@ impl Project { .collect(), lanes, eq, + color, history: Vec::new(), next_link, }) @@ -453,6 +490,7 @@ impl Project { source, link: Some(self.new_link()), eq: None, + color: None, }; for data in &mut self.lanes { data.clips.push(clip); @@ -469,11 +507,12 @@ impl Project { /// emits the same bytes. /// /// Every lane comes out, in display order and with its kind: that is what a - /// v5 `.edith` holds (empty lanes included) and what [`Project::from_parts`] + /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`] /// takes back. /// - /// The equalizer table is pruned the same way and for the same reason: an - /// undone [`set_eq`](Project::set_eq) leaves settings nothing plays behind, + /// The equalizer and colour tables are pruned the same way and for the same + /// reason: an undone [`set_eq`](Project::set_eq) or + /// [`set_color`](Project::set_color) leaves settings nothing plays behind, /// and this is the one moment they can go -- the indexes that survive it are /// only the ones a clip names. pub fn without_orphan_sources(&self) -> Parts { @@ -481,6 +520,8 @@ impl Project { let mut sources = Vec::new(); let mut moved_eq = vec![None; self.eq.len()]; let mut eq = Vec::new(); + let mut moved_color = vec![None; self.color.len()]; + let mut color = Vec::new(); let mut lanes = self.lanes.clone(); for c in lanes.iter_mut().flat_map(|l| &mut l.clips) { let old = c.source; @@ -503,11 +544,23 @@ impl Project { } }); } + if let Some(old) = c.color.map(usize::from) { + c.color = Some(match moved_color[old] { + Some(new) => new, + None => { + color.push(self.color[old]); + let new = (color.len() - 1) as u16; + moved_color[old] = Some(new); + new + } + }); + } } ( sources, lanes.into_iter().map(|l| (l.kind, l.clips)).collect(), eq, + color, ) } @@ -557,6 +610,46 @@ impl Project { true } + /// How the clip at `idx` of `lane` is graded, or `None` for one that plays + /// ungraded (and for an index that is not there) -- what the renderer and + /// the export ask before they call [`crate::color::apply_yuv`]. + pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> { + self.color + .get(usize::from(self.lane(lane).get(idx)?.color?)) + } + + /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it + /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false` + /// (and no history) for an index that is not there or a value that is not + /// finite, and equal settings share a table entry. + pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option) -> bool { + if idx >= self.lane(lane).len() { + return false; + } + let slot = match params { + None => None, + Some(params) => { + if !color_finite(¶ms) { + return false; + } + Some(match self.color.iter().position(|p| *p == params) { + Some(at) => at as u16, + // ponytail: the 65535th *distinct* grade of one session is + // refused rather than silently aliased, exactly as `set_eq` + // refuses the 65535th curve; same upgrade path. + None if self.color.len() >= usize::from(u16::MAX) => return false, + None => { + self.color.push(params); + (self.color.len() - 1) as u16 + } + }) + } + }; + self.snapshot(); + self.lane_mut(lane).expect("checked above")[idx].color = slot; + true + } + /// Length of the timeline in frames: where the *last* lane runs out. A lane /// that ends early is a trailing gap in that lane, not a shorter timeline. pub fn timeline_frames(&self) -> u32 { @@ -1085,6 +1178,16 @@ fn finite(params: &EqParams) -> bool { .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite()) } +/// The same for a colour grade: [`crate::color`] itself falls back to identity +/// on a non-finite value, but a value that cannot be written and read back as +/// itself has no business reaching the model. +fn color_finite(p: &ColorParams) -> bool { + p.brightness.is_finite() + && p.contrast.is_finite() + && p.saturation.is_finite() + && p.tint.is_finite() +} + fn sorted_disjoint(clips: &[Clip]) -> bool { clips.iter().all(|c| c.out_frame > c.in_frame) && clips.windows(2).all(|w| w[0].end() <= w[1].start) @@ -1222,6 +1325,7 @@ mod tests { source, link: None, eq: None, + color: None, } } @@ -1238,6 +1342,15 @@ mod tests { } } + /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`] + /// for the colour table. + fn grade_at(n: u32) -> ColorParams { + ColorParams { + brightness: f64::from(n) as f32 * 0.05, + ..Default::default() + } + } + /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`]. fn two(video: Vec, audio: Vec) -> Vec<(LaneKind, Vec)> { vec![(LaneKind::Video, video), (LaneKind::Audio, audio)] @@ -1416,6 +1529,7 @@ mod tests { source: 0, link: None, eq: None, + color: None, }; #[test] @@ -1833,9 +1947,10 @@ mod tests { // Import a second file, undo it: source 1 is now an orphan. let mut p = two_sources(); assert!(p.undo()); - let (sources, lanes, eq) = p.without_orphan_sources(); + let (sources, lanes, eq, color) = p.without_orphan_sources(); assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone"); assert!(eq.is_empty(), "and a project with no equalizer writes none"); + assert!(color.is_empty(), "nor a colour it never graded with"); assert_eq!( lanes, two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()), @@ -1848,7 +1963,7 @@ mod tests { assert_eq!(p.import(FILE2, 0), 1); assert_eq!(p.import("/nonexistent/c.mp4", 0), 2); assert!(p.append_clip(2, 4)); - let (sources, lanes, eq) = p.without_orphan_sources(); + let (sources, lanes, eq, color) = p.without_orphan_sources(); assert_eq!( sources, vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)] @@ -1858,7 +1973,7 @@ mod tests { [0, 1] ); // ...and what comes out is loadable, with the same timeline. - let reloaded = Project::from_parts(sources, lanes, eq).expect("from_parts"); + let reloaded = Project::from_parts(sources, lanes, eq, color).expect("from_parts"); assert_eq!(reloaded.timeline_frames(), p.timeline_frames()); assert_eq!(reloaded.sources().len(), 2); } @@ -1928,7 +2043,7 @@ mod tests { assert!(p.undo(), "back to the first setting"); assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1))); - let (_, lanes, eq) = p.without_orphan_sources(); + let (_, lanes, eq, _) = p.without_orphan_sources(); assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written"); assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers"); assert_eq!(lanes[0].1[1].eq, None); @@ -1936,18 +2051,138 @@ mod tests { // One curve on three clips is one entry: settings that are equal share. assert!(p.set_eq(Lane::V1, 1, Some(band_at(1)))); assert!(p.set_eq(Lane::A1, 2, Some(band_at(1)))); - let (_, lanes, eq) = p.without_orphan_sources(); + let (_, lanes, eq, _) = p.without_orphan_sources(); assert_eq!(eq.len(), 1, "equal settings share their entry"); assert_eq!(lanes[1].1[2].eq, Some(0)); reloads(&p, "an equalizer that outlived an undo"); } + /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a + /// grade is the clip's, through every edit that copies a placement. + #[test] + fn a_colour_follows_the_clip_through_split_copy_and_undo() { + let mut p = three(); + assert!( + p.color_of(Lane::V1, 0).is_none(), + "a fresh clip is ungraded" + ); + assert!(p.set_color(Lane::V1, 0, Some(grade_at(2)))); + assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); + assert!( + p.color_of(Lane::A1, 0).is_none(), + "one clip, not the lane below" + ); + assert!( + p.eq_of(Lane::V1, 0).is_none(), + "and a grade is not an equalizer" + ); + + // Cutting a graded clip must not grade half of it: both halves inherit. + assert!(p.split(1)); + assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); + assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2))); + assert!( + p.color_of(Lane::V1, 2).is_none(), + "the clip after it is ungraded" + ); + + // A clipboard copy carries it -- onto another lane, at that. + let copied = p.lane(Lane::V1)[1]; + assert!(p.place(Lane::A1, 20, copied)); + assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2))); + assert!(p.undo()); + assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off"); + + // ...and a change to one is one undo step, in both directions. + assert!(p.set_color(Lane::V1, 0, Some(grade_at(5)))); + assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5))); + assert!(p.undo()); + assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); + assert!( + p.set_color(Lane::V1, 0, None), + "and taking it off is an edit" + ); + assert!(p.color_of(Lane::V1, 0).is_none()); + assert!(p.undo()); + assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); + + // Two refusals, neither of which costs an undo step. + let nan = ColorParams { + contrast: f32::NAN, + ..grade_at(1) + }; + assert!( + !p.set_color(Lane::V1, 99, Some(grade_at(1))), + "no clip there" + ); + assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value"); + assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2))); + assert!(p.undo()); + assert_eq!( + p.lane(Lane::V1).len(), + 3, + "one step back is before the split" + ); + assert!(p.undo()); + assert!( + p.color_of(Lane::V1, 0).is_none(), + "and the next is before the grade: the refusals pushed none" + ); + } + + /// The colour table is append-only within a session, exactly as the eq one + /// is -- and a save is where an undone grade goes. + #[test] + fn an_undone_colour_is_pruned_when_the_project_is_saved() { + let mut p = three(); + assert!(p.set_color(Lane::V1, 0, Some(grade_at(1)))); + assert!(p.set_color(Lane::V1, 0, Some(grade_at(2)))); + assert!(p.undo(), "back to the first grade"); + assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1))); + + let (_, lanes, _, color) = p.without_orphan_sources(); + assert_eq!( + color, + vec![grade_at(1)], + "what nothing plays is not written" + ); + assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers"); + assert_eq!(lanes[0].1[1].color, None); + + // One grade on three clips is one entry: settings that are equal share. + assert!(p.set_color(Lane::V1, 1, Some(grade_at(1)))); + assert!(p.set_color(Lane::A1, 2, Some(grade_at(1)))); + let (_, lanes, _, color) = p.without_orphan_sources(); + assert_eq!(color.len(), 1, "equal grades share their entry"); + assert_eq!(lanes[1].1[2].color, Some(0)); + reloads(&p, "a colour that outlived an undo"); + + // An equalizer and a grade on one clip are two independent tables. + assert!(p.set_eq(Lane::V1, 0, Some(band_at(3)))); + let (_, lanes, eq, color) = p.without_orphan_sources(); + assert_eq!((eq.len(), color.len()), (1, 1)); + assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0))); + } + + /// Not a claim about correctness but about cost: a clip is copied on every + /// paste, every undo snapshot and every lane clone, so its size is worth + /// knowing. The eq index fit the padding a `Copy` clip already had; the + /// colour one did not, and the struct grew a word. + #[test] + fn a_clip_is_still_a_small_copy() { + assert_eq!( + std::mem::size_of::(), + 40, + "Clip changed size -- 32 before the colour index, 40 after" + ); + } + #[test] fn from_parts_has_no_history_and_checks_the_invariants() { - let (sources, lanes, eq) = three().without_orphan_sources(); + let (sources, lanes, eq, color) = three().without_orphan_sources(); let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone()); - let mut p = - Project::from_parts(sources.clone(), lanes.clone(), eq.clone()).expect("valid parts"); + let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone()) + .expect("valid parts"); assert_eq!(p.clips(), three().clips()); assert!(!p.undo(), "a loaded project has nothing to undo"); assert!(p.split(4), "...and is editable from there"); @@ -1955,13 +2190,24 @@ mod tests { // A lane may be empty; every lane may not, and neither may no lane. assert!( - Project::from_parts(sources.clone(), two(video.clone(), Vec::new()), Vec::new()) - .is_ok() + Project::from_parts( + sources.clone(), + two(video.clone(), Vec::new()), + Vec::new(), + Vec::new(), + ) + .is_ok() ); assert!( - Project::from_parts(sources.clone(), two(Vec::new(), Vec::new()), Vec::new()).is_err() + Project::from_parts( + sources.clone(), + two(Vec::new(), Vec::new()), + Vec::new(), + Vec::new(), + ) + .is_err() ); - assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_err()); + assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err()); let bad: [Vec; 5] = [ vec![clip(0, 0, 3, 1)], // source that is not there vec![clip(0, 3, 3, 0)], // empty clip @@ -1971,15 +2217,21 @@ mod tests { ]; for clips in bad { assert!( - Project::from_parts(sources.clone(), two(clips.clone(), Vec::new()), Vec::new()) - .is_err(), + Project::from_parts( + sources.clone(), + two(clips.clone(), Vec::new()), + Vec::new(), + Vec::new(), + ) + .is_err(), "{clips:?}" ); assert!( Project::from_parts( sources.clone(), two(video.clone(), clips.clone()), - Vec::new() + Vec::new(), + Vec::new(), ) .is_err() ); @@ -1992,7 +2244,8 @@ mod tests { (LaneKind::Audio, audio.clone()), (LaneKind::Video, clips), ], - Vec::new() + Vec::new(), + Vec::new(), ) .is_err() ); @@ -2005,17 +2258,76 @@ mod tests { ..video[0] }] }; - assert!(Project::from_parts(sources.clone(), two(eqd(0), Vec::new()), Vec::new()).is_err()); + assert!( + Project::from_parts( + sources.clone(), + two(eqd(0), Vec::new()), + Vec::new(), + Vec::new(), + ) + .is_err() + ); let mut nan = band_at(1); nan.bands[0].freq_hz = f32::NAN; - assert!(Project::from_parts(sources.clone(), two(eqd(0), Vec::new()), vec![nan]).is_err()); - let loaded = - Project::from_parts(sources.clone(), two(eqd(0), Vec::new()), vec![band_at(1)]) - .expect("an eq the table holds"); + assert!( + Project::from_parts( + sources.clone(), + two(eqd(0), Vec::new()), + vec![nan], + Vec::new(), + ) + .is_err() + ); + let loaded = Project::from_parts( + sources.clone(), + two(eqd(0), Vec::new()), + vec![band_at(1)], + Vec::new(), + ) + .expect("an eq the table holds"); assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1))); + // The same two refusals for a colour, at the same door. + let graded = |i: u16| { + vec![Clip { + color: Some(i), + ..video[0] + }] + }; + assert!( + Project::from_parts( + sources.clone(), + two(graded(0), Vec::new()), + Vec::new(), + Vec::new(), + ) + .is_err(), + "a colour index no entry answers" + ); + assert!( + Project::from_parts( + sources.clone(), + two(graded(0), Vec::new()), + Vec::new(), + vec![ColorParams { + tint: f32::NAN, + ..grade_at(1) + }], + ) + .is_err(), + "a value the file format could not have written" + ); + let loaded = Project::from_parts( + sources.clone(), + two(graded(0), Vec::new()), + Vec::new(), + vec![grade_at(1)], + ) + .expect("a colour the table holds"); + assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1))); + // Group ids survive a load, and the next split gets a fresh one. - let mut p = Project::from_parts(sources, lanes, eq).expect("valid parts"); + let mut p = Project::from_parts(sources, lanes, eq, color).expect("valid parts"); assert!(p.split(4)); assert!(p.clips().iter().all(|c| c.link.is_some())); } @@ -2038,11 +2350,12 @@ mod tests { source: 0, link: Some(link), eq: None, + color: None, }; // The door: named errors, one per cause. let err = |video: Vec, audio: Vec| { - Project::from_parts(sources.clone(), two(video, audio), Vec::new()) + Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new()) .expect_err("refused") .to_string() }; @@ -2059,9 +2372,9 @@ mod tests { // A one-sided link is *not* an error: it is what a lift leaves behind. let mut p = Project::single(FILE, 9); assert!(p.lift(Lane::A1, 0)); - let (sources, lanes, eq) = p.clone().without_orphan_sources(); + let (sources, lanes, eq, color) = p.clone().without_orphan_sources(); assert!( - Project::from_parts(sources, lanes, eq).is_ok(), + Project::from_parts(sources, lanes, eq, color).is_ok(), "a lifted lane's project has to load again" ); @@ -2163,7 +2476,7 @@ mod tests { .unwrap_or(&clip(0, 0, 5, 0)); let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 }; let idx = next(4) as usize; - let _ = match next(11) { + let _ = match next(13) { 0 => p.split(frame), 1 => p.regroup(frame), 2 => p.lift(lane, idx), @@ -2177,6 +2490,10 @@ mod tests { // orphans must not come back out of the prune. 8 => p.set_eq(lane, idx, Some(band_at(next(4)))), 9 => p.set_eq(lane, idx, None), + // ...and a colour grade in the same mix, for the same + // reason: it rides on the clip and its orphans must go. + 10 => p.set_color(lane, idx, Some(grade_at(next(4)))), + 11 => p.set_color(lane, idx, None), _ => p.append_clip(0, 1 + next(9)), }; reloads(&p, &format!("seed {seed}, step {step}")); @@ -2188,8 +2505,8 @@ mod tests { /// handed back to the constructor a load goes through -- every lane of them, /// and the reloaded timeline has to be the same lanes in the same order. fn reloads(p: &Project, what: &str) { - let (sources, lanes, eq) = p.clone().without_orphan_sources(); - match Project::from_parts(sources, lanes, eq) { + let (sources, lanes, eq, color) = p.clone().without_orphan_sources(); + match Project::from_parts(sources, lanes, eq, color) { Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes), Ok(back) => { assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed"); @@ -2212,6 +2529,19 @@ mod tests { .collect() }; assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed"); + // The colour table renumbers in the same prune, so the same + // claim: the params a clip names, not the index it names them by. + let colors = |p: &Project| -> Vec>> { + p.lanes() + .into_iter() + .map(|l| { + (0..p.lane(l).len()) + .map(|i| p.color_of(l, i).copied()) + .collect() + }) + .collect() + }; + assert_eq!(colors(&back), colors(p), "{what}: the colours changed"); } } } @@ -2367,6 +2697,7 @@ mod tests { source: 0, link: Some(link), eq: None, + color: None, }; let lanes = vec![ LaneData { @@ -2399,6 +2730,7 @@ mod tests { source: 0, link: Some(link), eq: None, + color: None, }; // V1, A1, V2, A2 -- one take over [0, 4) on all four. let kinds = [ @@ -2446,7 +2778,7 @@ mod tests { let v2 = p.add_lane(LaneKind::Video); assert!(p.place(v2, 4, clip(0, 20, 32, 0))); let a2 = p.add_lane(LaneKind::Audio); - let (sources, lanes, eq) = p.without_orphan_sources(); + let (sources, lanes, eq, color) = p.without_orphan_sources(); assert_eq!( lanes.iter().map(|(k, _)| *k).collect::>(), [ @@ -2460,7 +2792,7 @@ mod tests { assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written"); assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane"); // ...and all four load again as the same four. - let back = Project::from_parts(sources, lanes, eq).expect("four lanes load"); + let back = Project::from_parts(sources, lanes, eq, color).expect("four lanes load"); assert_eq!(back.lanes(), p.lanes()); assert_eq!(back.lane(a2), p.lane(a2)); @@ -2542,7 +2874,7 @@ mod tests { (LaneKind::Video, vec![clip(10, 5, 15, 1)]), (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), ]; - let p = Project::from_parts(sources, lanes, vec![]).expect("valid parts"); + let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts"); assert_eq!( p.composite_spans_from(0), vec![ @@ -2583,7 +2915,7 @@ mod tests { (LaneKind::Video, vec![clip(10, 0, 10, 1)]), (LaneKind::Audio, vec![clip(0, 0, 30, 0)]), ]; - let p = Project::from_parts(sources, holed, vec![]).expect("valid parts"); + let p = Project::from_parts(sources, holed, vec![], vec![]).expect("valid parts"); assert_eq!( p.composite_spans_from(0), vec![ @@ -2627,7 +2959,7 @@ mod tests { (LaneKind::Audio, vec![clip(15, 0, 15, 1)]), (LaneKind::Audio, Vec::new()), ]; - let p = Project::from_parts(sources, lanes, vec![]).expect("valid parts"); + let p = Project::from_parts(sources, lanes, vec![], vec![]).expect("valid parts"); let lists = p.audio_segments_from(0, FPS); assert_eq!(lists.len(), 2, "the empty lane is not mixed in"); assert_eq!(lists[0], p.segments_from(0, FPS), "A1 is unchanged"); @@ -2643,6 +2975,7 @@ mod tests { (LaneKind::Audio, Vec::new()), ], vec![], + vec![], ) .expect("valid parts"); assert_eq!(p.audio_segments_from(0, FPS), vec![vec![(None, 0.0, 1.0)]]); diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 6e7bd5c..9e8ab74 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -65,6 +65,7 @@ fn mixed_project() -> Project { source, link: None, eq: None, + color: None, }; Project::from_parts( vec![ @@ -84,11 +85,13 @@ fn mixed_project() -> Project { source: 0, link: None, eq: None, + color: None, }], ), (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]), ], Vec::new(), + Vec::new(), ) .expect("a two-source project with a hole in the audio lane") } diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs index 5011ac9..380dd96 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -192,6 +192,7 @@ fn exports_the_audio_stream_the_timeline_plays() { source: 0, link: Some(0), eq: None, + color: None, }; // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz // stereo. A project may only hold streams that agree, so this timeline is @@ -206,6 +207,7 @@ fn exports_the_audio_stream_the_timeline_plays() { (engine::project::LaneKind::Audio, vec![whole]), ], Vec::new(), + Vec::new(), ) .expect("a one-source project on stream 1"); let out = out_path("stream1"); diff --git a/crates/engine/tests/lanes.rs b/crates/engine/tests/lanes.rs index 509ac38..5eeb0ea 100644 --- a/crates/engine/tests/lanes.rs +++ b/crates/engine/tests/lanes.rs @@ -236,6 +236,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() { source: 0, link: None, eq: None, + color: None, }; let project = Project::from_parts( vec![Source::new(&source, 0)], @@ -245,6 +246,7 @@ fn the_mp4_copy_follows_the_lane_that_holds_the_sound() { (LaneKind::Audio, vec![clip]), ], vec![], + vec![], ) .expect("valid parts"); assert_eq!( @@ -293,12 +295,13 @@ fn two_audio_lanes_are_summed() { source: 0, link: None, eq: None, + color: None, }; let a2 = project.add_lane(LaneKind::Audio); assert!(project.place(a2, TOP_IN, doubled), "place the second lane"); - let (sources, lanes, eq) = project.without_orphan_sources(); + let (sources, lanes, eq, color) = project.without_orphan_sources(); assert_eq!(lanes.len(), 3, "V1, A1 and the new A2"); - let project = Project::from_parts(sources, lanes, eq).expect("valid parts"); + let project = Project::from_parts(sources, lanes, eq, color).expect("valid parts"); let (meta, _) = engine::demux::Demuxer::open(&asset("test_av.mp4")).unwrap(); let wav = |name: &str, project: Project| { diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 7e1b26a..42a611f 100644 --- a/crates/engine/tests/saveload.rs +++ b/crates/engine/tests/saveload.rs @@ -126,9 +126,9 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec, f64 /// The version-1 promise: a file written before the lanes existed still opens, /// as one grouped video+audio pair per clip laid end to end, and saving it -/// again writes version 5 -- which reopens as the same timeline. +/// again writes version 6 -- which reopens as the same timeline. #[test] -fn a_version_1_project_loads_fully_grouped_and_saves_as_version_5() { +fn a_version_1_project_loads_fully_grouped_and_saves_as_version_6() { let dir = scratch("v1"); copy_in(&dir, "test_av.mp4"); let path = dir.join("old.edith"); @@ -156,11 +156,11 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_5() { "playhead kept" ); - // Saved again it is v5, and v5 round-trips to the same timeline. + // Saved again it is v6, and v6 round-trips to the same timeline. let v2 = dir.join("new.edith"); loaded.save_project(&v2).expect("save"); let text = std::fs::read_to_string(&v2).expect("read back"); - assert!(text.starts_with("edith 5\n"), "{text}"); + assert!(text.starts_with("edith 6\n"), "{text}"); assert_eq!( text.lines().filter(|l| l.starts_with("video ")).count(), 2, @@ -237,21 +237,23 @@ fn a_version_4_project_holds_more_than_two_lanes() { ); assert_eq!(loaded.timeline_duration(), 60.0 / loaded.meta().frame_rate); - // ...and saving it writes the v5 twin of what it read: the lane list, its - // order and the empty lane all survive, each clip now saying it plays flat. + // ...and saving it writes the v6 twin of what it read: the lane list, its + // order and the empty lane all survive, each clip now saying it plays flat + // and ungraded. let again = dir.join("again.edith"); loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - "edith 5\nplayhead 0\nsource 0 test_av.mp4\n\ - video 1 0 0 30 0 3 -\naudio 1\nvideo 2 40 0 20 0 - -\naudio 2 0 0 30 0 3 -\n", - "a four-lane project is written as it was read, one version on" + "edith 6\nplayhead 0\nsource 0 test_av.mp4\n\ + video 1 0 0 30 0 3 - -\naudio 1\nvideo 2 40 0 20 0 - - -\naudio 2 0 0 30 0 3 - -\n", + "a four-lane project is written as it was read, two versions on" ); } /// What version 5 is for: a clip carries equalizer settings, the file names /// them once for however many clips share them, and the whole thing survives -/// the engine's own door -- open, save, byte for byte the file it read. +/// the engine's own door -- open, save, every curve and index of it intact one +/// version on. #[test] fn a_version_5_project_carries_per_clip_equalizers() { let dir = scratch("v5_eq"); @@ -271,11 +273,44 @@ fn a_version_5_project_carries_per_clip_equalizers() { loaded.save_project(&again).expect("save"); assert_eq!( std::fs::read_to_string(&again).expect("read back"), - text, + "edith 6\nplayhead 0\nsource 0 test_av.mp4\n\ + eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\ + eq 12000.0:6.25:0.5:hs\n\ + video 1 0 0 30 0 - 0 -\nvideo 1 30 30 60 0 - 1 -\n\ + audio 1 0 0 30 0 - 0 -\naudio 1 30 30 60 0 - - -\n", "the equalizer table and every clip's index survive a round trip" ); } +/// What version 6 is for, the same claim one version on: a clip carries a +/// colour grade beside its equalizer, the file names each once for however many +/// clips share it, and the whole thing comes back out byte for byte. +#[test] +fn a_version_6_project_carries_per_clip_colours() { + let dir = scratch("v6_color"); + copy_in(&dir, "test_av.mp4"); + let path = dir.join("color.edith"); + // Two clips on one grade, one on another, one ungraded -- and an equalizer + // on a clip that is graded too, so the two tables are seen not to collide. + let text = "edith 6\nplayhead 0\nsource 0 test_av.mp4\n\ + eq 80.0:-3.0:0.707:ls\n\ + color 0.1:1.2:0.9:-0.3\n\ + color -0.25:1.0:0.0:0.5\n\ + video 1 0 0 30 0 - 0 0\nvideo 1 30 30 60 0 - - 1\n\ + audio 1 0 0 30 0 - - 0\naudio 1 30 30 60 0 - - -\n"; + std::fs::write(&path, text).expect("write a v6 file"); + + let loaded = PlaybackSession::open_project(&path).expect("a v6 project opens"); + assert_eq!(loaded.lane_clips(engine::project::Lane::V1).len(), 2); + let again = dir.join("again.edith"); + loaded.save_project(&again).expect("save"); + assert_eq!( + std::fs::read_to_string(&again).expect("read back"), + text, + "the colour table and every clip's index survive a round trip" + ); +} + #[test] fn a_saved_project_reopens_as_the_same_timeline() { let dir = scratch("round_trip"); @@ -487,7 +522,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() { for (text, want) in [ ( - "edith 6\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - -\n", + "edith 7\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - -\n", "line 1", ), // An eq index the table does not hold, and a band shape there is none.