From 782fc53dd49222a3704eb4bc3703ca0f46b3b636 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Mon, 10 Aug 2026 10:34:06 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20per-clip=20EQ=20per?= =?UTF-8?q?sists=20in=20.edith=20v5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A clip names its equalizer by index into a project-level table, the way it already names its source: `Clip` stays `Copy`, so a split hands both halves the same settings, a clipboard copy carries them and an undo restores whichever index the clip had. The table is append-only within a session -- an index on a clipboard clip or in an undo snapshot can never dangle -- and only a save prunes it, exactly as an undone import leaves its source entry behind. The file grows `eq ...` lines (freq:gain:q:shape, printed `{:?}` so every f32 comes back bit for bit) and one more clip field naming one of them. v4, v3, v2 and v1 still load and re-save as v5. --- crates/app/src/main.rs | 2 + crates/engine/src/edith.rs | 438 ++++++++++++++++++++++++---- crates/engine/src/playback.rs | 8 +- crates/engine/src/project.rs | 316 ++++++++++++++++++-- crates/engine/tests/audio_export.rs | 3 + crates/engine/tests/export.rs | 2 + crates/engine/tests/saveload.rs | 53 +++- 7 files changed, 725 insertions(+), 97 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index bcbdf73..6211b10 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -3459,6 +3459,7 @@ mod tests { out_frame: frames, source, link: None, + eq: None, } } @@ -3648,6 +3649,7 @@ mod tests { out_frame: 60, source: 0, link: None, + eq: 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 969db1d..8936d18 100644 --- a/crates/engine/src/edith.rs +++ b/crates/engine/src/edith.rs @@ -1,13 +1,14 @@ //! The project file: a line of text per thing, and nothing else. //! //! ```text -//! edith 4 +//! edith 5 //! playhead 90 //! source 0 test_av.mp4 //! source 1 /elsewhere/test_av2.mp4 -//! video 1 0 0 120 0 0 -//! audio 1 0 0 120 0 0 -//! video 2 120 0 120 1 - +//! 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 - - //! audio 2 //! ``` //! @@ -17,27 +18,37 @@ //! stream first because a path runs to the end of the line (it may hold //! spaces) and an optional *trailing* field could not be told from one. //! -//! 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, and its group id (`-` for none). 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. +//! An eq line is `eq ...`, one band per field, each +//! `:::` with the shape spelled `ls`, `pk` or +//! `hs` ([`crate::eq::BandKind`]). Like a source it is named by *position* -- +//! the first eq line is eq 0 -- and a clip names one, so twenty clips sharing a +//! curve write it once. `eq` on its own is the empty cascade, which is a +//! 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 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 3** was this without the lane number, and held one video lane and +//! **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 three still load -- a v1 file's clips are laid out +//! `. All four 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 saving any of them writes v4. An older -//! reader refuses a newer file by name. +//! 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. //! //! 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. @@ -63,11 +74,13 @@ use std::io::Write; use std::os::unix::ffi::{OsStrExt, OsStringExt}; use std::path::{Path, PathBuf}; +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 4"; +const MAGIC: &[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"; const MAGIC_V1: &[u8] = b"edith 1"; @@ -83,15 +96,19 @@ pub struct Document { /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then /// `A1` -- for every dialect before v4. pub lanes: Vec<(LaneKind, Vec)>, + /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for + /// every dialect before v5. + pub eq: Vec, pub playhead: u32, } -/// Writes the project to `path`, atomically. `sources` should already be -/// orphan-free ([`crate::Project::without_orphan_sources`]). +/// Writes the project to `path`, atomically. `sources` and `eq` should already +/// be orphan-free ([`crate::Project::without_orphan_sources`]). pub fn save( path: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], + eq: &[EqParams], playhead: u32, ) -> crate::Result<()> { let dir = project_dir(path); @@ -104,7 +121,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, playhead))?; + f.write_all(&emit(&dir, sources, lanes, eq, playhead))?; f.sync_all() }) .and_then(|()| std::fs::rename(&part, path)) @@ -134,7 +151,13 @@ fn project_dir(path: &Path) -> PathBuf { dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf()) } -fn emit(dir: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], playhead: u32) -> Vec { +fn emit( + dir: &Path, + sources: &[Source], + lanes: &[(LaneKind, Vec)], + eq: &[EqParams], + playhead: u32, +) -> Vec { let mut out = Vec::new(); out.extend_from_slice(MAGIC); out.push(b'\n'); @@ -144,6 +167,25 @@ fn emit(dir: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], playhea escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out); out.push(b'\n'); } + // Before the clips, for the reason the sources are: a clip names one by the + // position of its line, so the line has to be there first. + for params in eq { + out.extend_from_slice(b"eq"); + for b in ¶ms.bands { + // `{:?}` rather than `{}`: it is the formatting that promises the + // shortest string parsing back to this exact f32, and it never + // prints a bare integer, which would read as another field's shape. + let kind = match b.kind { + BandKind::LowShelf => "ls", + BandKind::Peak => "pk", + BandKind::HighShelf => "hs", + }; + out.extend_from_slice( + format!(" {:?}:{:?}:{:?}:{kind}", b.freq_hz, b.gain_db, b.q).as_bytes(), + ); + } + out.push(b'\n'); + } // 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. @@ -166,9 +208,10 @@ fn emit(dir: &Path, sources: &[Source], lanes: &[(LaneKind, Vec)], playhea } 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()); out.extend_from_slice( format!( - "{keyword} {ord} {} {} {} {} {link}\n", + "{keyword} {ord} {} {} {} {} {link} {eq}\n", c.start, c.in_frame, c.out_frame, c.source ) .as_bytes(), @@ -188,9 +231,11 @@ 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; - // ...and the one that numbers its lanes. Every older one held two. - let v4 = first == MAGIC; - if !v4 && !streamless && first != MAGIC_V3 { + // The one that carries equalizer settings... + let v5 = first == MAGIC; + // ...and the ones that number their lanes. Every older one held two. + let numbered = v5 || first == MAGIC_V4; + if !numbered && !streamless && first != MAGIC_V3 { return Err(match first.strip_prefix(b"edith ") { Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)), None => "line 1: not a edith file".to_string(), @@ -200,13 +245,15 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { let mut doc = Document { sources: Vec::new(), - // v4 declares its lanes as they come; every dialect before it held + // v4 on declares its lanes as they come; every dialect before it held // exactly `V1` and `A1`, either of which could be empty. - lanes: if v4 { + lanes: if numbered { Vec::new() } else { vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())] }, + // Nothing before v5 equalizes anything. + eq: Vec::new(), playhead: 0, }; let mut playhead_seen = false; @@ -262,6 +309,21 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { audio_stream, }); } + b"eq" if v5 => { + if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) { + return Err(format!("line {n}: eq after a clip").into()); + } + // A bare `eq` is the empty cascade -- a setting that moves + // nothing, which is not the same thing as no setting at all. + let bands = match rest.is_empty() { + true => Vec::new(), + false => rest + .split(|&b| b == b' ') + .map(|field| band(field, n)) + .collect::>>()?, + }; + doc.eq.push(EqParams { bands }); + } // 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. @@ -274,6 +336,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { out_frame: number(f[1], n)?, source: number(f[2], n)? as usize, link: Some(doc.lanes[0].1.len() as u32), + eq: None, }, &doc, n, @@ -287,9 +350,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { b"video" => LaneKind::Video, _ => LaneKind::Audio, }; - // v4 names the lane, and a line naming nothing else is an empty - // lane's whole existence. Older dialects had one lane per kind. - let (ord, rest) = if v4 { + // v4 on names the lane, and a line naming nothing else is an + // empty lane's whole existence. Older dialects had one lane per + // kind. + let (ord, rest) = if numbered { let at = rest.iter().position(|&b| b == b' '); ( number(&rest[..at.unwrap_or(rest.len())], n)?, @@ -299,10 +363,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result { (1, rest) }; let at = lane_of(&mut doc.lanes, kind, ord, n)?; - if v4 && rest.is_empty() { + if numbered && rest.is_empty() { continue; } - let f = fields(rest, 5, "clip", n)?; + // v5 grew the eq field; every older dialect ends at the link. + let f = fields(rest, if v5 { 6 } else { 5 }, "clip", n)?; let clip = check( Clip { start: number(f[0], n)?, @@ -313,6 +378,20 @@ 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) + } + }, }, &doc, n, @@ -428,6 +507,50 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result { Ok(clip) } +/// One `:::` field of an eq line. +fn band(field: &[u8], line: usize) -> crate::Result { + let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect(); + if parts.len() != 4 { + return Err(format!("line {line}: band wants 4 fields, found {}", parts.len()).into()); + } + Ok(Band { + freq_hz: float(parts[0], line)?, + gain_db: float(parts[1], line)?, + q: float(parts[2], line)?, + kind: match parts[3] { + b"ls" => BandKind::LowShelf, + b"pk" => BandKind::Peak, + b"hs" => BandKind::HighShelf, + other => { + return Err(format!( + "line {line}: {:?} is not a band shape", + String::from_utf8_lossy(other) + ) + .into()); + } + }, + }) +} + +/// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity +/// and NaN are refused rather than carried -- they are the values a coefficient +/// cannot be built from, and the ones that would not compare equal to +/// themselves on the way back. +fn float(field: &[u8], line: usize) -> crate::Result { + match std::str::from_utf8(field) + .ok() + .and_then(|s| s.parse::().ok()) + .filter(|f| f.is_finite()) + { + Some(f) => Ok(f), + None => Err(format!( + "line {line}: {:?} is not a number", + String::from_utf8_lossy(field) + ) + .into()), + } +} + fn number(field: &[u8], line: usize) -> crate::Result { match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) { Some(n) => Ok(n), @@ -485,9 +608,21 @@ mod tests { out_frame, source, link, + eq: None, } } + /// [`emit`] for a timeline that equalizes nothing, which is every case that + /// predates the eq lines. + fn flat( + dir: &Path, + sources: &[Source], + lanes: &[(LaneKind, Vec)], + playhead: u32, + ) -> Vec { + emit(dir, sources, lanes, &[], playhead) + } + /// Two sources, one under the project's own directory and one not, a clip /// from each on the video lane, and an audio lane with a gap in the middle /// -- the shape every case below starts from. @@ -520,11 +655,11 @@ mod tests { #[test] fn relative_and_absolute_paths_round_trip() { let (dir, sources, lanes) = doc(); - let bytes = emit(&dir, &sources, &lanes, 12); + let bytes = flat(&dir, &sources, &lanes, 12); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 4\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 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", "the file under the project directory is written relative to it, \ each with the audio stream it plays" ); @@ -536,7 +671,7 @@ mod tests { ); assert_eq!(back.playhead, 12); // ...and emitting the parsed document reproduces the same bytes. - assert_eq!(emit(&dir, &back.sources, &back.lanes, back.playhead), bytes); + assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes); } /// The whole of the bump: a project of any number of lanes writes and reads @@ -555,17 +690,17 @@ mod tests { (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]), (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]), ]; - let bytes = emit(&dir, &sources, &lanes, 7); + let bytes = flat(&dir, &sources, &lanes, 7); assert_eq!( String::from_utf8_lossy(&bytes), - "edith 4\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 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", "an empty lane is a line of its own; everything else is its clips" ); let back = parse(&bytes, &dir).expect("parse"); assert_eq!(back.lanes, lanes, "lane list, order and links all survive"); assert_eq!(back.playhead, 7); - assert_eq!(emit(&dir, &back.sources, &back.lanes, back.playhead), bytes); + assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes); // A lane number may not skip one of its kind: that lane was declared by // nothing, and the refusal names it. @@ -604,10 +739,193 @@ mod tests { ); } + /// One band, spelled the way an eq line spells it. + fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band { + Band { + freq_hz, + gain_db, + q, + kind, + } + } + + /// The whole of the v5 bump: the clips name a shared equalizer table, the + /// bytes are the ones documented at the top of this file, and every f32 in + /// them comes back *bit* for bit -- which is what makes a re-save of a + /// loaded project produce the same file rather than a drifting one. + #[test] + fn equalizers_round_trip_bit_exactly_and_are_shared() { + let dir = PathBuf::from("/proj"); + let sources = vec![source("/proj/a.mp4", 0)]; + let eq = vec![ + EqParams { + bands: vec![ + band_of(80.0, -3.0, 0.707, BandKind::LowShelf), + band_of(1000.0, 4.5, 1.0, BandKind::Peak), + ], + }, + // The awkward ones: a value needing all 24 mantissa bits, one whose + // shortest spelling is exponential, a subnormal, and a negative + // zero -- plus the empty cascade, which is a setting like any other. + EqParams { + bands: vec![band_of( + 16_777_215.0, + -0.1, + f32::MIN_POSITIVE / 3.0, + BandKind::HighShelf, + )], + }, + EqParams { bands: Vec::new() }, + ]; + // Two clips share entry 0, so it is written once; one clip plays flat. + let lanes = two( + vec![ + Clip { + eq: Some(0), + ..clip(0, 0, 30, 0, Some(0)) + }, + Clip { + eq: Some(1), + ..clip(30, 10, 20, 0, None) + }, + ], + vec![ + Clip { + eq: Some(0), + ..clip(0, 0, 30, 0, Some(0)) + }, + Clip { + eq: Some(2), + ..clip(30, 0, 10, 0, None) + }, + ], + ); + let bytes = emit(&dir, &sources, &lanes, &eq, 0); + assert_eq!( + String::from_utf8_lossy(&bytes), + "edith 5\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", + "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 eq it named"); + for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() { + for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() { + assert_eq!( + ( + got.freq_hz.to_bits(), + got.gain_db.to_bits(), + got.q.to_bits(), + got.kind + ), + ( + want.freq_hz.to_bits(), + want.gain_db.to_bits(), + want.q.to_bits(), + want.kind + ), + "eq {i} band {b} came back as other bits" + ); + } + } + 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); + } + + /// The refusals the eq grammar adds, each naming its line. + #[test] + fn a_malformed_equalizer_names_its_line() { + let dir = PathBuf::from("/proj"); + let head = "edith 5\nsource 0 a.mp4\n"; + for (file, want) in [ + ( + format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"), + "line 3: band wants 4 fields, found 3", + ), + ( + format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"), + "line 3: \"notch\" is not a band shape", + ), + ( + format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"), + "line 3: \"wide\" is not a number", + ), + // Neither of the two values a coefficient cannot be built from, and + // NaN would not even compare equal to itself on the way back. + ( + format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"), + "line 3: \"inf\" is not a number", + ), + ( + format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"), + "line 3: \"NaN\" is not a number", + ), + ( + format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"), + "line 4: clip names eq 1 of 1", + ), + ( + format!("{head}video 1 0 0 5 0 - 0\n"), + "line 3: clip names eq 0 of 0", + ), + // A clip's eq field is not optional in v5, 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 6 fields, found 5", + ), + ( + format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"), + "line 4: eq after a clip", + ), + // ...and an eq line in a file that predates them is a corrupt file. + ( + "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(), + "line 3: unknown keyword \"eq\"", + ), + ] { + assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want); + } + } + + /// A v4 file is a v5 one that equalizes nothing: it loads as it always did, + /// and re-saving it writes the new magic, the `-` in every clip's eq field, + /// and not one byte else. + #[test] + fn a_v4_file_equalizes_nothing() { + let dir = PathBuf::from("/proj"); + let (_, sources, lanes) = doc(); + let v4 = b"edith 4\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"; + let old = parse(v4, &dir).expect("v4 parses"); + assert_eq!( + (&old.sources, &old.lanes, old.playhead), + (&sources, &lanes, 12) + ); + 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" + ); + // An empty lane's line is still the whole of that lane, eq or no eq. + let empty = parse( + b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n", + &dir, + ) + .expect("parse"); + assert!(empty.lanes[1].1.is_empty()); + } + /// The other half of the compatibility promise: a v3 file is a v4 one /// without the lane numbers, and a v2 file names no audio stream and means /// stream 0 -- what the whole dialect could play. Both load as the two lanes - /// they always were, and saving either writes v4 with nothing else changed. + /// they always were, and saving either writes v5 with nothing else changed. #[test] fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() { let dir = PathBuf::from("/proj"); @@ -622,13 +940,13 @@ mod tests { &lanes, 12 ), - "a v3 file loads as exactly the state its v4 twin does" + "a v3 file loads as exactly the state its v5 twin does" ); // ...and re-saved it *is* that twin: the magic and a lane number per // clip line, and not one byte else. assert_eq!( - emit(&dir, &old.sources, &old.lanes, old.playhead), - emit(&dir, &old.sources, &lanes, 12), + flat(&dir, &old.sources, &old.lanes, old.playhead), + flat(&dir, &old.sources, &lanes, 12), ); let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\ @@ -640,20 +958,20 @@ mod tests { ); assert_eq!(back.lanes, lanes); - let v4 = emit(&dir, &back.sources, &back.lanes, back.playhead); + let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead); assert_eq!( - String::from_utf8_lossy(&v4), - "edith 4\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", + 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", "a re-saved v2 project differs only by its version, the lane \ - numbers and the streams it always meant" + numbers, the streams it always meant and an equalizer it has none of" ); - let again = parse(&v4, &dir).expect("v4 parses"); + let again = parse(&v5, &dir).expect("v5 parses"); assert_eq!(again.sources, back.sources); } /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of - /// lanes, and saving it again writes v4. + /// lanes, and saving it again writes v5. #[test] fn a_v1_file_loads_as_two_grouped_lanes() { let dir = PathBuf::from("/proj"); @@ -670,10 +988,10 @@ mod tests { "one take per clip, on both lanes" ); assert_eq!(back.playhead, 5); - // Saved again it is v4, and that round-trips to the same document. - let v4 = emit(&dir, &back.sources, &back.lanes, back.playhead); - assert!(v4.starts_with(b"edith 4\n")); - let again = parse(&v4, &dir).expect("v4 parses"); + // 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")); + 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. for (bytes, want) in [ @@ -761,11 +1079,11 @@ 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 4\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 -\naudio 1 0 0 30 0 -\n" + "edith 5\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 @@ -788,7 +1106,7 @@ mod tests { path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())), audio_stream: 0, }; - let bytes = emit( + let bytes = flat( &dir, &[nasty.clone()], &two(vec![clip(0, 0, 5, 0, None)], Vec::new()), @@ -809,10 +1127,10 @@ mod tests { #[test] fn a_wrong_first_line_is_refused_by_name() { let dir = PathBuf::from("/proj"); - let err = parse(b"edith 5\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) + let err = parse(b"edith 6\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir) .unwrap_err() .to_string(); - assert_eq!(err, "line 1: unsupported version 5"); + assert_eq!(err, "line 1: unsupported version 6"); for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] { assert_eq!( parse(junk, &dir).unwrap_err().to_string(), @@ -891,7 +1209,7 @@ mod tests { #[test] fn truncations_never_panic() { let (dir, sources, lanes) = doc(); - let bytes = emit(&dir, &sources, &lanes, 12); + let bytes = flat(&dir, &sources, &lanes, 12); for cut in 0..bytes.len() { let _ = parse(&bytes[..cut], &dir); // ...and the same file with a byte lopped off the front, which diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index a98ed2e..21dfd02 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)?; + let project = Project::from_parts(doc.sources, doc.lanes, doc.eq)?; let span = project.span_at(Lane::V1, 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) = self.project.without_orphan_sources(); + let (sources, lanes, eq) = 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, playhead) + crate::edith::save(path, &sources, &lanes, &eq, playhead) } /// The next decoded frame, its `index` rewritten from a source frame to a @@ -537,6 +537,7 @@ impl PlaybackSession { out_frame: frames.max(1), source, link: None, + eq: 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 @@ -643,6 +644,7 @@ impl PlaybackSession { out_frame: frames, source, link: None, + eq: 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 b208938..78689eb 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -45,9 +45,19 @@ //! clipboard or inside an undo snapshot can never dangle. An index -- not an //! `Arc` -- because [`Clip`] is `Copy`, which is what makes copy/paste a //! plain assignment. +//! +//! A clip names its equalizer the same way, by index into a second append-only +//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands +//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both +//! halves the same settings, a copy carries them, and an undo restores whatever +//! 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. use std::path::{Path, PathBuf}; +use crate::eq::EqParams; + /// A half-open `[in_frame, out_frame)` range of frames of source /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start). /// Never empty. @@ -64,6 +74,13 @@ pub struct Clip { /// Group id: clips sharing one were split from the same take. `None` for a /// clip that belongs to no group. pub link: Option, + /// Index into the project's equalizer table + /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays + /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this + /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a + /// 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, } impl Clip { @@ -194,6 +211,11 @@ 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); + /// The edit list plus its undo history. #[derive(Clone, Debug)] pub struct Project { @@ -202,6 +224,8 @@ pub struct Project { /// In display order, which is the order [`Lane::ord`] counts in: the nth /// lane of a kind here is that kind's `ord` n. Never empty. lanes: Vec, + /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into. + eq: Vec, /// Snapshots pushed *before* each successful edit; `undo` pops one. The /// whole lane list, so adding a lane undoes as well. history: Vec>, @@ -222,12 +246,14 @@ impl Project { out_frame: frame_count.max(1), source: 0, link: Some(0), + eq: None, }; Self { // A file is opened on its first audio stream: nothing has picked // one yet, and every file with audio at all has that one. sources: vec![Source::new(path, 0)], lanes: LaneData::two_lanes(vec![clip], vec![clip]), + eq: Vec::new(), history: Vec::new(), next_link: 1, } @@ -240,13 +266,17 @@ 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 that is not - /// there, a clip whose end overflows, a lane that is unsorted or + /// 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. pub fn from_parts( sources: Vec, lanes: Vec<(LaneKind, Vec)>, + eq: 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 lanes.iter().all(|(_, clips)| clips.is_empty()) { return Err("every lane is empty: that is not a project".into()); } @@ -280,6 +310,15 @@ impl Project { ) .into()); } + if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) { + return Err(format!( + "{name} clip at {} names eq {} of {}", + c.start, + c.eq.unwrap_or_default(), + eq.len() + ) + .into()); + } } if !sorted_disjoint(&data.clips) { return Err(format!("the {name} lane is out of order or overlaps itself").into()); @@ -300,6 +339,7 @@ impl Project { .map(|s| Source::new(&s.path, s.audio_stream)) .collect(), lanes, + eq, history: Vec::new(), next_link, }) @@ -410,6 +450,7 @@ impl Project { out_frame: frame_count.max(1), source, link: Some(self.new_link()), + eq: None, }; for data in &mut self.lanes { data.clips.push(clip); @@ -426,11 +467,18 @@ impl Project { /// emits the same bytes. /// /// Every lane comes out, in display order and with its kind: that is what a - /// v4 `.edith` holds (empty lanes included) and what [`Project::from_parts`] + /// v5 `.edith` holds (empty lanes included) and what [`Project::from_parts`] /// takes back. - pub fn without_orphan_sources(&self) -> (Vec, Vec<(LaneKind, Vec)>) { + /// + /// 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, + /// 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 { let mut moved = vec![None; self.sources.len()]; let mut sources = Vec::new(); + let mut moved_eq = vec![None; self.eq.len()]; + let mut eq = Vec::new(); let mut lanes = self.lanes.clone(); for c in lanes.iter_mut().flat_map(|l| &mut l.clips) { let old = c.source; @@ -442,13 +490,71 @@ impl Project { sources.len() - 1 } }; + if let Some(old) = c.eq.map(usize::from) { + c.eq = Some(match moved_eq[old] { + Some(new) => new, + None => { + eq.push(self.eq[old].clone()); + let new = (eq.len() - 1) as u16; + moved_eq[old] = Some(new); + new + } + }); + } } ( sources, lanes.into_iter().map(|l| (l.kind, l.clips)).collect(), + eq, ) } + /// What the clip at `idx` of `lane` plays through, or `None` for one that + /// plays flat (and for an index that is not there) -- what a feeder and an + /// export ask before they build an [`crate::eq::EqState`]. + pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> { + self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?)) + } + + /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to + /// take them off. One undo step, like every other edit. `false` -- and no + /// history -- for an index that is not there and for params holding a value + /// that is not finite, which is the one thing the file format could not + /// write and read back. + /// + /// Settings equal to ones already in the table share their entry, so a + /// project that puts the same curve on twenty clips writes it once. + pub fn set_eq(&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 !finite(¶ms) { + return false; + } + Some(match self.eq.iter().position(|p| *p == params) { + Some(at) => at as u16, + // ponytail: the table is append-only within a session (see + // the module docs) and `Clip::eq` is a u16, so the 65535th + // *distinct* setting of one session is refused rather than + // silently aliased. Upgrade path if a UI ever drags a slider + // that far: widen `Clip::eq` to u32 (Clip has the room) or + // snapshot the table into the history and compact it here. + None if self.eq.len() >= usize::from(u16::MAX) => return false, + None => { + self.eq.push(params); + (self.eq.len() - 1) as u16 + } + }) + } + }; + self.snapshot(); + self.lane_mut(lane).expect("checked above")[idx].eq = 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 { @@ -857,6 +963,16 @@ fn joinable(clips: &[Clip], frame: u32) -> Option { /// The lane invariant: sorted by `start`, no two placements overlapping, no /// empty placement. Checked at every constructor and asserted after every /// mutation -- the offset model is only tractable while it holds. +/// The one thing an equalizer setting may not be: a value the text format +/// cannot write and read back as itself. Checked wherever params come in, so +/// what an edit produces is always what a save writes and a load reads. +fn finite(params: &EqParams) -> bool { + params + .bands + .iter() + .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.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) @@ -993,6 +1109,20 @@ mod tests { out_frame, source, link: None, + eq: None, + } + } + + /// A recognisable equalizer setting: one peak band, `n` telling two of them + /// apart -- which is what makes the table's dedup and its prune visible. + fn band_at(n: u32) -> EqParams { + EqParams { + bands: vec![crate::eq::Band { + freq_hz: 1000.0, + gain_db: f64::from(n) as f32 * 1.5, + q: 0.707, + kind: crate::eq::BandKind::Peak, + }], } } @@ -1173,6 +1303,7 @@ mod tests { out_frame: 102, source: 0, link: None, + eq: None, }; #[test] @@ -1590,8 +1721,9 @@ 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) = p.without_orphan_sources(); + let (sources, lanes, eq) = 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_eq!( lanes, two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()), @@ -1604,7 +1736,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) = p.without_orphan_sources(); + let (sources, lanes, eq) = p.without_orphan_sources(); assert_eq!( sources, vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)] @@ -1614,25 +1746,110 @@ mod tests { [0, 1] ); // ...and what comes out is loadable, with the same timeline. - let reloaded = Project::from_parts(sources, lanes).expect("from_parts"); + let reloaded = Project::from_parts(sources, lanes, eq).expect("from_parts"); assert_eq!(reloaded.timeline_frames(), p.timeline_frames()); assert_eq!(reloaded.sources().len(), 2); } + /// A clip's equalizer is the clip's: it survives every edit that copies a + /// placement, and it comes back with an undo. + #[test] + fn an_equalizer_follows_the_clip_through_split_copy_and_undo() { + let mut p = three(); + assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat"); + assert!(p.set_eq(Lane::A1, 0, Some(band_at(2)))); + assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); + assert!( + p.eq_of(Lane::V1, 0).is_none(), + "one clip, not the lane above" + ); + + // Cutting an EQ'd clip must not silence half of it: both halves inherit. + assert!(p.split(1)); + assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); + assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2))); + assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat"); + + // A clipboard copy carries it -- onto another lane, at that. + let copied = p.lane(Lane::A1)[1]; + assert!(p.place(Lane::V1, 20, copied)); + assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2))); + assert!(p.undo()); + assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off"); + + // ...and a change to one is one undo step, in both directions. + assert!(p.set_eq(Lane::A1, 0, Some(band_at(5)))); + assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5))); + assert!(p.undo()); + assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); + assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit"); + assert!(p.eq_of(Lane::A1, 0).is_none()); + assert!(p.undo()); + assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); + + // Two refusals, neither of which costs an undo step. + let mut nan = band_at(1); + nan.bands[0].q = f32::INFINITY; + assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there"); + assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band"); + assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2))); + assert!(p.undo()); + assert_eq!( + p.lane(Lane::A1).len(), + 3, + "one step back is before the split" + ); + assert!(p.undo()); + assert!( + p.eq_of(Lane::A1, 0).is_none(), + "and the next is before the setting: the refusals pushed none" + ); + } + + /// The table is append-only within a session, exactly as the sources are, so + /// an undone setting is still in it -- and a save is where it goes. + #[test] + fn an_undone_equalizer_is_pruned_when_the_project_is_saved() { + let mut p = three(); + assert!(p.set_eq(Lane::V1, 0, Some(band_at(1)))); + assert!(p.set_eq(Lane::V1, 0, Some(band_at(2)))); + 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(); + 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); + + // 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(); + 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"); + } + #[test] fn from_parts_has_no_history_and_checks_the_invariants() { - let (sources, lanes) = three().without_orphan_sources(); + let (sources, lanes, eq) = 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()).expect("valid parts"); + let mut p = + Project::from_parts(sources.clone(), lanes.clone(), eq.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"); assert!(p.undo()); // 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())).is_ok()); - assert!(Project::from_parts(sources.clone(), two(Vec::new(), Vec::new())).is_err()); - assert!(Project::from_parts(sources.clone(), Vec::new()).is_err()); + assert!( + Project::from_parts(sources.clone(), two(video.clone(), Vec::new()), Vec::new()) + .is_ok() + ); + assert!( + Project::from_parts(sources.clone(), two(Vec::new(), Vec::new()), Vec::new()).is_err() + ); + assert!(Project::from_parts(sources.clone(), 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 @@ -1642,11 +1859,17 @@ mod tests { ]; for clips in bad { assert!( - Project::from_parts(sources.clone(), two(clips.clone(), Vec::new())).is_err(), + Project::from_parts(sources.clone(), two(clips.clone(), Vec::new()), Vec::new()) + .is_err(), "{clips:?}" ); assert!( - Project::from_parts(sources.clone(), two(video.clone(), clips.clone())).is_err() + Project::from_parts( + sources.clone(), + two(video.clone(), clips.clone()), + Vec::new() + ) + .is_err() ); // ...and on a third lane, which is checked by the same walk. assert!( @@ -1656,13 +1879,31 @@ mod tests { (LaneKind::Video, video.clone()), (LaneKind::Audio, audio.clone()), (LaneKind::Video, clips), - ] + ], + Vec::new() ) .is_err() ); } + // An equalizer index no table entry answers, and a table entry the file + // format could not have written, are refused at this door too. + let eqd = |i: u16| { + vec![Clip { + eq: Some(i), + ..video[0] + }] + }; + assert!(Project::from_parts(sources.clone(), two(eqd(0), 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_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1))); + // Group ids survive a load, and the next split gets a fresh one. - let mut p = Project::from_parts(sources, lanes).expect("valid parts"); + let mut p = Project::from_parts(sources, lanes, eq).expect("valid parts"); assert!(p.split(4)); assert!(p.clips().iter().all(|c| c.link.is_some())); } @@ -1684,11 +1925,12 @@ mod tests { out_frame, source: 0, link: Some(link), + eq: None, }; // The door: named errors, one per cause. let err = |video: Vec, audio: Vec| { - Project::from_parts(sources.clone(), two(video, audio)) + Project::from_parts(sources.clone(), two(video, audio), Vec::new()) .expect_err("refused") .to_string() }; @@ -1705,9 +1947,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) = p.clone().without_orphan_sources(); + let (sources, lanes, eq) = p.clone().without_orphan_sources(); assert!( - Project::from_parts(sources, lanes).is_ok(), + Project::from_parts(sources, lanes, eq).is_ok(), "a lifted lane's project has to load again" ); @@ -1776,7 +2018,7 @@ mod tests { &p, "a second audio stream of the same file, placed and split", ); - let (sources, _) = p.without_orphan_sources(); + let (sources, ..) = p.without_orphan_sources(); assert_eq!( sources.iter().map(|s| s.audio_stream).collect::>(), [0, 1], @@ -1809,7 +2051,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(9) { + let _ = match next(11) { 0 => p.split(frame), 1 => p.regroup(frame), 2 => p.lift(lane, idx), @@ -1818,6 +2060,11 @@ mod tests { 5 => p.ripple_delete(frame, next(9)), 6 => p.delete(idx), 7 => p.undo(), + // An equalizer put on and taken off in the mix: what a clip + // carries has to reload with it, and the entries an undo + // 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), _ => p.append_clip(0, 1 + next(9)), }; reloads(&p, &format!("seed {seed}, step {step}")); @@ -1829,8 +2076,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) = p.clone().without_orphan_sources(); - match Project::from_parts(sources, lanes) { + let (sources, lanes, eq) = p.clone().without_orphan_sources(); + match Project::from_parts(sources, lanes, eq) { 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"); @@ -1840,6 +2087,19 @@ mod tests { p.lanes().into_iter().map(|l| p.lane_spans(l)).collect() }; assert_eq!(spans(&back), spans(p), "{what}: the placements changed"); + // The prune renumbers the eq table too, so what has to survive + // is the settings themselves, clip by clip. + let eqs = |p: &Project| -> Vec>> { + p.lanes() + .into_iter() + .map(|l| { + (0..p.lane(l).len()) + .map(|i| p.eq_of(l, i).cloned()) + .collect() + }) + .collect() + }; + assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed"); } } } @@ -1994,6 +2254,7 @@ mod tests { out_frame, source: 0, link: Some(link), + eq: None, }; let lanes = vec![ LaneData { @@ -2025,6 +2286,7 @@ mod tests { out_frame: end, source: 0, link: Some(link), + eq: None, }; // V1, A1, V2, A2 -- one take over [0, 4) on all four. let kinds = [ @@ -2072,7 +2334,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) = p.without_orphan_sources(); + let (sources, lanes, eq) = p.without_orphan_sources(); assert_eq!( lanes.iter().map(|(k, _)| *k).collect::>(), [ @@ -2086,7 +2348,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).expect("four lanes load"); + let back = Project::from_parts(sources, lanes, eq).expect("four lanes load"); assert_eq!(back.lanes(), p.lanes()); assert_eq!(back.lane(a2), p.lane(a2)); @@ -2128,7 +2390,9 @@ mod tests { .unwrap_or(&clip(0, 0, 5, 0)); let lane = lanes[next(3) as usize]; let idx = next(4) as usize; - let _ = match next(10) { + let _ = match next(12) { + 10 => p.set_eq(lane, idx, Some(band_at(next(4)))), + 11 => p.set_eq(lane, idx, None), 0 => p.split(frame), 1 => p.regroup(frame), 2 => p.lift(lane, idx), diff --git a/crates/engine/tests/audio_export.rs b/crates/engine/tests/audio_export.rs index 9007916..6e7bd5c 100644 --- a/crates/engine/tests/audio_export.rs +++ b/crates/engine/tests/audio_export.rs @@ -64,6 +64,7 @@ fn mixed_project() -> Project { out_frame: 30, source, link: None, + eq: None, }; Project::from_parts( vec![ @@ -82,10 +83,12 @@ fn mixed_project() -> Project { out_frame: 90, source: 0, link: None, + eq: None, }], ), (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]), ], + 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 2228877..5011ac9 100644 --- a/crates/engine/tests/export.rs +++ b/crates/engine/tests/export.rs @@ -191,6 +191,7 @@ fn exports_the_audio_stream_the_timeline_plays() { out_frame: meta.frame_count, source: 0, link: Some(0), + eq: 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 @@ -204,6 +205,7 @@ fn exports_the_audio_stream_the_timeline_plays() { (engine::project::LaneKind::Video, vec![whole]), (engine::project::LaneKind::Audio, vec![whole]), ], + Vec::new(), ) .expect("a one-source project on stream 1"); let out = out_path("stream1"); diff --git a/crates/engine/tests/saveload.rs b/crates/engine/tests/saveload.rs index 1bafa82..7e1b26a 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 4 -- which reopens as the same timeline. +/// again writes version 5 -- which reopens as the same timeline. #[test] -fn a_version_1_project_loads_fully_grouped_and_saves_as_version_4() { +fn a_version_1_project_loads_fully_grouped_and_saves_as_version_5() { 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_4() { "playhead kept" ); - // Saved again it is v4, and v4 round-trips to the same timeline. + // Saved again it is v5, and v5 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 4\n"), "{text}"); + assert!(text.starts_with("edith 5\n"), "{text}"); assert_eq!( text.lines().filter(|l| l.starts_with("video ")).count(), 2, @@ -237,14 +237,42 @@ 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 back the same bytes: the lane list, its order and - // the empty lane all survive the round trip. + // ...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. + 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" + ); +} + +/// 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. +#[test] +fn a_version_5_project_carries_per_clip_equalizers() { + let dir = scratch("v5_eq"); + copy_in(&dir, "test_av.mp4"); + let path = dir.join("eq.edith"); + // Two clips on one curve, one on another, one flat. + let text = "edith 5\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"; + std::fs::write(&path, text).expect("write a v5 file"); + + let loaded = PlaybackSession::open_project(&path).expect("a v5 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, - "a four-lane project is written as it was read" + "the equalizer table and every clip's index survive a round trip" ); } @@ -459,9 +487,18 @@ fn malformed_files_are_numbered_errors_and_never_panics() { for (text, want) in [ ( - "edith 5\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 -\n", + "edith 6\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. + ( + "edith 5\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - 0\n", + "line 3", + ), + ( + "edith 5\nsource 0 test_av.mp4\neq 80.0:0.0:0.707:band\nvideo 1 0 0 30 0 - 0\n", + "line 3", + ), // A lane number that skips one of its kind: V2 was never declared. ( "edith 4\nsource 0 test_av.mp4\nvideo 2 0 0 30 0 -\n",