forge
Explore
Log in

Don't you dare go Hollow

Per-clip color persists in .edith v6

Browse files at this commit

0530fc9c418ded1877b48bbfbee9a2efce88aa6bAhmet Kaan GümüşParent: 6a64d06
  • feat
    • per-clip color persists in .edith v6
Show full message
✨ feat(engine): per-clip color persists in .edith v6

A clip names a colour grade the way it names an equalizer: an index into an append-only Project table, deduped on set, pruned at save, inherited by both halves of a split and carried by copy, paste and undo.

The file format grows a color <b>:<c>:<s>:<t> line and a 7th clip field; v5..v1 still load and every one of them re-saves as v6. Clip grew from 32 to 40 bytes -- the eq index fit the padding hole, the colour one did not.
crates/app/src/main.rsmodified+2 -0
@@ -3460,6 +3460,7 @@ mod tests {
34603460 source,
34613461 link: None,
34623462 eq: None,
3463+ color: None,
34633464 }
34643465 }
34653466
@@ -3650,6 +3651,7 @@ mod tests {
36503651 source: 0,
36513652 link: None,
36523653 eq: None,
3654+ color: None,
36533655 };
36543656 assert_eq!(clip.end(), 90);
36553657 // Cut splits from inside only: neither edge has anything to split off.
crates/engine/src/edith.rsmodified+299 -63
@@ -1,14 +1,15 @@
11 //! The project file: a line of text per thing, and nothing else.
22 //!
33 //! ```text
4-//! edith 5
4+//! edith 6
55 //! playhead 90
66 //! source 0 test_av.mp4
77 //! source 1 /elsewhere/test_av2.mp4
88 //! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
9-//! video 1 0 0 120 0 0 0
10-//! audio 1 0 0 120 0 0 0
11-//! video 2 120 0 120 1 - -
9+//! color 0.1:1.2:0.9:-0.3
10+//! video 1 0 0 120 0 0 0 0
11+//! audio 1 0 0 120 0 0 0 -
12+//! video 2 120 0 120 1 - - -
1213 //! audio 2
1314 //! ```
1415 //!
@@ -26,29 +27,35 @@
2627 //! setting like any other. The numbers are printed to round trip bit-exactly;
2728 //! anything not finite is refused, here and at [`crate::Project::set_eq`].
2829 //!
29-//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>`:
30-//! which lane the clip is on -- its kind and its 1-based number among the lanes
31-//! of that kind, the [`crate::project::Lane::label`] a header column shows --
32-//! then where the clip sits on the timeline, the half-open source range it
33-//! plays, the file it plays from, its group id, and the eq line it plays
34-//! through (`-` for neither). Timeline placement is explicit, so a *gap* is
35-//! simply a stretch no line covers -- there is nothing to write for one, and
36-//! nothing that can disagree about its length.
30+//! A colour line is `color <brightness>:<contrast>:<saturation>:<tint>`
31+//! ([`crate::color::ColorParams`]), named by position exactly as an eq line is
32+//! -- the first colour line is color 0 -- printed and refused by the same rules.
33+//!
34+//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link> <eq>
35+//! <color>`: which lane the clip is on -- its kind and its 1-based number among
36+//! the lanes of that kind, the [`crate::project::Lane::label`] a header column
37+//! shows -- then where the clip sits on the timeline, the half-open source range
38+//! it plays, the file it plays from, its group id, the eq line it plays through
39+//! and the colour line it is graded by (`-` for none of them). Timeline
40+//! placement is explicit, so a *gap* is simply a stretch no line covers -- there
41+//! is nothing to write for one, and nothing that can disagree about its length.
3742 //!
3843 //! A lane is declared by the clips on it, in the order the lanes are displayed
3944 //! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
4045 //! is the only way an empty lane could still be there on the way back. A lane
4146 //! number may not skip one of its kind.
4247 //!
43-//! **Version 4** was this without the eq lines and without the clip's eq field.
44-//! **Version 3** was that without the lane number, and held one video lane and
45-//! one audio lane, no more. **Version 2** wrote `source <path>` as well, which
46-//! is this file's stream 0 -- one per file, whichever audio track came first.
47-//! **Version 1** wrote that and one lane, queued end to end: `clip <in> <out>
48-//! <source>`. All four still load -- a v1 file's clips are laid out
48+//! **Version 5** was this without the colour lines and without the clip's colour
49+//! field. **Version 4** was that without the eq lines and without the clip's eq
50+//! field. **Version 3** was that without the lane number, and held one video
51+//! lane and one audio lane, no more. **Version 2** wrote `source <path>` as
52+//! well, which is this file's stream 0 -- one per file, whichever audio track
53+//! came first. **Version 1** wrote that and one lane, queued end to end: `clip
54+//! <in> <out> <source>`. All five still load -- a v1 file's clips are laid out
4955 //! cumulatively and copied onto both lanes as one group each, which is exactly
50-//! what a v1 timeline meant, and an older file simply equalizes nothing -- and
51-//! saving any of them writes v5. An older reader refuses a newer file by name.
56+//! what a v1 timeline meant, and an older file simply equalizes and grades
57+//! nothing -- and saving any of them writes v6. An older reader refuses a newer
58+//! file by name.
5259 //!
5360 //! Text because an edit list is a few integers and a path, and a path is
5461 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -74,12 +81,14 @@ use std::io::Write;
7481 use std::os::unix::ffi::{OsStrExt, OsStringExt};
7582 use std::path::{Path, PathBuf};
7683
84+use crate::color::ColorParams;
7785 use crate::eq::{Band, BandKind, EqParams};
7886 use crate::project::{Clip, Lane, LaneKind, Source};
7987
8088 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
8189 /// docs for what those dialects looked like.
82-const MAGIC: &[u8] = b"edith 5";
90+const MAGIC: &[u8] = b"edith 6";
91+const MAGIC_V5: &[u8] = b"edith 5";
8392 const MAGIC_V4: &[u8] = b"edith 4";
8493 const MAGIC_V3: &[u8] = b"edith 3";
8594 const MAGIC_V2: &[u8] = b"edith 2";
@@ -99,16 +108,20 @@ pub struct Document {
99108 /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for
100109 /// every dialect before v5.
101110 pub eq: Vec<EqParams>,
111+ /// The colour table [`Clip::color`] indexes into, in file order. Empty for
112+ /// every dialect before v6.
113+ pub color: Vec<ColorParams>,
102114 pub playhead: u32,
103115 }
104116
105-/// Writes the project to `path`, atomically. `sources` and `eq` should already
106-/// be orphan-free ([`crate::Project::without_orphan_sources`]).
117+/// Writes the project to `path`, atomically. `sources`, `eq` and `color` should
118+/// already be orphan-free ([`crate::Project::without_orphan_sources`]).
107119 pub fn save(
108120 path: &Path,
109121 sources: &[Source],
110122 lanes: &[(LaneKind, Vec<Clip>)],
111123 eq: &[EqParams],
124+ color: &[ColorParams],
112125 playhead: u32,
113126 ) -> crate::Result<()> {
114127 let dir = project_dir(path);
@@ -121,7 +134,7 @@ pub fn save(
121134 // the second one puts the name itself there.
122135 let result = std::fs::File::create(&part)
123136 .and_then(|mut f| {
124- f.write_all(&emit(&dir, sources, lanes, eq, playhead))?;
137+ f.write_all(&emit(&dir, sources, lanes, eq, color, playhead))?;
125138 f.sync_all()
126139 })
127140 .and_then(|()| std::fs::rename(&part, path))
@@ -156,6 +169,7 @@ fn emit(
156169 sources: &[Source],
157170 lanes: &[(LaneKind, Vec<Clip>)],
158171 eq: &[EqParams],
172+ color: &[ColorParams],
159173 playhead: u32,
160174 ) -> Vec<u8> {
161175 let mut out = Vec::new();
@@ -186,6 +200,16 @@ fn emit(
186200 }
187201 out.push(b'\n');
188202 }
203+ // ...and the colour table, for the same reason and by the same rules.
204+ for p in color {
205+ out.extend_from_slice(
206+ format!(
207+ "color {:?}:{:?}:{:?}:{:?}\n",
208+ p.brightness, p.contrast, p.saturation, p.tint
209+ )
210+ .as_bytes(),
211+ );
212+ }
189213 // Lane by lane rather than interleaved by time: a lane reads as a list, the
190214 // parser gets its sortedness check for free from the order it is in, and
191215 // the lanes come back out in the order they are displayed in.
@@ -209,9 +233,10 @@ fn emit(
209233 for c in clips {
210234 let link = c.link.map_or("-".to_string(), |l| l.to_string());
211235 let eq = c.eq.map_or("-".to_string(), |e| e.to_string());
236+ let color = c.color.map_or("-".to_string(), |e| e.to_string());
212237 out.extend_from_slice(
213238 format!(
214- "{keyword} {ord} {} {} {} {} {link} {eq}\n",
239+ "{keyword} {ord} {} {} {} {} {link} {eq} {color}\n",
215240 c.start, c.in_frame, c.out_frame, c.source
216241 )
217242 .as_bytes(),
@@ -231,8 +256,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
231256 // The dialects that wrote a source line without its stream field. Reading
232257 // one is the whole of what "an old project still opens" means here.
233258 let streamless = v1 || first == MAGIC_V2;
234- // The one that carries equalizer settings...
235- let v5 = first == MAGIC;
259+ // The one that carries colour grades...
260+ let v6 = first == MAGIC;
261+ // ...the ones that carry equalizer settings...
262+ let v5 = v6 || first == MAGIC_V5;
236263 // ...and the ones that number their lanes. Every older one held two.
237264 let numbered = v5 || first == MAGIC_V4;
238265 if !numbered && !streamless && first != MAGIC_V3 {
@@ -252,8 +279,9 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
252279 } else {
253280 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
254281 },
255- // Nothing before v5 equalizes anything.
282+ // Nothing before v5 equalizes anything, and nothing before v6 grades.
256283 eq: Vec::new(),
284+ color: Vec::new(),
257285 playhead: 0,
258286 };
259287 let mut playhead_seen = false;
@@ -324,6 +352,24 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
324352 };
325353 doc.eq.push(EqParams { bands });
326354 }
355+ b"color" if v6 => {
356+ if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
357+ return Err(format!("line {n}: color after a clip").into());
358+ }
359+ let f = fields(rest, 1, "color", n)?;
360+ let parts: Vec<&[u8]> = f[0].split(|&b| b == b':').collect();
361+ if parts.len() != 4 {
362+ return Err(
363+ format!("line {n}: color wants 4 fields, found {}", parts.len()).into(),
364+ );
365+ }
366+ doc.color.push(ColorParams {
367+ brightness: float(parts[0], n)?,
368+ contrast: float(parts[1], n)?,
369+ saturation: float(parts[2], n)?,
370+ tint: float(parts[3], n)?,
371+ });
372+ }
327373 // v1: one lane, no placement, no groups. Every clip becomes one
328374 // grouped video+audio pair laid where the queue reached, which is
329375 // what the file always meant.
@@ -337,6 +383,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
337383 source: number(f[2], n)? as usize,
338384 link: Some(doc.lanes[0].1.len() as u32),
339385 eq: None,
386+ color: None,
340387 },
341388 &doc,
342389 n,
@@ -366,8 +413,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
366413 if numbered && rest.is_empty() {
367414 continue;
368415 }
369- // v5 grew the eq field; every older dialect ends at the link.
370- let f = fields(rest, if v5 { 6 } else { 5 }, "clip", n)?;
416+ // v6 grew the colour field and v5 the eq one; every older
417+ // dialect ends at the link.
418+ let want = 5 + usize::from(v5) + usize::from(v6);
419+ let f = fields(rest, want, "clip", n)?;
371420 let clip = check(
372421 Clip {
373422 start: number(f[0], n)?,
@@ -378,20 +427,8 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
378427 b"-" => None,
379428 field => Some(number(field, n)?),
380429 },
381- eq: match f.get(5).copied() {
382- None | Some(b"-") => None,
383- Some(field) => {
384- let i = number(field, n)?;
385- if i as usize >= doc.eq.len() || i > u32::from(u16::MAX) {
386- return Err(format!(
387- "line {n}: clip names eq {i} of {}",
388- doc.eq.len()
389- )
390- .into());
391- }
392- Some(i as u16)
393- }
394- },
430+ eq: table_index(f.get(5).copied(), doc.eq.len(), "eq", n)?,
431+ color: table_index(f.get(6).copied(), doc.color.len(), "color", n)?,
395432 },
396433 &doc,
397434 n,
@@ -507,6 +544,26 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
507544 Ok(clip)
508545 }
509546
547+/// A clip's `<eq>` or `<color>` field: `-` (or a dialect that has no such field
548+/// at all), or a line of a table that is already declared. Refused by the name
549+/// of what it points at, so the message reads as the file does.
550+fn table_index(
551+ field: Option<&[u8]>,
552+ len: usize,
553+ what: &str,
554+ line: usize,
555+) -> crate::Result<Option<u16>> {
556+ let field = match field {
557+ None | Some(b"-") => return Ok(None),
558+ Some(field) => field,
559+ };
560+ let i = number(field, line)?;
561+ if i as usize >= len || i > u32::from(u16::MAX) {
562+ return Err(format!("line {line}: clip names {what} {i} of {len}").into());
563+ }
564+ Ok(Some(i as u16))
565+}
566+
510567 /// One `<frequency>:<gain>:<Q>:<shape>` field of an eq line.
511568 fn band(field: &[u8], line: usize) -> crate::Result<Band> {
512569 let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
@@ -609,6 +666,7 @@ mod tests {
609666 source,
610667 link,
611668 eq: None,
669+ color: None,
612670 }
613671 }
614672
@@ -620,7 +678,7 @@ mod tests {
620678 lanes: &[(LaneKind, Vec<Clip>)],
621679 playhead: u32,
622680 ) -> Vec<u8> {
623- emit(dir, sources, lanes, &[], playhead)
681+ emit(dir, sources, lanes, &[], &[], playhead)
624682 }
625683
626684 /// Two sources, one under the project's own directory and one not, a clip
@@ -658,8 +716,8 @@ mod tests {
658716 let bytes = flat(&dir, &sources, &lanes, 12);
659717 assert_eq!(
660718 String::from_utf8_lossy(&bytes),
661- "edith 5\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
662- video 1 0 0 30 0 0 -\nvideo 1 30 10 20 1 1 -\naudio 1 0 0 30 0 0 -\n",
719+ "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
720+ video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n",
663721 "the file under the project directory is written relative to it, \
664722 each with the audio stream it plays"
665723 );
@@ -693,8 +751,8 @@ mod tests {
693751 let bytes = flat(&dir, &sources, &lanes, 7);
694752 assert_eq!(
695753 String::from_utf8_lossy(&bytes),
696- "edith 5\nplayhead 7\nsource 0 a.mp4\n\
697- video 1 0 0 30 0 4 -\naudio 1\nvideo 2 40 0 10 0 - -\naudio 2 0 0 30 0 4 -\n",
754+ "edith 6\nplayhead 7\nsource 0 a.mp4\n\
755+ video 1 0 0 30 0 4 - -\naudio 1\nvideo 2 40 0 10 0 - - -\naudio 2 0 0 30 0 4 - -\n",
698756 "an empty lane is a line of its own; everything else is its clips"
699757 );
700758 let back = parse(&bytes, &dir).expect("parse");
@@ -800,15 +858,15 @@ mod tests {
800858 },
801859 ],
802860 );
803- let bytes = emit(&dir, &sources, &lanes, &eq, 0);
861+ let bytes = emit(&dir, &sources, &lanes, &eq, &[], 0);
804862 assert_eq!(
805863 String::from_utf8_lossy(&bytes),
806- "edith 5\nplayhead 0\nsource 0 a.mp4\n\
864+ "edith 6\nplayhead 0\nsource 0 a.mp4\n\
807865 eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
808866 eq 16777215.0:-0.1:3.918315e-39:hs\n\
809867 eq\n\
810- video 1 0 0 30 0 0 0\nvideo 1 30 10 20 0 - 1\n\
811- audio 1 0 0 30 0 0 0\naudio 1 30 0 10 0 - 2\n",
868+ video 1 0 0 30 0 0 0 -\nvideo 1 30 10 20 0 - 1 -\n\
869+ audio 1 0 0 30 0 0 0 -\naudio 1 30 0 10 0 - 2 -\n",
812870 "the table comes before the clips, and a clip names a line of it"
813871 );
814872
@@ -834,7 +892,177 @@ mod tests {
834892 }
835893 }
836894 assert_eq!(back.eq.len(), 3, "the empty cascade is an entry of its own");
837- assert_eq!(emit(&dir, &back.sources, &back.lanes, &back.eq, 0), bytes);
895+ assert_eq!(
896+ emit(&dir, &back.sources, &back.lanes, &back.eq, &back.color, 0),
897+ bytes
898+ );
899+ }
900+
901+ /// The whole of the v6 bump, the eq test's twin: the clips name a shared
902+ /// colour table, the bytes are the ones documented at the top of this file,
903+ /// and every f32 comes back *bit* for bit, so a re-save is the same file.
904+ #[test]
905+ fn colours_round_trip_bit_exactly_and_are_shared() {
906+ let dir = PathBuf::from("/proj");
907+ let sources = vec![source("/proj/a.mp4", 0)];
908+ let color = vec![
909+ ColorParams {
910+ brightness: 0.1,
911+ contrast: 1.2,
912+ saturation: 0.9,
913+ tint: -0.3,
914+ },
915+ // The awkward ones again: all 24 mantissa bits, an exponential
916+ // spelling, a subnormal and a negative zero -- and the identity,
917+ // which is a setting like any other.
918+ ColorParams {
919+ brightness: -0.000_000_1,
920+ contrast: 16_777_215.0,
921+ saturation: f32::MIN_POSITIVE / 3.0,
922+ tint: -0.0,
923+ },
924+ ColorParams::default(),
925+ ];
926+ // Two clips share entry 0, so it is written once; one clip is ungraded.
927+ let lanes = two(
928+ vec![
929+ Clip {
930+ color: Some(0),
931+ ..clip(0, 0, 30, 0, Some(0))
932+ },
933+ Clip {
934+ color: Some(1),
935+ ..clip(30, 10, 20, 0, None)
936+ },
937+ ],
938+ vec![
939+ Clip {
940+ color: Some(0),
941+ ..clip(0, 0, 30, 0, Some(0))
942+ },
943+ Clip {
944+ color: Some(2),
945+ ..clip(30, 0, 10, 0, None)
946+ },
947+ ],
948+ );
949+ let bytes = emit(&dir, &sources, &lanes, &[], &color, 0);
950+ assert_eq!(
951+ String::from_utf8_lossy(&bytes),
952+ "edith 6\nplayhead 0\nsource 0 a.mp4\n\
953+ color 0.1:1.2:0.9:-0.3\n\
954+ color -1e-7:16777215.0:3.918315e-39:-0.0\n\
955+ color 0.0:1.0:1.0:0.0\n\
956+ video 1 0 0 30 0 0 - 0\nvideo 1 30 10 20 0 - - 1\n\
957+ audio 1 0 0 30 0 0 - 0\naudio 1 30 0 10 0 - - 2\n",
958+ "the table comes before the clips, and a clip names a line of it"
959+ );
960+
961+ let back = parse(&bytes, &dir).expect("parse");
962+ assert_eq!(back.lanes, lanes, "every clip keeps the colour it named");
963+ for (i, (got, want)) in back.color.iter().zip(&color).enumerate() {
964+ assert_eq!(
965+ (
966+ got.brightness.to_bits(),
967+ got.contrast.to_bits(),
968+ got.saturation.to_bits(),
969+ got.tint.to_bits()
970+ ),
971+ (
972+ want.brightness.to_bits(),
973+ want.contrast.to_bits(),
974+ want.saturation.to_bits(),
975+ want.tint.to_bits()
976+ ),
977+ "color {i} came back as other bits"
978+ );
979+ }
980+ assert_eq!(back.color.len(), 3);
981+ assert_eq!(
982+ emit(&dir, &back.sources, &back.lanes, &back.eq, &back.color, 0),
983+ bytes
984+ );
985+ }
986+
987+ /// A v5 file is a v6 one that grades nothing: it loads with its equalizers
988+ /// intact, and re-saving it writes the new magic and a `-` colour field.
989+ #[test]
990+ fn a_v5_file_grades_nothing() {
991+ let dir = PathBuf::from("/proj");
992+ let v5 = b"edith 5\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
993+ video 1 0 0 30 0 0 0\naudio 1 0 0 30 0 0 -\n";
994+ let old = parse(v5, &dir).expect("v5 parses");
995+ assert!(old.color.is_empty(), "nothing before v6 grades anything");
996+ assert_eq!(old.eq.len(), 1, "...and its equalizers are untouched");
997+ assert_eq!(old.lanes[0].1[0].eq, Some(0));
998+ assert!(old.lanes[0].1[0].color.is_none());
999+ assert_eq!(
1000+ String::from_utf8_lossy(&emit(
1001+ &dir,
1002+ &old.sources,
1003+ &old.lanes,
1004+ &old.eq,
1005+ &old.color,
1006+ old.playhead
1007+ )),
1008+ "edith 6\nplayhead 3\nsource 0 a.mp4\neq 80.0:-3.0:0.707:ls\n\
1009+ video 1 0 0 30 0 0 0 -\naudio 1 0 0 30 0 0 - -\n"
1010+ );
1011+ }
1012+
1013+ /// The refusals the colour grammar adds, each naming its line.
1014+ #[test]
1015+ fn a_malformed_colour_names_its_line() {
1016+ let dir = PathBuf::from("/proj");
1017+ let head = "edith 6\nsource 0 a.mp4\n";
1018+ for (file, want) in [
1019+ (
1020+ format!("{head}color 0.0:1.0:1.0\nvideo 1 0 0 5 0 - - 0\n"),
1021+ "line 3: color wants 4 fields, found 3",
1022+ ),
1023+ (
1024+ 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"),
1025+ "line 3: color wants 1 fields, found 2",
1026+ ),
1027+ (
1028+ format!("{head}color 0.0:warm:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1029+ "line 3: \"warm\" is not a number",
1030+ ),
1031+ // The two values the format cannot write and read back as itself.
1032+ (
1033+ format!("{head}color inf:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 0\n"),
1034+ "line 3: \"inf\" is not a number",
1035+ ),
1036+ (
1037+ format!("{head}color 0.0:1.0:1.0:NaN\nvideo 1 0 0 5 0 - - 0\n"),
1038+ "line 3: \"NaN\" is not a number",
1039+ ),
1040+ (
1041+ format!("{head}color 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - - 1\n"),
1042+ "line 4: clip names color 1 of 1",
1043+ ),
1044+ (
1045+ format!("{head}video 1 0 0 5 0 - - 0\n"),
1046+ "line 3: clip names color 0 of 0",
1047+ ),
1048+ // A clip's colour field is not optional in v6, and the table has to
1049+ // be declared before the clip that names it.
1050+ (
1051+ format!("{head}video 1 0 0 5 0 - -\n"),
1052+ "line 3: clip wants 7 fields, found 6",
1053+ ),
1054+ (
1055+ format!("{head}video 1 0 0 5 0 - - -\ncolor 0.0:1.0:1.0:0.0\n"),
1056+ "line 4: color after a clip",
1057+ ),
1058+ // ...and a colour line in a file that predates them is a corrupt one.
1059+ (
1060+ "edith 5\nsource 0 a.mp4\ncolor 0.0:1.0:1.0:0.0\nvideo 1 0 0 5 0 - -\n".to_string(),
1061+ "line 3: unknown keyword \"color\"",
1062+ ),
1063+ ] {
1064+ assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
1065+ }
8381066 }
8391067
8401068 /// The refusals the eq grammar adds, each naming its line.
@@ -910,8 +1138,8 @@ mod tests {
9101138 assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
9111139 assert_eq!(
9121140 String::from_utf8_lossy(&flat(&dir, &old.sources, &old.lanes, old.playhead)),
913- "edith 5\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
914- video 1 0 0 30 0 0 -\nvideo 1 30 10 20 1 1 -\naudio 1 0 0 30 0 0 -\n"
1141+ "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
1142+ video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n"
9151143 );
9161144 // An empty lane's line is still the whole of that lane, eq or no eq.
9171145 let empty = parse(
@@ -961,8 +1189,8 @@ mod tests {
9611189 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
9621190 assert_eq!(
9631191 String::from_utf8_lossy(&v5),
964- "edith 5\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\
965- video 1 0 0 30 0 0 -\nvideo 1 30 10 20 1 1 -\naudio 1 0 0 30 0 0 -\n",
1192+ "edith 6\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\
1193+ video 1 0 0 30 0 0 - -\nvideo 1 30 10 20 1 1 - -\naudio 1 0 0 30 0 0 - -\n",
9661194 "a re-saved v2 project differs only by its version, the lane \
9671195 numbers, the streams it always meant and an equalizer it has none of"
9681196 );
@@ -990,7 +1218,7 @@ mod tests {
9901218 assert_eq!(back.playhead, 5);
9911219 // Saved again it is v5, and that round-trips to the same document.
9921220 let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
993- assert!(v5.starts_with(b"edith 5\n"));
1221+ assert!(v5.starts_with(b"edith 6\n"));
9941222 let again = parse(&v5, &dir).expect("v5 parses");
9951223 assert_eq!(again.lanes, back.lanes);
9961224 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
@@ -1079,11 +1307,19 @@ mod tests {
10791307 path: source,
10801308 audio_stream: 1,
10811309 };
1082- save(&path, &[entry], &two(one.to_vec(), one.to_vec()), &[], 0).expect("save");
1310+ save(
1311+ &path,
1312+ &[entry],
1313+ &two(one.to_vec(), one.to_vec()),
1314+ &[],
1315+ &[],
1316+ 0,
1317+ )
1318+ .expect("save");
10831319 let bytes = std::fs::read(&path).expect("read back");
10841320 assert_eq!(
10851321 String::from_utf8_lossy(&bytes),
1086- "edith 5\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 - -\naudio 1 0 0 30 0 - -\n"
1322+ "edith 6\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 - - -\naudio 1 0 0 30 0 - - -\n"
10871323 );
10881324 // Loading rejoins the *given* directory, so the file is reached by the
10891325 // way the project was opened -- the same file, through the link, still
@@ -1127,10 +1363,10 @@ mod tests {
11271363 #[test]
11281364 fn a_wrong_first_line_is_refused_by_name() {
11291365 let dir = PathBuf::from("/proj");
1130- let err = parse(b"edith 6\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
1366+ let err = parse(b"edith 7\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
11311367 .unwrap_err()
11321368 .to_string();
1133- assert_eq!(err, "line 1: unsupported version 6");
1369+ assert_eq!(err, "line 1: unsupported version 7");
11341370 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
11351371 assert_eq!(
11361372 parse(junk, &dir).unwrap_err().to_string(),
crates/engine/src/playback.rsmodified+5 -3
@@ -246,7 +246,7 @@ impl PlaybackSession {
246246 }
247247
248248 let playhead = doc.playhead;
249- let project = Project::from_parts(doc.sources, doc.lanes, doc.eq)?;
249+ let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?;
250250 let span = project.span_at(Lane::V1, 0).expect("never empty");
251251 // Last, because it is the one thing here that cannot be taken back: the
252252 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -300,10 +300,10 @@ impl PlaybackSession {
300300 /// [`crate::edith`]). Sources no clip plays from are left out, and the
301301 /// playhead is saved with it so a reopened project resumes where it stood.
302302 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
303- let (sources, lanes, eq) = self.project.without_orphan_sources();
303+ let (sources, lanes, eq, color) = self.project.without_orphan_sources();
304304 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
305305 .min(self.project.timeline_frames().saturating_sub(1));
306- crate::edith::save(path, &sources, &lanes, &eq, playhead)
306+ crate::edith::save(path, &sources, &lanes, &eq, &color, playhead)
307307 }
308308
309309 /// The next decoded frame, its `index` rewritten from a source frame to a
@@ -538,6 +538,7 @@ impl PlaybackSession {
538538 source,
539539 link: None,
540540 eq: None,
541+ color: None,
541542 };
542543 // Which lane a source may land on is decided here and only here, so a
543544 // front-end never has to make the same call twice: a file with no
@@ -645,6 +646,7 @@ impl PlaybackSession {
645646 source,
646647 link: None,
647648 eq: None,
649+ color: None,
648650 },
649651 );
650652 // Same reason as a video import: the running audio worker's segment
crates/engine/src/project.rsmodified+371 -39
@@ -53,9 +53,16 @@
5353 //! index the clip had. Only a *save* prunes the table
5454 //! ([`Project::without_orphan_sources`]), for the reason an undone import
5555 //! leaves its source entry behind: an index handed out is an index forever.
56+//!
57+//! Its colour grade is a third such table ([`Clip::color`],
58+//! [`Project::set_color`]) and behaves in every way like the equalizer one --
59+//! shared by equal settings, inherited by both halves of a split, pruned only at
60+//! a save. An index rather than the four floats themselves for the same reason:
61+//! twenty clips graded alike name one entry, and the file writes it once.
5662
5763 use std::path::{Path, PathBuf};
5864
65+use crate::color::ColorParams;
5966 use crate::eq::EqParams;
6067
6168 /// A half-open `[in_frame, out_frame)` range of frames of source
@@ -81,6 +88,11 @@ pub struct Clip {
8188 /// plain assignment. The table is append-only within a session, so an index
8289 /// on a clipboard clip or inside an undo snapshot can never dangle.
8390 pub eq: Option<u16>,
91+ /// Index into the project's colour table
92+ /// ([`Project::color_of`]/[`Project::set_color`]), or `None` for a clip that
93+ /// plays ungraded. An index for [`Clip::eq`]'s reason, and with the same
94+ /// promises: `Copy`, append-only within a session, never dangling.
95+ pub color: Option<u16>,
8496 }
8597
8698 impl Clip {
@@ -212,9 +224,15 @@ impl Span {
212224 }
213225
214226 /// What a save writes and a load takes back: the sources, every lane in
215-/// display order with its kind, and the equalizer table their clips index into
216-/// -- [`Project::without_orphan_sources`] out, [`Project::from_parts`] in.
217-pub type Parts = (Vec<Source>, Vec<(LaneKind, Vec<Clip>)>, Vec<EqParams>);
227+/// display order with its kind, and the equalizer and colour tables their clips
228+/// index into -- [`Project::without_orphan_sources`] out,
229+/// [`Project::from_parts`] in.
230+pub type Parts = (
231+ Vec<Source>,
232+ Vec<(LaneKind, Vec<Clip>)>,
233+ Vec<EqParams>,
234+ Vec<ColorParams>,
235+);
218236
219237 /// The edit list plus its undo history.
220238 #[derive(Clone, Debug)]
@@ -226,6 +244,8 @@ pub struct Project {
226244 lanes: Vec<LaneData>,
227245 /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
228246 eq: Vec<EqParams>,
247+ /// The same, for [`Clip::color`].
248+ color: Vec<ColorParams>,
229249 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
230250 /// whole lane list, so adding a lane undoes as well.
231251 history: Vec<Vec<LaneData>>,
@@ -247,6 +267,7 @@ impl Project {
247267 source: 0,
248268 link: Some(0),
249269 eq: None,
270+ color: None,
250271 };
251272 Self {
252273 // A file is opened on its first audio stream: nothing has picked
@@ -254,6 +275,7 @@ impl Project {
254275 sources: vec![Source::new(path, 0)],
255276 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
256277 eq: Vec::new(),
278+ color: Vec::new(),
257279 history: Vec::new(),
258280 next_link: 1,
259281 }
@@ -266,17 +288,22 @@ impl Project {
266288 /// [`Project::undo`] is `false` until the first edit of the new session.
267289 /// This is the one door untrusted parts come in through, so every invariant
268290 /// every other constructor keeps is checked here, by name and in release:
269- /// every lane empty, an empty clip, a clip naming a source (or an equalizer)
270- /// that is not there, a clip whose end overflows, a lane that is unsorted or
271- /// self-overlapping, and the grouping rules of [`Clip::link`] below.
291+ /// every lane empty, an empty clip, a clip naming a source (or an equalizer,
292+ /// or a colour) that is not there, a clip whose end overflows, a lane that is
293+ /// unsorted or self-overlapping, and the grouping rules of [`Clip::link`]
294+ /// below.
272295 pub fn from_parts(
273296 sources: Vec<Source>,
274297 lanes: Vec<(LaneKind, Vec<Clip>)>,
275298 eq: Vec<EqParams>,
299+ color: Vec<ColorParams>,
276300 ) -> crate::Result<Self> {
277301 if let Some(bad) = eq.iter().position(|p| !finite(p)) {
278302 return Err(format!("eq {bad} holds a band that is not a finite number").into());
279303 }
304+ if let Some(bad) = color.iter().position(|p| !color_finite(p)) {
305+ return Err(format!("color {bad} holds a value that is not a finite number").into());
306+ }
280307 if lanes.iter().all(|(_, clips)| clips.is_empty()) {
281308 return Err("every lane is empty: that is not a project".into());
282309 }
@@ -319,6 +346,15 @@ impl Project {
319346 )
320347 .into());
321348 }
349+ if c.color.is_some_and(|i| usize::from(i) >= color.len()) {
350+ return Err(format!(
351+ "{name} clip at {} names color {} of {}",
352+ c.start,
353+ c.color.unwrap_or_default(),
354+ color.len()
355+ )
356+ .into());
357+ }
322358 }
323359 if !sorted_disjoint(&data.clips) {
324360 return Err(format!("the {name} lane is out of order or overlaps itself").into());
@@ -340,6 +376,7 @@ impl Project {
340376 .collect(),
341377 lanes,
342378 eq,
379+ color,
343380 history: Vec::new(),
344381 next_link,
345382 })
@@ -451,6 +488,7 @@ impl Project {
451488 source,
452489 link: Some(self.new_link()),
453490 eq: None,
491+ color: None,
454492 };
455493 for data in &mut self.lanes {
456494 data.clips.push(clip);
@@ -467,11 +505,12 @@ impl Project {
467505 /// emits the same bytes.
468506 ///
469507 /// Every lane comes out, in display order and with its kind: that is what a
470- /// v5 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
508+ /// v6 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
471509 /// takes back.
472510 ///
473- /// The equalizer table is pruned the same way and for the same reason: an
474- /// undone [`set_eq`](Project::set_eq) leaves settings nothing plays behind,
511+ /// The equalizer and colour tables are pruned the same way and for the same
512+ /// reason: an undone [`set_eq`](Project::set_eq) or
513+ /// [`set_color`](Project::set_color) leaves settings nothing plays behind,
475514 /// and this is the one moment they can go -- the indexes that survive it are
476515 /// only the ones a clip names.
477516 pub fn without_orphan_sources(&self) -> Parts {
@@ -479,6 +518,8 @@ impl Project {
479518 let mut sources = Vec::new();
480519 let mut moved_eq = vec![None; self.eq.len()];
481520 let mut eq = Vec::new();
521+ let mut moved_color = vec![None; self.color.len()];
522+ let mut color = Vec::new();
482523 let mut lanes = self.lanes.clone();
483524 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
484525 let old = c.source;
@@ -501,11 +542,23 @@ impl Project {
501542 }
502543 });
503544 }
545+ if let Some(old) = c.color.map(usize::from) {
546+ c.color = Some(match moved_color[old] {
547+ Some(new) => new,
548+ None => {
549+ color.push(self.color[old]);
550+ let new = (color.len() - 1) as u16;
551+ moved_color[old] = Some(new);
552+ new
553+ }
554+ });
555+ }
504556 }
505557 (
506558 sources,
507559 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
508560 eq,
561+ color,
509562 )
510563 }
511564
@@ -555,6 +608,46 @@ impl Project {
555608 true
556609 }
557610
611+ /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
612+ /// ungraded (and for an index that is not there) -- what the renderer and
613+ /// the export ask before they call [`crate::color::apply_yuv`].
614+ pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
615+ self.color
616+ .get(usize::from(self.lane(lane).get(idx)?.color?))
617+ }
618+
619+ /// Give the clip at `idx` of `lane` this colour grade, or `None` to take it
620+ /// off. [`Project::set_eq`]'s twin in every respect: one undo step, `false`
621+ /// (and no history) for an index that is not there or a value that is not
622+ /// finite, and equal settings share a table entry.
623+ pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
624+ if idx >= self.lane(lane).len() {
625+ return false;
626+ }
627+ let slot = match params {
628+ None => None,
629+ Some(params) => {
630+ if !color_finite(&params) {
631+ return false;
632+ }
633+ Some(match self.color.iter().position(|p| *p == params) {
634+ Some(at) => at as u16,
635+ // ponytail: the 65535th *distinct* grade of one session is
636+ // refused rather than silently aliased, exactly as `set_eq`
637+ // refuses the 65535th curve; same upgrade path.
638+ None if self.color.len() >= usize::from(u16::MAX) => return false,
639+ None => {
640+ self.color.push(params);
641+ (self.color.len() - 1) as u16
642+ }
643+ })
644+ }
645+ };
646+ self.snapshot();
647+ self.lane_mut(lane).expect("checked above")[idx].color = slot;
648+ true
649+ }
650+
558651 /// Length of the timeline in frames: where the *last* lane runs out. A lane
559652 /// that ends early is a trailing gap in that lane, not a shorter timeline.
560653 pub fn timeline_frames(&self) -> u32 {
@@ -973,6 +1066,16 @@ fn finite(params: &EqParams) -> bool {
9731066 .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
9741067 }
9751068
1069+/// The same for a colour grade: [`crate::color`] itself falls back to identity
1070+/// on a non-finite value, but a value that cannot be written and read back as
1071+/// itself has no business reaching the model.
1072+fn color_finite(p: &ColorParams) -> bool {
1073+ p.brightness.is_finite()
1074+ && p.contrast.is_finite()
1075+ && p.saturation.is_finite()
1076+ && p.tint.is_finite()
1077+}
1078+
9761079 fn sorted_disjoint(clips: &[Clip]) -> bool {
9771080 clips.iter().all(|c| c.out_frame > c.in_frame)
9781081 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
@@ -1110,6 +1213,7 @@ mod tests {
11101213 source,
11111214 link: None,
11121215 eq: None,
1216+ color: None,
11131217 }
11141218 }
11151219
@@ -1126,6 +1230,15 @@ mod tests {
11261230 }
11271231 }
11281232
1233+ /// A recognisable colour grade, `n` telling two of them apart -- [`band_at`]
1234+ /// for the colour table.
1235+ fn grade_at(n: u32) -> ColorParams {
1236+ ColorParams {
1237+ brightness: f64::from(n) as f32 * 0.05,
1238+ ..Default::default()
1239+ }
1240+ }
1241+
11291242 /// The `V1`, `A1` lane list a two-lane load hands [`Project::from_parts`].
11301243 fn two(video: Vec<Clip>, audio: Vec<Clip>) -> Vec<(LaneKind, Vec<Clip>)> {
11311244 vec![(LaneKind::Video, video), (LaneKind::Audio, audio)]
@@ -1304,6 +1417,7 @@ mod tests {
13041417 source: 0,
13051418 link: None,
13061419 eq: None,
1420+ color: None,
13071421 };
13081422
13091423 #[test]
@@ -1721,9 +1835,10 @@ mod tests {
17211835 // Import a second file, undo it: source 1 is now an orphan.
17221836 let mut p = two_sources();
17231837 assert!(p.undo());
1724- let (sources, lanes, eq) = p.without_orphan_sources();
1838+ let (sources, lanes, eq, color) = p.without_orphan_sources();
17251839 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
17261840 assert!(eq.is_empty(), "and a project with no equalizer writes none");
1841+ assert!(color.is_empty(), "nor a colour it never graded with");
17271842 assert_eq!(
17281843 lanes,
17291844 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
@@ -1736,7 +1851,7 @@ mod tests {
17361851 assert_eq!(p.import(FILE2, 0), 1);
17371852 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
17381853 assert!(p.append_clip(2, 4));
1739- let (sources, lanes, eq) = p.without_orphan_sources();
1854+ let (sources, lanes, eq, color) = p.without_orphan_sources();
17401855 assert_eq!(
17411856 sources,
17421857 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
@@ -1746,7 +1861,7 @@ mod tests {
17461861 [0, 1]
17471862 );
17481863 // ...and what comes out is loadable, with the same timeline.
1749- let reloaded = Project::from_parts(sources, lanes, eq).expect("from_parts");
1864+ let reloaded = Project::from_parts(sources, lanes, eq, color).expect("from_parts");
17501865 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
17511866 assert_eq!(reloaded.sources().len(), 2);
17521867 }
@@ -1816,7 +1931,7 @@ mod tests {
18161931 assert!(p.undo(), "back to the first setting");
18171932 assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
18181933
1819- let (_, lanes, eq) = p.without_orphan_sources();
1934+ let (_, lanes, eq, _) = p.without_orphan_sources();
18201935 assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
18211936 assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
18221937 assert_eq!(lanes[0].1[1].eq, None);
@@ -1824,18 +1939,138 @@ mod tests {
18241939 // One curve on three clips is one entry: settings that are equal share.
18251940 assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
18261941 assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
1827- let (_, lanes, eq) = p.without_orphan_sources();
1942+ let (_, lanes, eq, _) = p.without_orphan_sources();
18281943 assert_eq!(eq.len(), 1, "equal settings share their entry");
18291944 assert_eq!(lanes[1].1[2].eq, Some(0));
18301945 reloads(&p, "an equalizer that outlived an undo");
18311946 }
18321947
1948+ /// [`an_equalizer_follows_the_clip_through_split_copy_and_undo`]'s twin: a
1949+ /// grade is the clip's, through every edit that copies a placement.
1950+ #[test]
1951+ fn a_colour_follows_the_clip_through_split_copy_and_undo() {
1952+ let mut p = three();
1953+ assert!(
1954+ p.color_of(Lane::V1, 0).is_none(),
1955+ "a fresh clip is ungraded"
1956+ );
1957+ assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
1958+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
1959+ assert!(
1960+ p.color_of(Lane::A1, 0).is_none(),
1961+ "one clip, not the lane below"
1962+ );
1963+ assert!(
1964+ p.eq_of(Lane::V1, 0).is_none(),
1965+ "and a grade is not an equalizer"
1966+ );
1967+
1968+ // Cutting a graded clip must not grade half of it: both halves inherit.
1969+ assert!(p.split(1));
1970+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
1971+ assert_eq!(p.color_of(Lane::V1, 1), Some(&grade_at(2)));
1972+ assert!(
1973+ p.color_of(Lane::V1, 2).is_none(),
1974+ "the clip after it is ungraded"
1975+ );
1976+
1977+ // A clipboard copy carries it -- onto another lane, at that.
1978+ let copied = p.lane(Lane::V1)[1];
1979+ assert!(p.place(Lane::A1, 20, copied));
1980+ assert_eq!(p.color_of(Lane::A1, 4), Some(&grade_at(2)));
1981+ assert!(p.undo());
1982+ assert_eq!(p.lane(Lane::A1).len(), 4, "the placement came back off");
1983+
1984+ // ...and a change to one is one undo step, in both directions.
1985+ assert!(p.set_color(Lane::V1, 0, Some(grade_at(5))));
1986+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(5)));
1987+ assert!(p.undo());
1988+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
1989+ assert!(
1990+ p.set_color(Lane::V1, 0, None),
1991+ "and taking it off is an edit"
1992+ );
1993+ assert!(p.color_of(Lane::V1, 0).is_none());
1994+ assert!(p.undo());
1995+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
1996+
1997+ // Two refusals, neither of which costs an undo step.
1998+ let nan = ColorParams {
1999+ contrast: f32::NAN,
2000+ ..grade_at(1)
2001+ };
2002+ assert!(
2003+ !p.set_color(Lane::V1, 99, Some(grade_at(1))),
2004+ "no clip there"
2005+ );
2006+ assert!(!p.set_color(Lane::V1, 0, Some(nan)), "not a finite value");
2007+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(2)));
2008+ assert!(p.undo());
2009+ assert_eq!(
2010+ p.lane(Lane::V1).len(),
2011+ 3,
2012+ "one step back is before the split"
2013+ );
2014+ assert!(p.undo());
2015+ assert!(
2016+ p.color_of(Lane::V1, 0).is_none(),
2017+ "and the next is before the grade: the refusals pushed none"
2018+ );
2019+ }
2020+
2021+ /// The colour table is append-only within a session, exactly as the eq one
2022+ /// is -- and a save is where an undone grade goes.
2023+ #[test]
2024+ fn an_undone_colour_is_pruned_when_the_project_is_saved() {
2025+ let mut p = three();
2026+ assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))));
2027+ assert!(p.set_color(Lane::V1, 0, Some(grade_at(2))));
2028+ assert!(p.undo(), "back to the first grade");
2029+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(1)));
2030+
2031+ let (_, lanes, _, color) = p.without_orphan_sources();
2032+ assert_eq!(
2033+ color,
2034+ vec![grade_at(1)],
2035+ "what nothing plays is not written"
2036+ );
2037+ assert_eq!(lanes[0].1[0].color, Some(0), "and the survivor renumbers");
2038+ assert_eq!(lanes[0].1[1].color, None);
2039+
2040+ // One grade on three clips is one entry: settings that are equal share.
2041+ assert!(p.set_color(Lane::V1, 1, Some(grade_at(1))));
2042+ assert!(p.set_color(Lane::A1, 2, Some(grade_at(1))));
2043+ let (_, lanes, _, color) = p.without_orphan_sources();
2044+ assert_eq!(color.len(), 1, "equal grades share their entry");
2045+ assert_eq!(lanes[1].1[2].color, Some(0));
2046+ reloads(&p, "a colour that outlived an undo");
2047+
2048+ // An equalizer and a grade on one clip are two independent tables.
2049+ assert!(p.set_eq(Lane::V1, 0, Some(band_at(3))));
2050+ let (_, lanes, eq, color) = p.without_orphan_sources();
2051+ assert_eq!((eq.len(), color.len()), (1, 1));
2052+ assert_eq!((lanes[0].1[0].eq, lanes[0].1[0].color), (Some(0), Some(0)));
2053+ }
2054+
2055+ /// Not a claim about correctness but about cost: a clip is copied on every
2056+ /// paste, every undo snapshot and every lane clone, so its size is worth
2057+ /// knowing. The eq index fit the padding a `Copy` clip already had; the
2058+ /// colour one did not, and the struct grew a word.
2059+ #[test]
2060+ fn a_clip_is_still_a_small_copy() {
2061+ assert_eq!(
2062+ std::mem::size_of::<Clip>(),
2063+ 40,
2064+ "Clip changed size -- 32 before the colour index, 40 after"
2065+ );
2066+ }
2067+
18332068 #[test]
18342069 fn from_parts_has_no_history_and_checks_the_invariants() {
1835- let (sources, lanes, eq) = three().without_orphan_sources();
2070+ let (sources, lanes, eq, color) = three().without_orphan_sources();
18362071 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
1837- let mut p =
1838- Project::from_parts(sources.clone(), lanes.clone(), eq.clone()).expect("valid parts");
2072+ let mut p = Project::from_parts(sources.clone(), lanes.clone(), eq.clone(), color.clone())
2073+ .expect("valid parts");
18392074 assert_eq!(p.clips(), three().clips());
18402075 assert!(!p.undo(), "a loaded project has nothing to undo");
18412076 assert!(p.split(4), "...and is editable from there");
@@ -1843,13 +2078,24 @@ mod tests {
18432078
18442079 // A lane may be empty; every lane may not, and neither may no lane.
18452080 assert!(
1846- Project::from_parts(sources.clone(), two(video.clone(), Vec::new()), Vec::new())
1847- .is_ok()
2081+ Project::from_parts(
2082+ sources.clone(),
2083+ two(video.clone(), Vec::new()),
2084+ Vec::new(),
2085+ Vec::new(),
2086+ )
2087+ .is_ok()
18482088 );
18492089 assert!(
1850- Project::from_parts(sources.clone(), two(Vec::new(), Vec::new()), Vec::new()).is_err()
2090+ Project::from_parts(
2091+ sources.clone(),
2092+ two(Vec::new(), Vec::new()),
2093+ Vec::new(),
2094+ Vec::new(),
2095+ )
2096+ .is_err()
18512097 );
1852- assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_err());
2098+ assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new(), Vec::new()).is_err());
18532099 let bad: [Vec<Clip>; 5] = [
18542100 vec![clip(0, 0, 3, 1)], // source that is not there
18552101 vec![clip(0, 3, 3, 0)], // empty clip
@@ -1859,15 +2105,21 @@ mod tests {
18592105 ];
18602106 for clips in bad {
18612107 assert!(
1862- Project::from_parts(sources.clone(), two(clips.clone(), Vec::new()), Vec::new())
1863- .is_err(),
2108+ Project::from_parts(
2109+ sources.clone(),
2110+ two(clips.clone(), Vec::new()),
2111+ Vec::new(),
2112+ Vec::new(),
2113+ )
2114+ .is_err(),
18642115 "{clips:?}"
18652116 );
18662117 assert!(
18672118 Project::from_parts(
18682119 sources.clone(),
18692120 two(video.clone(), clips.clone()),
1870- Vec::new()
2121+ Vec::new(),
2122+ Vec::new(),
18712123 )
18722124 .is_err()
18732125 );
@@ -1880,7 +2132,8 @@ mod tests {
18802132 (LaneKind::Audio, audio.clone()),
18812133 (LaneKind::Video, clips),
18822134 ],
1883- Vec::new()
2135+ Vec::new(),
2136+ Vec::new(),
18842137 )
18852138 .is_err()
18862139 );
@@ -1893,17 +2146,76 @@ mod tests {
18932146 ..video[0]
18942147 }]
18952148 };
1896- assert!(Project::from_parts(sources.clone(), two(eqd(0), Vec::new()), Vec::new()).is_err());
2149+ assert!(
2150+ Project::from_parts(
2151+ sources.clone(),
2152+ two(eqd(0), Vec::new()),
2153+ Vec::new(),
2154+ Vec::new(),
2155+ )
2156+ .is_err()
2157+ );
18972158 let mut nan = band_at(1);
18982159 nan.bands[0].freq_hz = f32::NAN;
1899- assert!(Project::from_parts(sources.clone(), two(eqd(0), Vec::new()), vec![nan]).is_err());
1900- let loaded =
1901- Project::from_parts(sources.clone(), two(eqd(0), Vec::new()), vec![band_at(1)])
1902- .expect("an eq the table holds");
2160+ assert!(
2161+ Project::from_parts(
2162+ sources.clone(),
2163+ two(eqd(0), Vec::new()),
2164+ vec![nan],
2165+ Vec::new(),
2166+ )
2167+ .is_err()
2168+ );
2169+ let loaded = Project::from_parts(
2170+ sources.clone(),
2171+ two(eqd(0), Vec::new()),
2172+ vec![band_at(1)],
2173+ Vec::new(),
2174+ )
2175+ .expect("an eq the table holds");
19032176 assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
19042177
2178+ // The same two refusals for a colour, at the same door.
2179+ let graded = |i: u16| {
2180+ vec![Clip {
2181+ color: Some(i),
2182+ ..video[0]
2183+ }]
2184+ };
2185+ assert!(
2186+ Project::from_parts(
2187+ sources.clone(),
2188+ two(graded(0), Vec::new()),
2189+ Vec::new(),
2190+ Vec::new(),
2191+ )
2192+ .is_err(),
2193+ "a colour index no entry answers"
2194+ );
2195+ assert!(
2196+ Project::from_parts(
2197+ sources.clone(),
2198+ two(graded(0), Vec::new()),
2199+ Vec::new(),
2200+ vec![ColorParams {
2201+ tint: f32::NAN,
2202+ ..grade_at(1)
2203+ }],
2204+ )
2205+ .is_err(),
2206+ "a value the file format could not have written"
2207+ );
2208+ let loaded = Project::from_parts(
2209+ sources.clone(),
2210+ two(graded(0), Vec::new()),
2211+ Vec::new(),
2212+ vec![grade_at(1)],
2213+ )
2214+ .expect("a colour the table holds");
2215+ assert_eq!(loaded.color_of(Lane::V1, 0), Some(&grade_at(1)));
2216+
19052217 // Group ids survive a load, and the next split gets a fresh one.
1906- let mut p = Project::from_parts(sources, lanes, eq).expect("valid parts");
2218+ let mut p = Project::from_parts(sources, lanes, eq, color).expect("valid parts");
19072219 assert!(p.split(4));
19082220 assert!(p.clips().iter().all(|c| c.link.is_some()));
19092221 }
@@ -1926,11 +2238,12 @@ mod tests {
19262238 source: 0,
19272239 link: Some(link),
19282240 eq: None,
2241+ color: None,
19292242 };
19302243
19312244 // The door: named errors, one per cause.
19322245 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
1933- Project::from_parts(sources.clone(), two(video, audio), Vec::new())
2246+ Project::from_parts(sources.clone(), two(video, audio), Vec::new(), Vec::new())
19342247 .expect_err("refused")
19352248 .to_string()
19362249 };
@@ -1947,9 +2260,9 @@ mod tests {
19472260 // A one-sided link is *not* an error: it is what a lift leaves behind.
19482261 let mut p = Project::single(FILE, 9);
19492262 assert!(p.lift(Lane::A1, 0));
1950- let (sources, lanes, eq) = p.clone().without_orphan_sources();
2263+ let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
19512264 assert!(
1952- Project::from_parts(sources, lanes, eq).is_ok(),
2265+ Project::from_parts(sources, lanes, eq, color).is_ok(),
19532266 "a lifted lane's project has to load again"
19542267 );
19552268
@@ -2051,7 +2364,7 @@ mod tests {
20512364 .unwrap_or(&clip(0, 0, 5, 0));
20522365 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
20532366 let idx = next(4) as usize;
2054- let _ = match next(11) {
2367+ let _ = match next(13) {
20552368 0 => p.split(frame),
20562369 1 => p.regroup(frame),
20572370 2 => p.lift(lane, idx),
@@ -2065,6 +2378,10 @@ mod tests {
20652378 // orphans must not come back out of the prune.
20662379 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
20672380 9 => p.set_eq(lane, idx, None),
2381+ // ...and a colour grade in the same mix, for the same
2382+ // reason: it rides on the clip and its orphans must go.
2383+ 10 => p.set_color(lane, idx, Some(grade_at(next(4)))),
2384+ 11 => p.set_color(lane, idx, None),
20682385 _ => p.append_clip(0, 1 + next(9)),
20692386 };
20702387 reloads(&p, &format!("seed {seed}, step {step}"));
@@ -2076,8 +2393,8 @@ mod tests {
20762393 /// handed back to the constructor a load goes through -- every lane of them,
20772394 /// and the reloaded timeline has to be the same lanes in the same order.
20782395 fn reloads(p: &Project, what: &str) {
2079- let (sources, lanes, eq) = p.clone().without_orphan_sources();
2080- match Project::from_parts(sources, lanes, eq) {
2396+ let (sources, lanes, eq, color) = p.clone().without_orphan_sources();
2397+ match Project::from_parts(sources, lanes, eq, color) {
20812398 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
20822399 Ok(back) => {
20832400 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
@@ -2100,6 +2417,19 @@ mod tests {
21002417 .collect()
21012418 };
21022419 assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
2420+ // The colour table renumbers in the same prune, so the same
2421+ // claim: the params a clip names, not the index it names them by.
2422+ let colors = |p: &Project| -> Vec<Vec<Option<ColorParams>>> {
2423+ p.lanes()
2424+ .into_iter()
2425+ .map(|l| {
2426+ (0..p.lane(l).len())
2427+ .map(|i| p.color_of(l, i).copied())
2428+ .collect()
2429+ })
2430+ .collect()
2431+ };
2432+ assert_eq!(colors(&back), colors(p), "{what}: the colours changed");
21032433 }
21042434 }
21052435 }
@@ -2255,6 +2585,7 @@ mod tests {
22552585 source: 0,
22562586 link: Some(link),
22572587 eq: None,
2588+ color: None,
22582589 };
22592590 let lanes = vec![
22602591 LaneData {
@@ -2287,6 +2618,7 @@ mod tests {
22872618 source: 0,
22882619 link: Some(link),
22892620 eq: None,
2621+ color: None,
22902622 };
22912623 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
22922624 let kinds = [
@@ -2334,7 +2666,7 @@ mod tests {
23342666 let v2 = p.add_lane(LaneKind::Video);
23352667 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
23362668 let a2 = p.add_lane(LaneKind::Audio);
2337- let (sources, lanes, eq) = p.without_orphan_sources();
2669+ let (sources, lanes, eq, color) = p.without_orphan_sources();
23382670 assert_eq!(
23392671 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
23402672 [
@@ -2348,7 +2680,7 @@ mod tests {
23482680 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
23492681 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
23502682 // ...and all four load again as the same four.
2351- let back = Project::from_parts(sources, lanes, eq).expect("four lanes load");
2683+ let back = Project::from_parts(sources, lanes, eq, color).expect("four lanes load");
23522684 assert_eq!(back.lanes(), p.lanes());
23532685 assert_eq!(back.lane(a2), p.lane(a2));
23542686
crates/engine/tests/audio_export.rsmodified+3 -0
@@ -65,6 +65,7 @@ fn mixed_project() -> Project {
6565 source,
6666 link: None,
6767 eq: None,
68+ color: None,
6869 };
6970 Project::from_parts(
7071 vec![
@@ -84,11 +85,13 @@ fn mixed_project() -> Project {
8485 source: 0,
8586 link: None,
8687 eq: None,
88+ color: None,
8789 }],
8890 ),
8991 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),
9092 ],
9193 Vec::new(),
94+ Vec::new(),
9295 )
9396 .expect("a two-source project with a hole in the audio lane")
9497 }
crates/engine/tests/export.rsmodified+2 -0
@@ -192,6 +192,7 @@ fn exports_the_audio_stream_the_timeline_plays() {
192192 source: 0,
193193 link: Some(0),
194194 eq: None,
195+ color: None,
195196 };
196197 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz
197198 // 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() {
206207 (engine::project::LaneKind::Audio, vec![whole]),
207208 ],
208209 Vec::new(),
210+ Vec::new(),
209211 )
210212 .expect("a one-source project on stream 1");
211213 let out = out_path("stream1");
crates/engine/tests/saveload.rsmodified+47 -12
@@ -126,9 +126,9 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<Source>, f64
126126
127127 /// The version-1 promise: a file written before the lanes existed still opens,
128128 /// as one grouped video+audio pair per clip laid end to end, and saving it
129-/// again writes version 5 -- which reopens as the same timeline.
129+/// again writes version 6 -- which reopens as the same timeline.
130130 #[test]
131-fn a_version_1_project_loads_fully_grouped_and_saves_as_version_5() {
131+fn a_version_1_project_loads_fully_grouped_and_saves_as_version_6() {
132132 let dir = scratch("v1");
133133 copy_in(&dir, "test_av.mp4");
134134 let path = dir.join("old.edith");
@@ -156,11 +156,11 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_5() {
156156 "playhead kept"
157157 );
158158
159- // Saved again it is v5, and v5 round-trips to the same timeline.
159+ // Saved again it is v6, and v6 round-trips to the same timeline.
160160 let v2 = dir.join("new.edith");
161161 loaded.save_project(&v2).expect("save");
162162 let text = std::fs::read_to_string(&v2).expect("read back");
163- assert!(text.starts_with("edith 5\n"), "{text}");
163+ assert!(text.starts_with("edith 6\n"), "{text}");
164164 assert_eq!(
165165 text.lines().filter(|l| l.starts_with("video ")).count(),
166166 2,
@@ -237,21 +237,23 @@ fn a_version_4_project_holds_more_than_two_lanes() {
237237 );
238238 assert_eq!(loaded.timeline_duration(), 60.0 / loaded.meta().frame_rate);
239239
240- // ...and saving it writes the v5 twin of what it read: the lane list, its
241- // order and the empty lane all survive, each clip now saying it plays flat.
240+ // ...and saving it writes the v6 twin of what it read: the lane list, its
241+ // order and the empty lane all survive, each clip now saying it plays flat
242+ // and ungraded.
242243 let again = dir.join("again.edith");
243244 loaded.save_project(&again).expect("save");
244245 assert_eq!(
245246 std::fs::read_to_string(&again).expect("read back"),
246- "edith 5\nplayhead 0\nsource 0 test_av.mp4\n\
247- video 1 0 0 30 0 3 -\naudio 1\nvideo 2 40 0 20 0 - -\naudio 2 0 0 30 0 3 -\n",
248- "a four-lane project is written as it was read, one version on"
247+ "edith 6\nplayhead 0\nsource 0 test_av.mp4\n\
248+ video 1 0 0 30 0 3 - -\naudio 1\nvideo 2 40 0 20 0 - - -\naudio 2 0 0 30 0 3 - -\n",
249+ "a four-lane project is written as it was read, two versions on"
249250 );
250251 }
251252
252253 /// What version 5 is for: a clip carries equalizer settings, the file names
253254 /// them once for however many clips share them, and the whole thing survives
254-/// the engine's own door -- open, save, byte for byte the file it read.
255+/// the engine's own door -- open, save, every curve and index of it intact one
256+/// version on.
255257 #[test]
256258 fn a_version_5_project_carries_per_clip_equalizers() {
257259 let dir = scratch("v5_eq");
@@ -271,11 +273,44 @@ fn a_version_5_project_carries_per_clip_equalizers() {
271273 loaded.save_project(&again).expect("save");
272274 assert_eq!(
273275 std::fs::read_to_string(&again).expect("read back"),
274- text,
276+ "edith 6\nplayhead 0\nsource 0 test_av.mp4\n\
277+ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
278+ eq 12000.0:6.25:0.5:hs\n\
279+ video 1 0 0 30 0 - 0 -\nvideo 1 30 30 60 0 - 1 -\n\
280+ audio 1 0 0 30 0 - 0 -\naudio 1 30 30 60 0 - - -\n",
275281 "the equalizer table and every clip's index survive a round trip"
276282 );
277283 }
278284
285+/// What version 6 is for, the same claim one version on: a clip carries a
286+/// colour grade beside its equalizer, the file names each once for however many
287+/// clips share it, and the whole thing comes back out byte for byte.
288+#[test]
289+fn a_version_6_project_carries_per_clip_colours() {
290+ let dir = scratch("v6_color");
291+ copy_in(&dir, "test_av.mp4");
292+ let path = dir.join("color.edith");
293+ // Two clips on one grade, one on another, one ungraded -- and an equalizer
294+ // on a clip that is graded too, so the two tables are seen not to collide.
295+ let text = "edith 6\nplayhead 0\nsource 0 test_av.mp4\n\
296+ eq 80.0:-3.0:0.707:ls\n\
297+ color 0.1:1.2:0.9:-0.3\n\
298+ color -0.25:1.0:0.0:0.5\n\
299+ video 1 0 0 30 0 - 0 0\nvideo 1 30 30 60 0 - - 1\n\
300+ audio 1 0 0 30 0 - - 0\naudio 1 30 30 60 0 - - -\n";
301+ std::fs::write(&path, text).expect("write a v6 file");
302+
303+ let loaded = PlaybackSession::open_project(&path).expect("a v6 project opens");
304+ assert_eq!(loaded.lane_clips(engine::project::Lane::V1).len(), 2);
305+ let again = dir.join("again.edith");
306+ loaded.save_project(&again).expect("save");
307+ assert_eq!(
308+ std::fs::read_to_string(&again).expect("read back"),
309+ text,
310+ "the colour table and every clip's index survive a round trip"
311+ );
312+}
313+
279314 #[test]
280315 fn a_saved_project_reopens_as_the_same_timeline() {
281316 let dir = scratch("round_trip");
@@ -487,7 +522,7 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
487522
488523 for (text, want) in [
489524 (
490- "edith 6\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - -\n",
525+ "edith 7\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - - -\n",
491526 "line 1",
492527 ),
493528 // An eq index the table does not hold, and a band shape there is none.