forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'worktree-agent-a42baf3b3c211cb1e'

Browse files at this commit

6a64d06b5d9172176e0b888b784281122c1ce63eAhmet Kaan GümüşParent: 192312a782fc53
crates/app/src/main.rsmodified+2 -0
@@ -3459,6 +3459,7 @@ mod tests {
3459 out_frame: frames,3459 out_frame: frames,
3460 source,3460 source,
3461 link: None,3461 link: None,
3462+ eq: None,
3462 }3463 }
3463 }3464 }
3464 3465
@@ -3648,6 +3649,7 @@ mod tests {
3648 out_frame: 60,3649 out_frame: 60,
3649 source: 0,3650 source: 0,
3650 link: None,3651 link: None,
3652+ eq: None,
3651 };3653 };
3652 assert_eq!(clip.end(), 90);3654 assert_eq!(clip.end(), 90);
3653 // Cut splits from inside only: neither edge has anything to split off.3655 // Cut splits from inside only: neither edge has anything to split off.
crates/engine/src/edith.rsmodified+378 -60
@@ -1,13 +1,14 @@
1 //! The project file: a line of text per thing, and nothing else.1 //! The project file: a line of text per thing, and nothing else.
2 //!2 //!
3 //! ```text3 //! ```text
4-//! edith 44+//! edith 5
5 //! playhead 905 //! playhead 90
6 //! source 0 test_av.mp46 //! source 0 test_av.mp4
7 //! source 1 /elsewhere/test_av2.mp47 //! source 1 /elsewhere/test_av2.mp4
8-//! video 1 0 0 120 0 08+//! eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk
9-//! audio 1 0 0 120 0 09+//! video 1 0 0 120 0 0 0
10-//! video 2 120 0 120 1 -10+//! audio 1 0 0 120 0 0 0
11+//! video 2 120 0 120 1 - -
11 //! audio 212 //! audio 2
12 //! ```13 //! ```
13 //!14 //!
@@ -17,27 +18,37 @@
17 //! stream first because a path runs to the end of the line (it may hold18 //! stream first because a path runs to the end of the line (it may hold
18 //! spaces) and an optional *trailing* field could not be told from one.19 //! spaces) and an optional *trailing* field could not be told from one.
19 //!20 //!
20-//! A lane line is `<kind> <lane> <start> <in> <out> <source> <link>`: which lane21+//! An eq line is `eq <band>...`, one band per field, each
21-//! the clip is on -- its kind and its 1-based number among the lanes of that22+//! `<frequency>:<gain dB>:<Q>:<shape>` with the shape spelled `ls`, `pk` or
22-//! kind, the [`crate::project::Lane::label`] a header column shows -- then where23+//! `hs` ([`crate::eq::BandKind`]). Like a source it is named by *position* --
23-//! the clip sits on the timeline, the half-open source range it plays, the file24+//! the first eq line is eq 0 -- and a clip names one, so twenty clips sharing a
24-//! it plays from, and its group id (`-` for none). Timeline placement is25+//! curve write it once. `eq` on its own is the empty cascade, which is a
25-//! explicit, so a *gap* is simply a stretch no line covers -- there is nothing26+//! setting like any other. The numbers are printed to round trip bit-exactly;
26-//! to write for one, and nothing that can disagree about its length.27+//! anything not finite is refused, here and at [`crate::Project::set_eq`].
28+//!
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.
27 //!37 //!
28 //! A lane is declared by the clips on it, in the order the lanes are displayed38 //! A lane is declared by the clips on it, in the order the lanes are displayed
29 //! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which39 //! in; a lane holding *nothing* has a bare `<kind> <lane>` line instead, which
30 //! is the only way an empty lane could still be there on the way back. A lane40 //! is the only way an empty lane could still be there on the way back. A lane
31 //! number may not skip one of its kind.41 //! number may not skip one of its kind.
32 //!42 //!
33-//! **Version 3** was this without the lane number, and held one video lane and43+//! **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
34 //! one audio lane, no more. **Version 2** wrote `source <path>` as well, which45 //! one audio lane, no more. **Version 2** wrote `source <path>` as well, which
35 //! is this file's stream 0 -- one per file, whichever audio track came first.46 //! is this file's stream 0 -- one per file, whichever audio track came first.
36 //! **Version 1** wrote that and one lane, queued end to end: `clip <in> <out>47 //! **Version 1** wrote that and one lane, queued end to end: `clip <in> <out>
37-//! <source>`. All three still load -- a v1 file's clips are laid out48+//! <source>`. All four still load -- a v1 file's clips are laid out
38 //! cumulatively and copied onto both lanes as one group each, which is exactly49 //! cumulatively and copied onto both lanes as one group each, which is exactly
39-//! what a v1 timeline meant -- and saving any of them writes v4. An older50+//! what a v1 timeline meant, and an older file simply equalizes nothing -- and
40-//! reader refuses a newer file by name.51+//! saving any of them writes v5. An older reader refuses a newer file by name.
41 //!52 //!
42 //! Text because an edit list is a few integers and a path, and a path is53 //! Text because an edit list is a few integers and a path, and a path is
43 //! *bytes* on this platform -- a JSON string would have to lossily decode one.54 //! *bytes* on this platform -- a JSON string would have to lossily decode one.
@@ -63,11 +74,13 @@ use std::io::Write;
63 use std::os::unix::ffi::{OsStrExt, OsStringExt};74 use std::os::unix::ffi::{OsStrExt, OsStringExt};
64 use std::path::{Path, PathBuf};75 use std::path::{Path, PathBuf};
65 76
77+use crate::eq::{Band, BandKind, EqParams};
66 use crate::project::{Clip, Lane, LaneKind, Source};78 use crate::project::{Clip, Lane, LaneKind, Source};
67 79
68 /// What [`save`] writes. Read support goes back to `edith 1`; see the module80 /// What [`save`] writes. Read support goes back to `edith 1`; see the module
69 /// docs for what those dialects looked like.81 /// docs for what those dialects looked like.
70-const MAGIC: &[u8] = b"edith 4";82+const MAGIC: &[u8] = b"edith 5";
83+const MAGIC_V4: &[u8] = b"edith 4";
71 const MAGIC_V3: &[u8] = b"edith 3";84 const MAGIC_V3: &[u8] = b"edith 3";
72 const MAGIC_V2: &[u8] = b"edith 2";85 const MAGIC_V2: &[u8] = b"edith 2";
73 const MAGIC_V1: &[u8] = b"edith 1";86 const MAGIC_V1: &[u8] = b"edith 1";
@@ -83,15 +96,19 @@ pub struct Document {
83 /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then96 /// [`crate::Project::from_parts`] takes them in. Exactly two -- `V1` then
84 /// `A1` -- for every dialect before v4.97 /// `A1` -- for every dialect before v4.
85 pub lanes: Vec<(LaneKind, Vec<Clip>)>,98 pub lanes: Vec<(LaneKind, Vec<Clip>)>,
99+ /// The equalizer table [`Clip::eq`] indexes into, in file order. Empty for
100+ /// every dialect before v5.
101+ pub eq: Vec<EqParams>,
86 pub playhead: u32,102 pub playhead: u32,
87 }103 }
88 104
89-/// Writes the project to `path`, atomically. `sources` should already be105+/// Writes the project to `path`, atomically. `sources` and `eq` should already
90-/// orphan-free ([`crate::Project::without_orphan_sources`]).106+/// be orphan-free ([`crate::Project::without_orphan_sources`]).
91 pub fn save(107 pub fn save(
92 path: &Path,108 path: &Path,
93 sources: &[Source],109 sources: &[Source],
94 lanes: &[(LaneKind, Vec<Clip>)],110 lanes: &[(LaneKind, Vec<Clip>)],
111+ eq: &[EqParams],
95 playhead: u32,112 playhead: u32,
96 ) -> crate::Result<()> {113 ) -> crate::Result<()> {
97 let dir = project_dir(path);114 let dir = project_dir(path);
@@ -104,7 +121,7 @@ pub fn save(
104 // the second one puts the name itself there.121 // the second one puts the name itself there.
105 let result = std::fs::File::create(&part)122 let result = std::fs::File::create(&part)
106 .and_then(|mut f| {123 .and_then(|mut f| {
107- f.write_all(&emit(&dir, sources, lanes, playhead))?;124+ f.write_all(&emit(&dir, sources, lanes, eq, playhead))?;
108 f.sync_all()125 f.sync_all()
109 })126 })
110 .and_then(|()| std::fs::rename(&part, path))127 .and_then(|()| std::fs::rename(&part, path))
@@ -134,7 +151,13 @@ fn project_dir(path: &Path) -> PathBuf {
134 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())151 dir.canonicalize().unwrap_or_else(|_| dir.to_path_buf())
135 }152 }
136 153
137-fn emit(dir: &Path, sources: &[Source], lanes: &[(LaneKind, Vec<Clip>)], playhead: u32) -> Vec<u8> {154+fn emit(
155+ dir: &Path,
156+ sources: &[Source],
157+ lanes: &[(LaneKind, Vec<Clip>)],
158+ eq: &[EqParams],
159+ playhead: u32,
160+) -> Vec<u8> {
138 let mut out = Vec::new();161 let mut out = Vec::new();
139 out.extend_from_slice(MAGIC);162 out.extend_from_slice(MAGIC);
140 out.push(b'\n');163 out.push(b'\n');
@@ -144,6 +167,25 @@ fn emit(dir: &Path, sources: &[Source], lanes: &[(LaneKind, Vec<Clip>)], playhea
144 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);167 escape(s.path.strip_prefix(dir).unwrap_or(&s.path), &mut out);
145 out.push(b'\n');168 out.push(b'\n');
146 }169 }
170+ // Before the clips, for the reason the sources are: a clip names one by the
171+ // position of its line, so the line has to be there first.
172+ for params in eq {
173+ out.extend_from_slice(b"eq");
174+ for b in &params.bands {
175+ // `{:?}` rather than `{}`: it is the formatting that promises the
176+ // shortest string parsing back to this exact f32, and it never
177+ // prints a bare integer, which would read as another field's shape.
178+ let kind = match b.kind {
179+ BandKind::LowShelf => "ls",
180+ BandKind::Peak => "pk",
181+ BandKind::HighShelf => "hs",
182+ };
183+ out.extend_from_slice(
184+ format!(" {:?}:{:?}:{:?}:{kind}", b.freq_hz, b.gain_db, b.q).as_bytes(),
185+ );
186+ }
187+ out.push(b'\n');
188+ }
147 // Lane by lane rather than interleaved by time: a lane reads as a list, the189 // Lane by lane rather than interleaved by time: a lane reads as a list, the
148 // parser gets its sortedness check for free from the order it is in, and190 // parser gets its sortedness check for free from the order it is in, and
149 // the lanes come back out in the order they are displayed in.191 // 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<Clip>)], playhea
166 }208 }
167 for c in clips {209 for c in clips {
168 let link = c.link.map_or("-".to_string(), |l| l.to_string());210 let link = c.link.map_or("-".to_string(), |l| l.to_string());
211+ let eq = c.eq.map_or("-".to_string(), |e| e.to_string());
169 out.extend_from_slice(212 out.extend_from_slice(
170 format!(213 format!(
171- "{keyword} {ord} {} {} {} {} {link}\n",214+ "{keyword} {ord} {} {} {} {} {link} {eq}\n",
172 c.start, c.in_frame, c.out_frame, c.source215 c.start, c.in_frame, c.out_frame, c.source
173 )216 )
174 .as_bytes(),217 .as_bytes(),
@@ -188,9 +231,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
188 // The dialects that wrote a source line without its stream field. Reading231 // The dialects that wrote a source line without its stream field. Reading
189 // one is the whole of what "an old project still opens" means here.232 // one is the whole of what "an old project still opens" means here.
190 let streamless = v1 || first == MAGIC_V2;233 let streamless = v1 || first == MAGIC_V2;
191- // ...and the one that numbers its lanes. Every older one held two.234+ // The one that carries equalizer settings...
192- let v4 = first == MAGIC;235+ let v5 = first == MAGIC;
193- if !v4 && !streamless && first != MAGIC_V3 {236+ // ...and the ones that number their lanes. Every older one held two.
237+ let numbered = v5 || first == MAGIC_V4;
238+ if !numbered && !streamless && first != MAGIC_V3 {
194 return Err(match first.strip_prefix(b"edith ") {239 return Err(match first.strip_prefix(b"edith ") {
195 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),240 Some(v) => format!("line 1: unsupported version {}", String::from_utf8_lossy(v)),
196 None => "line 1: not a edith file".to_string(),241 None => "line 1: not a edith file".to_string(),
@@ -200,13 +245,15 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
200 245
201 let mut doc = Document {246 let mut doc = Document {
202 sources: Vec::new(),247 sources: Vec::new(),
203- // v4 declares its lanes as they come; every dialect before it held248+ // v4 on declares its lanes as they come; every dialect before it held
204 // exactly `V1` and `A1`, either of which could be empty.249 // exactly `V1` and `A1`, either of which could be empty.
205- lanes: if v4 {250+ lanes: if numbered {
206 Vec::new()251 Vec::new()
207 } else {252 } else {
208 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]253 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())]
209 },254 },
255+ // Nothing before v5 equalizes anything.
256+ eq: Vec::new(),
210 playhead: 0,257 playhead: 0,
211 };258 };
212 let mut playhead_seen = false;259 let mut playhead_seen = false;
@@ -262,6 +309,21 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
262 audio_stream,309 audio_stream,
263 });310 });
264 }311 }
312+ b"eq" if v5 => {
313+ if doc.lanes.iter().any(|(_, clips)| !clips.is_empty()) {
314+ return Err(format!("line {n}: eq after a clip").into());
315+ }
316+ // A bare `eq` is the empty cascade -- a setting that moves
317+ // nothing, which is not the same thing as no setting at all.
318+ let bands = match rest.is_empty() {
319+ true => Vec::new(),
320+ false => rest
321+ .split(|&b| b == b' ')
322+ .map(|field| band(field, n))
323+ .collect::<crate::Result<Vec<Band>>>()?,
324+ };
325+ doc.eq.push(EqParams { bands });
326+ }
265 // v1: one lane, no placement, no groups. Every clip becomes one327 // v1: one lane, no placement, no groups. Every clip becomes one
266 // grouped video+audio pair laid where the queue reached, which is328 // grouped video+audio pair laid where the queue reached, which is
267 // what the file always meant.329 // what the file always meant.
@@ -274,6 +336,7 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
274 out_frame: number(f[1], n)?,336 out_frame: number(f[1], n)?,
275 source: number(f[2], n)? as usize,337 source: number(f[2], n)? as usize,
276 link: Some(doc.lanes[0].1.len() as u32),338 link: Some(doc.lanes[0].1.len() as u32),
339+ eq: None,
277 },340 },
278 &doc,341 &doc,
279 n,342 n,
@@ -287,9 +350,10 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
287 b"video" => LaneKind::Video,350 b"video" => LaneKind::Video,
288 _ => LaneKind::Audio,351 _ => LaneKind::Audio,
289 };352 };
290- // v4 names the lane, and a line naming nothing else is an empty353+ // v4 on names the lane, and a line naming nothing else is an
291- // lane's whole existence. Older dialects had one lane per kind.354+ // empty lane's whole existence. Older dialects had one lane per
292- let (ord, rest) = if v4 {355+ // kind.
356+ let (ord, rest) = if numbered {
293 let at = rest.iter().position(|&b| b == b' ');357 let at = rest.iter().position(|&b| b == b' ');
294 (358 (
295 number(&rest[..at.unwrap_or(rest.len())], n)?,359 number(&rest[..at.unwrap_or(rest.len())], n)?,
@@ -299,10 +363,11 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
299 (1, rest)363 (1, rest)
300 };364 };
301 let at = lane_of(&mut doc.lanes, kind, ord, n)?;365 let at = lane_of(&mut doc.lanes, kind, ord, n)?;
302- if v4 && rest.is_empty() {366+ if numbered && rest.is_empty() {
303 continue;367 continue;
304 }368 }
305- let f = fields(rest, 5, "clip", n)?;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)?;
306 let clip = check(371 let clip = check(
307 Clip {372 Clip {
308 start: number(f[0], n)?,373 start: number(f[0], n)?,
@@ -313,6 +378,20 @@ fn parse(data: &[u8], dir: &Path) -> crate::Result<Document> {
313 b"-" => None,378 b"-" => None,
314 field => Some(number(field, n)?),379 field => Some(number(field, n)?),
315 },380 },
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+ },
316 },395 },
317 &doc,396 &doc,
318 n,397 n,
@@ -428,6 +507,50 @@ fn check(clip: Clip, doc: &Document, line: usize) -> crate::Result<Clip> {
428 Ok(clip)507 Ok(clip)
429 }508 }
430 509
510+/// One `<frequency>:<gain>:<Q>:<shape>` field of an eq line.
511+fn band(field: &[u8], line: usize) -> crate::Result<Band> {
512+ let parts: Vec<&[u8]> = field.split(|&b| b == b':').collect();
513+ if parts.len() != 4 {
514+ return Err(format!("line {line}: band wants 4 fields, found {}", parts.len()).into());
515+ }
516+ Ok(Band {
517+ freq_hz: float(parts[0], line)?,
518+ gain_db: float(parts[1], line)?,
519+ q: float(parts[2], line)?,
520+ kind: match parts[3] {
521+ b"ls" => BandKind::LowShelf,
522+ b"pk" => BandKind::Peak,
523+ b"hs" => BandKind::HighShelf,
524+ other => {
525+ return Err(format!(
526+ "line {line}: {:?} is not a band shape",
527+ String::from_utf8_lossy(other)
528+ )
529+ .into());
530+ }
531+ },
532+ })
533+}
534+
535+/// A band's number: whatever `{:?}` wrote, read back to the same bits. Infinity
536+/// and NaN are refused rather than carried -- they are the values a coefficient
537+/// cannot be built from, and the ones that would not compare equal to
538+/// themselves on the way back.
539+fn float(field: &[u8], line: usize) -> crate::Result<f32> {
540+ match std::str::from_utf8(field)
541+ .ok()
542+ .and_then(|s| s.parse::<f32>().ok())
543+ .filter(|f| f.is_finite())
544+ {
545+ Some(f) => Ok(f),
546+ None => Err(format!(
547+ "line {line}: {:?} is not a number",
548+ String::from_utf8_lossy(field)
549+ )
550+ .into()),
551+ }
552+}
553+
431 fn number(field: &[u8], line: usize) -> crate::Result<u32> {554 fn number(field: &[u8], line: usize) -> crate::Result<u32> {
432 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {555 match std::str::from_utf8(field).ok().and_then(|s| s.parse().ok()) {
433 Some(n) => Ok(n),556 Some(n) => Ok(n),
@@ -485,9 +608,21 @@ mod tests {
485 out_frame,608 out_frame,
486 source,609 source,
487 link,610 link,
611+ eq: None,
488 }612 }
489 }613 }
490 614
615+ /// [`emit`] for a timeline that equalizes nothing, which is every case that
616+ /// predates the eq lines.
617+ fn flat(
618+ dir: &Path,
619+ sources: &[Source],
620+ lanes: &[(LaneKind, Vec<Clip>)],
621+ playhead: u32,
622+ ) -> Vec<u8> {
623+ emit(dir, sources, lanes, &[], playhead)
624+ }
625+
491 /// Two sources, one under the project's own directory and one not, a clip626 /// Two sources, one under the project's own directory and one not, a clip
492 /// from each on the video lane, and an audio lane with a gap in the middle627 /// from each on the video lane, and an audio lane with a gap in the middle
493 /// -- the shape every case below starts from.628 /// -- the shape every case below starts from.
@@ -520,11 +655,11 @@ mod tests {
520 #[test]655 #[test]
521 fn relative_and_absolute_paths_round_trip() {656 fn relative_and_absolute_paths_round_trip() {
522 let (dir, sources, lanes) = doc();657 let (dir, sources, lanes) = doc();
523- let bytes = emit(&dir, &sources, &lanes, 12);658+ let bytes = flat(&dir, &sources, &lanes, 12);
524 assert_eq!(659 assert_eq!(
525 String::from_utf8_lossy(&bytes),660 String::from_utf8_lossy(&bytes),
526- "edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\661+ "edith 5\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
527- video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n",662+ video 1 0 0 30 0 0 -\nvideo 1 30 10 20 1 1 -\naudio 1 0 0 30 0 0 -\n",
528 "the file under the project directory is written relative to it, \663 "the file under the project directory is written relative to it, \
529 each with the audio stream it plays"664 each with the audio stream it plays"
530 );665 );
@@ -536,7 +671,7 @@ mod tests {
536 );671 );
537 assert_eq!(back.playhead, 12);672 assert_eq!(back.playhead, 12);
538 // ...and emitting the parsed document reproduces the same bytes.673 // ...and emitting the parsed document reproduces the same bytes.
539- assert_eq!(emit(&dir, &back.sources, &back.lanes, back.playhead), bytes);674+ assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
540 }675 }
541 676
542 /// The whole of the bump: a project of any number of lanes writes and reads677 /// The whole of the bump: a project of any number of lanes writes and reads
@@ -555,17 +690,17 @@ mod tests {
555 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),690 (LaneKind::Video, vec![clip(40, 0, 10, 0, None)]),
556 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),691 (LaneKind::Audio, vec![clip(0, 0, 30, 0, Some(4))]),
557 ];692 ];
558- let bytes = emit(&dir, &sources, &lanes, 7);693+ let bytes = flat(&dir, &sources, &lanes, 7);
559 assert_eq!(694 assert_eq!(
560 String::from_utf8_lossy(&bytes),695 String::from_utf8_lossy(&bytes),
561- "edith 4\nplayhead 7\nsource 0 a.mp4\n\696+ "edith 5\nplayhead 7\nsource 0 a.mp4\n\
562- video 1 0 0 30 0 4\naudio 1\nvideo 2 40 0 10 0 -\naudio 2 0 0 30 0 4\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",
563 "an empty lane is a line of its own; everything else is its clips"698 "an empty lane is a line of its own; everything else is its clips"
564 );699 );
565 let back = parse(&bytes, &dir).expect("parse");700 let back = parse(&bytes, &dir).expect("parse");
566 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");701 assert_eq!(back.lanes, lanes, "lane list, order and links all survive");
567 assert_eq!(back.playhead, 7);702 assert_eq!(back.playhead, 7);
568- assert_eq!(emit(&dir, &back.sources, &back.lanes, back.playhead), bytes);703+ assert_eq!(flat(&dir, &back.sources, &back.lanes, back.playhead), bytes);
569 704
570 // A lane number may not skip one of its kind: that lane was declared by705 // A lane number may not skip one of its kind: that lane was declared by
571 // nothing, and the refusal names it.706 // nothing, and the refusal names it.
@@ -604,10 +739,193 @@ mod tests {
604 );739 );
605 }740 }
606 741
742+ /// One band, spelled the way an eq line spells it.
743+ fn band_of(freq_hz: f32, gain_db: f32, q: f32, kind: BandKind) -> Band {
744+ Band {
745+ freq_hz,
746+ gain_db,
747+ q,
748+ kind,
749+ }
750+ }
751+
752+ /// The whole of the v5 bump: the clips name a shared equalizer table, the
753+ /// bytes are the ones documented at the top of this file, and every f32 in
754+ /// them comes back *bit* for bit -- which is what makes a re-save of a
755+ /// loaded project produce the same file rather than a drifting one.
756+ #[test]
757+ fn equalizers_round_trip_bit_exactly_and_are_shared() {
758+ let dir = PathBuf::from("/proj");
759+ let sources = vec![source("/proj/a.mp4", 0)];
760+ let eq = vec![
761+ EqParams {
762+ bands: vec![
763+ band_of(80.0, -3.0, 0.707, BandKind::LowShelf),
764+ band_of(1000.0, 4.5, 1.0, BandKind::Peak),
765+ ],
766+ },
767+ // The awkward ones: a value needing all 24 mantissa bits, one whose
768+ // shortest spelling is exponential, a subnormal, and a negative
769+ // zero -- plus the empty cascade, which is a setting like any other.
770+ EqParams {
771+ bands: vec![band_of(
772+ 16_777_215.0,
773+ -0.1,
774+ f32::MIN_POSITIVE / 3.0,
775+ BandKind::HighShelf,
776+ )],
777+ },
778+ EqParams { bands: Vec::new() },
779+ ];
780+ // Two clips share entry 0, so it is written once; one clip plays flat.
781+ let lanes = two(
782+ vec![
783+ Clip {
784+ eq: Some(0),
785+ ..clip(0, 0, 30, 0, Some(0))
786+ },
787+ Clip {
788+ eq: Some(1),
789+ ..clip(30, 10, 20, 0, None)
790+ },
791+ ],
792+ vec![
793+ Clip {
794+ eq: Some(0),
795+ ..clip(0, 0, 30, 0, Some(0))
796+ },
797+ Clip {
798+ eq: Some(2),
799+ ..clip(30, 0, 10, 0, None)
800+ },
801+ ],
802+ );
803+ let bytes = emit(&dir, &sources, &lanes, &eq, 0);
804+ assert_eq!(
805+ String::from_utf8_lossy(&bytes),
806+ "edith 5\nplayhead 0\nsource 0 a.mp4\n\
807+ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
808+ eq 16777215.0:-0.1:3.918315e-39:hs\n\
809+ 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",
812+ "the table comes before the clips, and a clip names a line of it"
813+ );
814+
815+ let back = parse(&bytes, &dir).expect("parse");
816+ assert_eq!(back.lanes, lanes, "every clip keeps the eq it named");
817+ for (i, (got, want)) in back.eq.iter().zip(&eq).enumerate() {
818+ for (b, (got, want)) in got.bands.iter().zip(&want.bands).enumerate() {
819+ assert_eq!(
820+ (
821+ got.freq_hz.to_bits(),
822+ got.gain_db.to_bits(),
823+ got.q.to_bits(),
824+ got.kind
825+ ),
826+ (
827+ want.freq_hz.to_bits(),
828+ want.gain_db.to_bits(),
829+ want.q.to_bits(),
830+ want.kind
831+ ),
832+ "eq {i} band {b} came back as other bits"
833+ );
834+ }
835+ }
836+ 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);
838+ }
839+
840+ /// The refusals the eq grammar adds, each naming its line.
841+ #[test]
842+ fn a_malformed_equalizer_names_its_line() {
843+ let dir = PathBuf::from("/proj");
844+ let head = "edith 5\nsource 0 a.mp4\n";
845+ for (file, want) in [
846+ (
847+ format!("{head}eq 80.0:0.0:0.707\nvideo 1 0 0 5 0 - 0\n"),
848+ "line 3: band wants 4 fields, found 3",
849+ ),
850+ (
851+ format!("{head}eq 80.0:0.0:0.707:notch\nvideo 1 0 0 5 0 - 0\n"),
852+ "line 3: \"notch\" is not a band shape",
853+ ),
854+ (
855+ format!("{head}eq 80.0:0.0:wide:pk\nvideo 1 0 0 5 0 - 0\n"),
856+ "line 3: \"wide\" is not a number",
857+ ),
858+ // Neither of the two values a coefficient cannot be built from, and
859+ // NaN would not even compare equal to itself on the way back.
860+ (
861+ format!("{head}eq 80.0:inf:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
862+ "line 3: \"inf\" is not a number",
863+ ),
864+ (
865+ format!("{head}eq NaN:0.0:0.707:pk\nvideo 1 0 0 5 0 - 0\n"),
866+ "line 3: \"NaN\" is not a number",
867+ ),
868+ (
869+ format!("{head}eq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 - 1\n"),
870+ "line 4: clip names eq 1 of 1",
871+ ),
872+ (
873+ format!("{head}video 1 0 0 5 0 - 0\n"),
874+ "line 3: clip names eq 0 of 0",
875+ ),
876+ // A clip's eq field is not optional in v5, and the table has to be
877+ // declared before the clip that names it.
878+ (
879+ format!("{head}video 1 0 0 5 0 -\n"),
880+ "line 3: clip wants 6 fields, found 5",
881+ ),
882+ (
883+ format!("{head}video 1 0 0 5 0 - -\neq 80.0:0.0:0.707:pk\n"),
884+ "line 4: eq after a clip",
885+ ),
886+ // ...and an eq line in a file that predates them is a corrupt file.
887+ (
888+ "edith 4\nsource 0 a.mp4\neq 80.0:0.0:0.707:pk\nvideo 1 0 0 5 0 -\n".to_string(),
889+ "line 3: unknown keyword \"eq\"",
890+ ),
891+ ] {
892+ assert_eq!(parse(file.as_bytes(), &dir).unwrap_err().to_string(), want);
893+ }
894+ }
895+
896+ /// A v4 file is a v5 one that equalizes nothing: it loads as it always did,
897+ /// and re-saving it writes the new magic, the `-` in every clip's eq field,
898+ /// and not one byte else.
899+ #[test]
900+ fn a_v4_file_equalizes_nothing() {
901+ let dir = PathBuf::from("/proj");
902+ let (_, sources, lanes) = doc();
903+ let v4 = b"edith 4\nplayhead 12\nsource 0 a.mp4\nsource 2 /elsewhere/b.mp4\n\
904+ video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n";
905+ let old = parse(v4, &dir).expect("v4 parses");
906+ assert_eq!(
907+ (&old.sources, &old.lanes, old.playhead),
908+ (&sources, &lanes, 12)
909+ );
910+ assert!(old.eq.is_empty(), "nothing before v5 equalizes anything");
911+ assert_eq!(
912+ 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"
915+ );
916+ // An empty lane's line is still the whole of that lane, eq or no eq.
917+ let empty = parse(
918+ b"edith 5\nsource 0 a.mp4\nvideo 1 0 0 5 0 - -\naudio 1\n",
919+ &dir,
920+ )
921+ .expect("parse");
922+ assert!(empty.lanes[1].1.is_empty());
923+ }
924+
607 /// The other half of the compatibility promise: a v3 file is a v4 one925 /// The other half of the compatibility promise: a v3 file is a v4 one
608 /// without the lane numbers, and a v2 file names no audio stream and means926 /// without the lane numbers, and a v2 file names no audio stream and means
609 /// stream 0 -- what the whole dialect could play. Both load as the two lanes927 /// stream 0 -- what the whole dialect could play. Both load as the two lanes
610- /// they always were, and saving either writes v4 with nothing else changed.928+ /// they always were, and saving either writes v5 with nothing else changed.
611 #[test]929 #[test]
612 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {930 fn a_v3_file_is_two_lanes_and_a_v2_one_is_stream_0() {
613 let dir = PathBuf::from("/proj");931 let dir = PathBuf::from("/proj");
@@ -622,13 +940,13 @@ mod tests {
622 &lanes,940 &lanes,
623 12941 12
624 ),942 ),
625- "a v3 file loads as exactly the state its v4 twin does"943+ "a v3 file loads as exactly the state its v5 twin does"
626 );944 );
627 // ...and re-saved it *is* that twin: the magic and a lane number per945 // ...and re-saved it *is* that twin: the magic and a lane number per
628 // clip line, and not one byte else.946 // clip line, and not one byte else.
629 assert_eq!(947 assert_eq!(
630- emit(&dir, &old.sources, &old.lanes, old.playhead),948+ flat(&dir, &old.sources, &old.lanes, old.playhead),
631- emit(&dir, &old.sources, &lanes, 12),949+ flat(&dir, &old.sources, &lanes, 12),
632 );950 );
633 951
634 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\952 let v2 = b"edith 2\nplayhead 12\nsource a.mp4\nsource /elsewhere/b.mp4\n\
@@ -640,20 +958,20 @@ mod tests {
640 );958 );
641 assert_eq!(back.lanes, lanes);959 assert_eq!(back.lanes, lanes);
642 960
643- let v4 = emit(&dir, &back.sources, &back.lanes, back.playhead);961+ let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
644 assert_eq!(962 assert_eq!(
645- String::from_utf8_lossy(&v4),963+ String::from_utf8_lossy(&v5),
646- "edith 4\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\964+ "edith 5\nplayhead 12\nsource 0 a.mp4\nsource 0 /elsewhere/b.mp4\n\
647- video 1 0 0 30 0 0\nvideo 1 30 10 20 1 1\naudio 1 0 0 30 0 0\n",965+ video 1 0 0 30 0 0 -\nvideo 1 30 10 20 1 1 -\naudio 1 0 0 30 0 0 -\n",
648 "a re-saved v2 project differs only by its version, the lane \966 "a re-saved v2 project differs only by its version, the lane \
649- numbers and the streams it always meant"967+ numbers, the streams it always meant and an equalizer it has none of"
650 );968 );
651- let again = parse(&v4, &dir).expect("v4 parses");969+ let again = parse(&v5, &dir).expect("v5 parses");
652 assert_eq!(again.sources, back.sources);970 assert_eq!(again.sources, back.sources);
653 }971 }
654 972
655 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of973 /// The compatibility promise: a v1 file is a fully-grouped, gapless pair of
656- /// lanes, and saving it again writes v4.974+ /// lanes, and saving it again writes v5.
657 #[test]975 #[test]
658 fn a_v1_file_loads_as_two_grouped_lanes() {976 fn a_v1_file_loads_as_two_grouped_lanes() {
659 let dir = PathBuf::from("/proj");977 let dir = PathBuf::from("/proj");
@@ -670,10 +988,10 @@ mod tests {
670 "one take per clip, on both lanes"988 "one take per clip, on both lanes"
671 );989 );
672 assert_eq!(back.playhead, 5);990 assert_eq!(back.playhead, 5);
673- // Saved again it is v4, and that round-trips to the same document.991+ // Saved again it is v5, and that round-trips to the same document.
674- let v4 = emit(&dir, &back.sources, &back.lanes, back.playhead);992+ let v5 = flat(&dir, &back.sources, &back.lanes, back.playhead);
675- assert!(v4.starts_with(b"edith 4\n"));993+ assert!(v5.starts_with(b"edith 5\n"));
676- let again = parse(&v4, &dir).expect("v4 parses");994+ let again = parse(&v5, &dir).expect("v5 parses");
677 assert_eq!(again.lanes, back.lanes);995 assert_eq!(again.lanes, back.lanes);
678 // A dialect may not be mixed: lane lines under v1, `clip` under v2.996 // A dialect may not be mixed: lane lines under v1, `clip` under v2.
679 for (bytes, want) in [997 for (bytes, want) in [
@@ -761,11 +1079,11 @@ mod tests {
761 path: source,1079 path: source,
762 audio_stream: 1,1080 audio_stream: 1,
763 };1081 };
764- save(&path, &[entry], &two(one.to_vec(), one.to_vec()), 0).expect("save");1082+ save(&path, &[entry], &two(one.to_vec(), one.to_vec()), &[], 0).expect("save");
765 let bytes = std::fs::read(&path).expect("read back");1083 let bytes = std::fs::read(&path).expect("read back");
766 assert_eq!(1084 assert_eq!(
767 String::from_utf8_lossy(&bytes),1085 String::from_utf8_lossy(&bytes),
768- "edith 4\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 -\naudio 1 0 0 30 0 -\n"1086+ "edith 5\nplayhead 0\nsource 1 a.mp4\nvideo 1 0 0 30 0 - -\naudio 1 0 0 30 0 - -\n"
769 );1087 );
770 // Loading rejoins the *given* directory, so the file is reached by the1088 // Loading rejoins the *given* directory, so the file is reached by the
771 // way the project was opened -- the same file, through the link, still1089 // way the project was opened -- the same file, through the link, still
@@ -788,7 +1106,7 @@ mod tests {
788 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),1106 path: PathBuf::from(OsString::from_vec(b"/proj/we\nird 100%\xff.mp4".to_vec())),
789 audio_stream: 0,1107 audio_stream: 0,
790 };1108 };
791- let bytes = emit(1109+ let bytes = flat(
792 &dir,1110 &dir,
793 &[nasty.clone()],1111 &[nasty.clone()],
794 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),1112 &two(vec![clip(0, 0, 5, 0, None)], Vec::new()),
@@ -809,10 +1127,10 @@ mod tests {
809 #[test]1127 #[test]
810 fn a_wrong_first_line_is_refused_by_name() {1128 fn a_wrong_first_line_is_refused_by_name() {
811 let dir = PathBuf::from("/proj");1129 let dir = PathBuf::from("/proj");
812- let err = parse(b"edith 5\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)1130+ let err = parse(b"edith 6\nsource 0 a.mp4\nvideo 0 0 5 0 -\n", &dir)
813 .unwrap_err()1131 .unwrap_err()
814 .to_string();1132 .to_string();
815- assert_eq!(err, "line 1: unsupported version 5");1133+ assert_eq!(err, "line 1: unsupported version 6");
816 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {1134 for junk in [&b""[..], b"{}\n", b"source a.mp4\n"] {
817 assert_eq!(1135 assert_eq!(
818 parse(junk, &dir).unwrap_err().to_string(),1136 parse(junk, &dir).unwrap_err().to_string(),
@@ -891,7 +1209,7 @@ mod tests {
891 #[test]1209 #[test]
892 fn truncations_never_panic() {1210 fn truncations_never_panic() {
893 let (dir, sources, lanes) = doc();1211 let (dir, sources, lanes) = doc();
894- let bytes = emit(&dir, &sources, &lanes, 12);1212+ let bytes = flat(&dir, &sources, &lanes, 12);
895 for cut in 0..bytes.len() {1213 for cut in 0..bytes.len() {
896 let _ = parse(&bytes[..cut], &dir);1214 let _ = parse(&bytes[..cut], &dir);
897 // ...and the same file with a byte lopped off the front, which1215 // ...and the same file with a byte lopped off the front, which
crates/engine/src/playback.rsmodified+5 -3
@@ -246,7 +246,7 @@ impl PlaybackSession {
246 }246 }
247 247
248 let playhead = doc.playhead;248 let playhead = doc.playhead;
249- let project = Project::from_parts(doc.sources, doc.lanes)?;249+ let project = Project::from_parts(doc.sources, doc.lanes, doc.eq)?;
250 let span = project.span_at(Lane::V1, 0).expect("never empty");250 let span = project.span_at(Lane::V1, 0).expect("never empty");
251 // Last, because it is the one thing here that cannot be taken back: the251 // Last, because it is the one thing here that cannot be taken back: the
252 // feeder thread outlives the `Audio` value (it holds its own clones) and252 // feeder thread outlives the `Audio` value (it holds its own clones) and
@@ -300,10 +300,10 @@ impl PlaybackSession {
300 /// [`crate::edith`]). Sources no clip plays from are left out, and the300 /// [`crate::edith`]). Sources no clip plays from are left out, and the
301 /// playhead is saved with it so a reopened project resumes where it stood.301 /// playhead is saved with it so a reopened project resumes where it stood.
302 pub fn save_project(&self, path: &Path) -> crate::Result<()> {302 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
303- let (sources, lanes) = self.project.without_orphan_sources();303+ let (sources, lanes, eq) = self.project.without_orphan_sources();
304 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)304 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
305 .min(self.project.timeline_frames().saturating_sub(1));305 .min(self.project.timeline_frames().saturating_sub(1));
306- crate::edith::save(path, &sources, &lanes, playhead)306+ crate::edith::save(path, &sources, &lanes, &eq, playhead)
307 }307 }
308 308
309 /// The next decoded frame, its `index` rewritten from a source frame to a309 /// The next decoded frame, its `index` rewritten from a source frame to a
@@ -537,6 +537,7 @@ impl PlaybackSession {
537 out_frame: frames.max(1),537 out_frame: frames.max(1),
538 source,538 source,
539 link: None,539 link: None,
540+ eq: None,
540 };541 };
541 // Which lane a source may land on is decided here and only here, so a542 // Which lane a source may land on is decided here and only here, so a
542 // front-end never has to make the same call twice: a file with no543 // front-end never has to make the same call twice: a file with no
@@ -643,6 +644,7 @@ impl PlaybackSession {
643 out_frame: frames,644 out_frame: frames,
644 source,645 source,
645 link: None,646 link: None,
647+ eq: None,
646 },648 },
647 );649 );
648 // Same reason as a video import: the running audio worker's segment650 // Same reason as a video import: the running audio worker's segment
crates/engine/src/project.rsmodified+290 -26
@@ -45,9 +45,19 @@
45 //! clipboard or inside an undo snapshot can never dangle. An index -- not an45 //! clipboard or inside an undo snapshot can never dangle. An index -- not an
46 //! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a46 //! `Arc<Path>` -- because [`Clip`] is `Copy`, which is what makes copy/paste a
47 //! plain assignment.47 //! plain assignment.
48+//!
49+//! A clip names its equalizer the same way, by index into a second append-only
50+//! table ([`Clip::eq`], [`Project::set_eq`]): the params are a `Vec` of bands
51+//! and a `Copy` clip cannot hold one. So an EQ'd clip that is split hands both
52+//! halves the same settings, a copy carries them, and an undo restores whatever
53+//! index the clip had. Only a *save* prunes the table
54+//! ([`Project::without_orphan_sources`]), for the reason an undone import
55+//! leaves its source entry behind: an index handed out is an index forever.
48 56
49 use std::path::{Path, PathBuf};57 use std::path::{Path, PathBuf};
50 58
59+use crate::eq::EqParams;
60+
51 /// A half-open `[in_frame, out_frame)` range of frames of source61 /// A half-open `[in_frame, out_frame)` range of frames of source
52 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).62 /// [`source`](Clip::source), placed at timeline frame [`start`](Clip::start).
53 /// Never empty.63 /// Never empty.
@@ -64,6 +74,13 @@ pub struct Clip {
64 /// Group id: clips sharing one were split from the same take. `None` for a74 /// Group id: clips sharing one were split from the same take. `None` for a
65 /// clip that belongs to no group.75 /// clip that belongs to no group.
66 pub link: Option<u32>,76 pub link: Option<u32>,
77+ /// Index into the project's equalizer table
78+ /// ([`Project::eq_of`]/[`Project::set_eq`]), or `None` for a clip that plays
79+ /// flat. An index -- not the params -- for [`Clip::source`]'s reason: this
80+ /// stays `Copy`, so an EQ'd clip survives a copy, a paste and an undo as a
81+ /// plain assignment. The table is append-only within a session, so an index
82+ /// on a clipboard clip or inside an undo snapshot can never dangle.
83+ pub eq: Option<u16>,
67 }84 }
68 85
69 impl Clip {86 impl Clip {
@@ -194,6 +211,11 @@ impl Span {
194 }211 }
195 }212 }
196 213
214+/// 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>);
218+
197 /// The edit list plus its undo history.219 /// The edit list plus its undo history.
198 #[derive(Clone, Debug)]220 #[derive(Clone, Debug)]
199 pub struct Project {221 pub struct Project {
@@ -202,6 +224,8 @@ pub struct Project {
202 /// In display order, which is the order [`Lane::ord`] counts in: the nth224 /// In display order, which is the order [`Lane::ord`] counts in: the nth
203 /// lane of a kind here is that kind's `ord` n. Never empty.225 /// lane of a kind here is that kind's `ord` n. Never empty.
204 lanes: Vec<LaneData>,226 lanes: Vec<LaneData>,
227+ /// Append-only, exactly as `sources` is: what [`Clip::eq`] indexes into.
228+ eq: Vec<EqParams>,
205 /// Snapshots pushed *before* each successful edit; `undo` pops one. The229 /// Snapshots pushed *before* each successful edit; `undo` pops one. The
206 /// whole lane list, so adding a lane undoes as well.230 /// whole lane list, so adding a lane undoes as well.
207 history: Vec<Vec<LaneData>>,231 history: Vec<Vec<LaneData>>,
@@ -222,12 +246,14 @@ impl Project {
222 out_frame: frame_count.max(1),246 out_frame: frame_count.max(1),
223 source: 0,247 source: 0,
224 link: Some(0),248 link: Some(0),
249+ eq: None,
225 };250 };
226 Self {251 Self {
227 // A file is opened on its first audio stream: nothing has picked252 // A file is opened on its first audio stream: nothing has picked
228 // one yet, and every file with audio at all has that one.253 // one yet, and every file with audio at all has that one.
229 sources: vec![Source::new(path, 0)],254 sources: vec![Source::new(path, 0)],
230 lanes: LaneData::two_lanes(vec![clip], vec![clip]),255 lanes: LaneData::two_lanes(vec![clip], vec![clip]),
256+ eq: Vec::new(),
231 history: Vec::new(),257 history: Vec::new(),
232 next_link: 1,258 next_link: 1,
233 }259 }
@@ -240,13 +266,17 @@ impl Project {
240 /// [`Project::undo`] is `false` until the first edit of the new session.266 /// [`Project::undo`] is `false` until the first edit of the new session.
241 /// This is the one door untrusted parts come in through, so every invariant267 /// This is the one door untrusted parts come in through, so every invariant
242 /// every other constructor keeps is checked here, by name and in release:268 /// every other constructor keeps is checked here, by name and in release:
243- /// every lane empty, an empty clip, a clip naming a source that is not269+ /// every lane empty, an empty clip, a clip naming a source (or an equalizer)
244- /// there, a clip whose end overflows, a lane that is unsorted or270+ /// that is not there, a clip whose end overflows, a lane that is unsorted or
245 /// self-overlapping, and the grouping rules of [`Clip::link`] below.271 /// self-overlapping, and the grouping rules of [`Clip::link`] below.
246 pub fn from_parts(272 pub fn from_parts(
247 sources: Vec<Source>,273 sources: Vec<Source>,
248 lanes: Vec<(LaneKind, Vec<Clip>)>,274 lanes: Vec<(LaneKind, Vec<Clip>)>,
275+ eq: Vec<EqParams>,
249 ) -> crate::Result<Self> {276 ) -> crate::Result<Self> {
277+ if let Some(bad) = eq.iter().position(|p| !finite(p)) {
278+ return Err(format!("eq {bad} holds a band that is not a finite number").into());
279+ }
250 if lanes.iter().all(|(_, clips)| clips.is_empty()) {280 if lanes.iter().all(|(_, clips)| clips.is_empty()) {
251 return Err("every lane is empty: that is not a project".into());281 return Err("every lane is empty: that is not a project".into());
252 }282 }
@@ -280,6 +310,15 @@ impl Project {
280 )310 )
281 .into());311 .into());
282 }312 }
313+ if c.eq.is_some_and(|i| usize::from(i) >= eq.len()) {
314+ return Err(format!(
315+ "{name} clip at {} names eq {} of {}",
316+ c.start,
317+ c.eq.unwrap_or_default(),
318+ eq.len()
319+ )
320+ .into());
321+ }
283 }322 }
284 if !sorted_disjoint(&data.clips) {323 if !sorted_disjoint(&data.clips) {
285 return Err(format!("the {name} lane is out of order or overlaps itself").into());324 return Err(format!("the {name} lane is out of order or overlaps itself").into());
@@ -300,6 +339,7 @@ impl Project {
300 .map(|s| Source::new(&s.path, s.audio_stream))339 .map(|s| Source::new(&s.path, s.audio_stream))
301 .collect(),340 .collect(),
302 lanes,341 lanes,
342+ eq,
303 history: Vec::new(),343 history: Vec::new(),
304 next_link,344 next_link,
305 })345 })
@@ -410,6 +450,7 @@ impl Project {
410 out_frame: frame_count.max(1),450 out_frame: frame_count.max(1),
411 source,451 source,
412 link: Some(self.new_link()),452 link: Some(self.new_link()),
453+ eq: None,
413 };454 };
414 for data in &mut self.lanes {455 for data in &mut self.lanes {
415 data.clips.push(clip);456 data.clips.push(clip);
@@ -426,11 +467,18 @@ impl Project {
426 /// emits the same bytes.467 /// emits the same bytes.
427 ///468 ///
428 /// Every lane comes out, in display order and with its kind: that is what a469 /// Every lane comes out, in display order and with its kind: that is what a
429- /// v4 `.edith` holds (empty lanes included) and what [`Project::from_parts`]470+ /// v5 `.edith` holds (empty lanes included) and what [`Project::from_parts`]
430 /// takes back.471 /// takes back.
431- pub fn without_orphan_sources(&self) -> (Vec<Source>, Vec<(LaneKind, Vec<Clip>)>) {472+ ///
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,
475+ /// and this is the one moment they can go -- the indexes that survive it are
476+ /// only the ones a clip names.
477+ pub fn without_orphan_sources(&self) -> Parts {
432 let mut moved = vec![None; self.sources.len()];478 let mut moved = vec![None; self.sources.len()];
433 let mut sources = Vec::new();479 let mut sources = Vec::new();
480+ let mut moved_eq = vec![None; self.eq.len()];
481+ let mut eq = Vec::new();
434 let mut lanes = self.lanes.clone();482 let mut lanes = self.lanes.clone();
435 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {483 for c in lanes.iter_mut().flat_map(|l| &mut l.clips) {
436 let old = c.source;484 let old = c.source;
@@ -442,13 +490,71 @@ impl Project {
442 sources.len() - 1490 sources.len() - 1
443 }491 }
444 };492 };
493+ if let Some(old) = c.eq.map(usize::from) {
494+ c.eq = Some(match moved_eq[old] {
495+ Some(new) => new,
496+ None => {
497+ eq.push(self.eq[old].clone());
498+ let new = (eq.len() - 1) as u16;
499+ moved_eq[old] = Some(new);
500+ new
501+ }
502+ });
503+ }
445 }504 }
446 (505 (
447 sources,506 sources,
448 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),507 lanes.into_iter().map(|l| (l.kind, l.clips)).collect(),
508+ eq,
449 )509 )
450 }510 }
451 511
512+ /// What the clip at `idx` of `lane` plays through, or `None` for one that
513+ /// plays flat (and for an index that is not there) -- what a feeder and an
514+ /// export ask before they build an [`crate::eq::EqState`].
515+ pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
516+ self.eq.get(usize::from(self.lane(lane).get(idx)?.eq?))
517+ }
518+
519+ /// Give the clip at `idx` of `lane` these equalizer settings, or `None` to
520+ /// take them off. One undo step, like every other edit. `false` -- and no
521+ /// history -- for an index that is not there and for params holding a value
522+ /// that is not finite, which is the one thing the file format could not
523+ /// write and read back.
524+ ///
525+ /// Settings equal to ones already in the table share their entry, so a
526+ /// project that puts the same curve on twenty clips writes it once.
527+ pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
528+ if idx >= self.lane(lane).len() {
529+ return false;
530+ }
531+ let slot = match params {
532+ None => None,
533+ Some(params) => {
534+ if !finite(&params) {
535+ return false;
536+ }
537+ Some(match self.eq.iter().position(|p| *p == params) {
538+ Some(at) => at as u16,
539+ // ponytail: the table is append-only within a session (see
540+ // the module docs) and `Clip::eq` is a u16, so the 65535th
541+ // *distinct* setting of one session is refused rather than
542+ // silently aliased. Upgrade path if a UI ever drags a slider
543+ // that far: widen `Clip::eq` to u32 (Clip has the room) or
544+ // snapshot the table into the history and compact it here.
545+ None if self.eq.len() >= usize::from(u16::MAX) => return false,
546+ None => {
547+ self.eq.push(params);
548+ (self.eq.len() - 1) as u16
549+ }
550+ })
551+ }
552+ };
553+ self.snapshot();
554+ self.lane_mut(lane).expect("checked above")[idx].eq = slot;
555+ true
556+ }
557+
452 /// Length of the timeline in frames: where the *last* lane runs out. A lane558 /// Length of the timeline in frames: where the *last* lane runs out. A lane
453 /// that ends early is a trailing gap in that lane, not a shorter timeline.559 /// that ends early is a trailing gap in that lane, not a shorter timeline.
454 pub fn timeline_frames(&self) -> u32 {560 pub fn timeline_frames(&self) -> u32 {
@@ -857,6 +963,16 @@ fn joinable(clips: &[Clip], frame: u32) -> Option<usize> {
857 /// The lane invariant: sorted by `start`, no two placements overlapping, no963 /// The lane invariant: sorted by `start`, no two placements overlapping, no
858 /// empty placement. Checked at every constructor and asserted after every964 /// empty placement. Checked at every constructor and asserted after every
859 /// mutation -- the offset model is only tractable while it holds.965 /// mutation -- the offset model is only tractable while it holds.
966+/// The one thing an equalizer setting may not be: a value the text format
967+/// cannot write and read back as itself. Checked wherever params come in, so
968+/// what an edit produces is always what a save writes and a load reads.
969+fn finite(params: &EqParams) -> bool {
970+ params
971+ .bands
972+ .iter()
973+ .all(|b| b.freq_hz.is_finite() && b.gain_db.is_finite() && b.q.is_finite())
974+}
975+
860 fn sorted_disjoint(clips: &[Clip]) -> bool {976 fn sorted_disjoint(clips: &[Clip]) -> bool {
861 clips.iter().all(|c| c.out_frame > c.in_frame)977 clips.iter().all(|c| c.out_frame > c.in_frame)
862 && clips.windows(2).all(|w| w[0].end() <= w[1].start)978 && clips.windows(2).all(|w| w[0].end() <= w[1].start)
@@ -993,6 +1109,20 @@ mod tests {
993 out_frame,1109 out_frame,
994 source,1110 source,
995 link: None,1111 link: None,
1112+ eq: None,
1113+ }
1114+ }
1115+
1116+ /// A recognisable equalizer setting: one peak band, `n` telling two of them
1117+ /// apart -- which is what makes the table's dedup and its prune visible.
1118+ fn band_at(n: u32) -> EqParams {
1119+ EqParams {
1120+ bands: vec![crate::eq::Band {
1121+ freq_hz: 1000.0,
1122+ gain_db: f64::from(n) as f32 * 1.5,
1123+ q: 0.707,
1124+ kind: crate::eq::BandKind::Peak,
1125+ }],
996 }1126 }
997 }1127 }
998 1128
@@ -1173,6 +1303,7 @@ mod tests {
1173 out_frame: 102,1303 out_frame: 102,
1174 source: 0,1304 source: 0,
1175 link: None,1305 link: None,
1306+ eq: None,
1176 };1307 };
1177 1308
1178 #[test]1309 #[test]
@@ -1590,8 +1721,9 @@ mod tests {
1590 // Import a second file, undo it: source 1 is now an orphan.1721 // Import a second file, undo it: source 1 is now an orphan.
1591 let mut p = two_sources();1722 let mut p = two_sources();
1592 assert!(p.undo());1723 assert!(p.undo());
1593- let (sources, lanes) = p.without_orphan_sources();1724+ let (sources, lanes, eq) = p.without_orphan_sources();
1594 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");1725 assert_eq!(sources, vec![Source::new(FILE, 0)], "the orphan is gone");
1726+ assert!(eq.is_empty(), "and a project with no equalizer writes none");
1595 assert_eq!(1727 assert_eq!(
1596 lanes,1728 lanes,
1597 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),1729 two(three().clips().to_vec(), three().lane(Lane::A1).to_vec()),
@@ -1604,7 +1736,7 @@ mod tests {
1604 assert_eq!(p.import(FILE2, 0), 1);1736 assert_eq!(p.import(FILE2, 0), 1);
1605 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);1737 assert_eq!(p.import("/nonexistent/c.mp4", 0), 2);
1606 assert!(p.append_clip(2, 4));1738 assert!(p.append_clip(2, 4));
1607- let (sources, lanes) = p.without_orphan_sources();1739+ let (sources, lanes, eq) = p.without_orphan_sources();
1608 assert_eq!(1740 assert_eq!(
1609 sources,1741 sources,
1610 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]1742 vec![Source::new(FILE, 0), Source::new("/nonexistent/c.mp4", 0)]
@@ -1614,25 +1746,110 @@ mod tests {
1614 [0, 1]1746 [0, 1]
1615 );1747 );
1616 // ...and what comes out is loadable, with the same timeline.1748 // ...and what comes out is loadable, with the same timeline.
1617- let reloaded = Project::from_parts(sources, lanes).expect("from_parts");1749+ let reloaded = Project::from_parts(sources, lanes, eq).expect("from_parts");
1618 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());1750 assert_eq!(reloaded.timeline_frames(), p.timeline_frames());
1619 assert_eq!(reloaded.sources().len(), 2);1751 assert_eq!(reloaded.sources().len(), 2);
1620 }1752 }
1621 1753
1754+ /// A clip's equalizer is the clip's: it survives every edit that copies a
1755+ /// placement, and it comes back with an undo.
1756+ #[test]
1757+ fn an_equalizer_follows_the_clip_through_split_copy_and_undo() {
1758+ let mut p = three();
1759+ assert!(p.eq_of(Lane::V1, 0).is_none(), "a fresh clip plays flat");
1760+ assert!(p.set_eq(Lane::A1, 0, Some(band_at(2))));
1761+ assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
1762+ assert!(
1763+ p.eq_of(Lane::V1, 0).is_none(),
1764+ "one clip, not the lane above"
1765+ );
1766+
1767+ // Cutting an EQ'd clip must not silence half of it: both halves inherit.
1768+ assert!(p.split(1));
1769+ assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
1770+ assert_eq!(p.eq_of(Lane::A1, 1), Some(&band_at(2)));
1771+ assert!(p.eq_of(Lane::A1, 2).is_none(), "the clip after it is flat");
1772+
1773+ // A clipboard copy carries it -- onto another lane, at that.
1774+ let copied = p.lane(Lane::A1)[1];
1775+ assert!(p.place(Lane::V1, 20, copied));
1776+ assert_eq!(p.eq_of(Lane::V1, 4), Some(&band_at(2)));
1777+ assert!(p.undo());
1778+ assert_eq!(p.lane(Lane::V1).len(), 4, "the placement came back off");
1779+
1780+ // ...and a change to one is one undo step, in both directions.
1781+ assert!(p.set_eq(Lane::A1, 0, Some(band_at(5))));
1782+ assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(5)));
1783+ assert!(p.undo());
1784+ assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
1785+ assert!(p.set_eq(Lane::A1, 0, None), "and taking it off is an edit");
1786+ assert!(p.eq_of(Lane::A1, 0).is_none());
1787+ assert!(p.undo());
1788+ assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
1789+
1790+ // Two refusals, neither of which costs an undo step.
1791+ let mut nan = band_at(1);
1792+ nan.bands[0].q = f32::INFINITY;
1793+ assert!(!p.set_eq(Lane::A1, 99, Some(band_at(1))), "no clip there");
1794+ assert!(!p.set_eq(Lane::A1, 0, Some(nan)), "not a finite band");
1795+ assert_eq!(p.eq_of(Lane::A1, 0), Some(&band_at(2)));
1796+ assert!(p.undo());
1797+ assert_eq!(
1798+ p.lane(Lane::A1).len(),
1799+ 3,
1800+ "one step back is before the split"
1801+ );
1802+ assert!(p.undo());
1803+ assert!(
1804+ p.eq_of(Lane::A1, 0).is_none(),
1805+ "and the next is before the setting: the refusals pushed none"
1806+ );
1807+ }
1808+
1809+ /// The table is append-only within a session, exactly as the sources are, so
1810+ /// an undone setting is still in it -- and a save is where it goes.
1811+ #[test]
1812+ fn an_undone_equalizer_is_pruned_when_the_project_is_saved() {
1813+ let mut p = three();
1814+ assert!(p.set_eq(Lane::V1, 0, Some(band_at(1))));
1815+ assert!(p.set_eq(Lane::V1, 0, Some(band_at(2))));
1816+ assert!(p.undo(), "back to the first setting");
1817+ assert_eq!(p.eq_of(Lane::V1, 0), Some(&band_at(1)));
1818+
1819+ let (_, lanes, eq) = p.without_orphan_sources();
1820+ assert_eq!(eq, vec![band_at(1)], "what nothing plays is not written");
1821+ assert_eq!(lanes[0].1[0].eq, Some(0), "and the survivor renumbers");
1822+ assert_eq!(lanes[0].1[1].eq, None);
1823+
1824+ // One curve on three clips is one entry: settings that are equal share.
1825+ assert!(p.set_eq(Lane::V1, 1, Some(band_at(1))));
1826+ assert!(p.set_eq(Lane::A1, 2, Some(band_at(1))));
1827+ let (_, lanes, eq) = p.without_orphan_sources();
1828+ assert_eq!(eq.len(), 1, "equal settings share their entry");
1829+ assert_eq!(lanes[1].1[2].eq, Some(0));
1830+ reloads(&p, "an equalizer that outlived an undo");
1831+ }
1832+
1622 #[test]1833 #[test]
1623 fn from_parts_has_no_history_and_checks_the_invariants() {1834 fn from_parts_has_no_history_and_checks_the_invariants() {
1624- let (sources, lanes) = three().without_orphan_sources();1835+ let (sources, lanes, eq) = three().without_orphan_sources();
1625 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());1836 let (video, audio) = (lanes[0].1.clone(), lanes[1].1.clone());
1626- let mut p = Project::from_parts(sources.clone(), lanes.clone()).expect("valid parts");1837+ let mut p =
1838+ Project::from_parts(sources.clone(), lanes.clone(), eq.clone()).expect("valid parts");
1627 assert_eq!(p.clips(), three().clips());1839 assert_eq!(p.clips(), three().clips());
1628 assert!(!p.undo(), "a loaded project has nothing to undo");1840 assert!(!p.undo(), "a loaded project has nothing to undo");
1629 assert!(p.split(4), "...and is editable from there");1841 assert!(p.split(4), "...and is editable from there");
1630 assert!(p.undo());1842 assert!(p.undo());
1631 1843
1632 // A lane may be empty; every lane may not, and neither may no lane.1844 // A lane may be empty; every lane may not, and neither may no lane.
1633- assert!(Project::from_parts(sources.clone(), two(video.clone(), Vec::new())).is_ok());1845+ assert!(
1634- assert!(Project::from_parts(sources.clone(), two(Vec::new(), Vec::new())).is_err());1846+ Project::from_parts(sources.clone(), two(video.clone(), Vec::new()), Vec::new())
1635- assert!(Project::from_parts(sources.clone(), Vec::new()).is_err());1847+ .is_ok()
1848+ );
1849+ assert!(
1850+ Project::from_parts(sources.clone(), two(Vec::new(), Vec::new()), Vec::new()).is_err()
1851+ );
1852+ assert!(Project::from_parts(sources.clone(), Vec::new(), Vec::new()).is_err());
1636 let bad: [Vec<Clip>; 5] = [1853 let bad: [Vec<Clip>; 5] = [
1637 vec![clip(0, 0, 3, 1)], // source that is not there1854 vec![clip(0, 0, 3, 1)], // source that is not there
1638 vec![clip(0, 3, 3, 0)], // empty clip1855 vec![clip(0, 3, 3, 0)], // empty clip
@@ -1642,11 +1859,17 @@ mod tests {
1642 ];1859 ];
1643 for clips in bad {1860 for clips in bad {
1644 assert!(1861 assert!(
1645- Project::from_parts(sources.clone(), two(clips.clone(), Vec::new())).is_err(),1862+ Project::from_parts(sources.clone(), two(clips.clone(), Vec::new()), Vec::new())
1863+ .is_err(),
1646 "{clips:?}"1864 "{clips:?}"
1647 );1865 );
1648 assert!(1866 assert!(
1649- Project::from_parts(sources.clone(), two(video.clone(), clips.clone())).is_err()1867+ Project::from_parts(
1868+ sources.clone(),
1869+ two(video.clone(), clips.clone()),
1870+ Vec::new()
1871+ )
1872+ .is_err()
1650 );1873 );
1651 // ...and on a third lane, which is checked by the same walk.1874 // ...and on a third lane, which is checked by the same walk.
1652 assert!(1875 assert!(
@@ -1656,13 +1879,31 @@ mod tests {
1656 (LaneKind::Video, video.clone()),1879 (LaneKind::Video, video.clone()),
1657 (LaneKind::Audio, audio.clone()),1880 (LaneKind::Audio, audio.clone()),
1658 (LaneKind::Video, clips),1881 (LaneKind::Video, clips),
1659- ]1882+ ],
1883+ Vec::new()
1660 )1884 )
1661 .is_err()1885 .is_err()
1662 );1886 );
1663 }1887 }
1888+ // An equalizer index no table entry answers, and a table entry the file
1889+ // format could not have written, are refused at this door too.
1890+ let eqd = |i: u16| {
1891+ vec![Clip {
1892+ eq: Some(i),
1893+ ..video[0]
1894+ }]
1895+ };
1896+ assert!(Project::from_parts(sources.clone(), two(eqd(0), Vec::new()), Vec::new()).is_err());
1897+ let mut nan = band_at(1);
1898+ 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");
1903+ assert_eq!(loaded.eq_of(Lane::V1, 0), Some(&band_at(1)));
1904+
1664 // Group ids survive a load, and the next split gets a fresh one.1905 // Group ids survive a load, and the next split gets a fresh one.
1665- let mut p = Project::from_parts(sources, lanes).expect("valid parts");1906+ let mut p = Project::from_parts(sources, lanes, eq).expect("valid parts");
1666 assert!(p.split(4));1907 assert!(p.split(4));
1667 assert!(p.clips().iter().all(|c| c.link.is_some()));1908 assert!(p.clips().iter().all(|c| c.link.is_some()));
1668 }1909 }
@@ -1684,11 +1925,12 @@ mod tests {
1684 out_frame,1925 out_frame,
1685 source: 0,1926 source: 0,
1686 link: Some(link),1927 link: Some(link),
1928+ eq: None,
1687 };1929 };
1688 1930
1689 // The door: named errors, one per cause.1931 // The door: named errors, one per cause.
1690 let err = |video: Vec<Clip>, audio: Vec<Clip>| {1932 let err = |video: Vec<Clip>, audio: Vec<Clip>| {
1691- Project::from_parts(sources.clone(), two(video, audio))1933+ Project::from_parts(sources.clone(), two(video, audio), Vec::new())
1692 .expect_err("refused")1934 .expect_err("refused")
1693 .to_string()1935 .to_string()
1694 };1936 };
@@ -1705,9 +1947,9 @@ mod tests {
1705 // A one-sided link is *not* an error: it is what a lift leaves behind.1947 // A one-sided link is *not* an error: it is what a lift leaves behind.
1706 let mut p = Project::single(FILE, 9);1948 let mut p = Project::single(FILE, 9);
1707 assert!(p.lift(Lane::A1, 0));1949 assert!(p.lift(Lane::A1, 0));
1708- let (sources, lanes) = p.clone().without_orphan_sources();1950+ let (sources, lanes, eq) = p.clone().without_orphan_sources();
1709 assert!(1951 assert!(
1710- Project::from_parts(sources, lanes).is_ok(),1952+ Project::from_parts(sources, lanes, eq).is_ok(),
1711 "a lifted lane's project has to load again"1953 "a lifted lane's project has to load again"
1712 );1954 );
1713 1955
@@ -1776,7 +2018,7 @@ mod tests {
1776 &p,2018 &p,
1777 "a second audio stream of the same file, placed and split",2019 "a second audio stream of the same file, placed and split",
1778 );2020 );
1779- let (sources, _) = p.without_orphan_sources();2021+ let (sources, ..) = p.without_orphan_sources();
1780 assert_eq!(2022 assert_eq!(
1781 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),2023 sources.iter().map(|s| s.audio_stream).collect::<Vec<_>>(),
1782 [0, 1],2024 [0, 1],
@@ -1809,7 +2051,7 @@ mod tests {
1809 .unwrap_or(&clip(0, 0, 5, 0));2051 .unwrap_or(&clip(0, 0, 5, 0));
1810 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };2052 let lane = if next(2) == 0 { Lane::V1 } else { Lane::A1 };
1811 let idx = next(4) as usize;2053 let idx = next(4) as usize;
1812- let _ = match next(9) {2054+ let _ = match next(11) {
1813 0 => p.split(frame),2055 0 => p.split(frame),
1814 1 => p.regroup(frame),2056 1 => p.regroup(frame),
1815 2 => p.lift(lane, idx),2057 2 => p.lift(lane, idx),
@@ -1818,6 +2060,11 @@ mod tests {
1818 5 => p.ripple_delete(frame, next(9)),2060 5 => p.ripple_delete(frame, next(9)),
1819 6 => p.delete(idx),2061 6 => p.delete(idx),
1820 7 => p.undo(),2062 7 => p.undo(),
2063+ // An equalizer put on and taken off in the mix: what a clip
2064+ // carries has to reload with it, and the entries an undo
2065+ // orphans must not come back out of the prune.
2066+ 8 => p.set_eq(lane, idx, Some(band_at(next(4)))),
2067+ 9 => p.set_eq(lane, idx, None),
1821 _ => p.append_clip(0, 1 + next(9)),2068 _ => p.append_clip(0, 1 + next(9)),
1822 };2069 };
1823 reloads(&p, &format!("seed {seed}, step {step}"));2070 reloads(&p, &format!("seed {seed}, step {step}"));
@@ -1829,8 +2076,8 @@ mod tests {
1829 /// handed back to the constructor a load goes through -- every lane of them,2076 /// handed back to the constructor a load goes through -- every lane of them,
1830 /// and the reloaded timeline has to be the same lanes in the same order.2077 /// and the reloaded timeline has to be the same lanes in the same order.
1831 fn reloads(p: &Project, what: &str) {2078 fn reloads(p: &Project, what: &str) {
1832- let (sources, lanes) = p.clone().without_orphan_sources();2079+ let (sources, lanes, eq) = p.clone().without_orphan_sources();
1833- match Project::from_parts(sources, lanes) {2080+ match Project::from_parts(sources, lanes, eq) {
1834 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),2081 Err(e) => panic!("{what}: saved but would not load: {e}\n{:?}", p.lanes),
1835 Ok(back) => {2082 Ok(back) => {
1836 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");2083 assert_eq!(back.lanes(), p.lanes(), "{what}: the lane list changed");
@@ -1840,6 +2087,19 @@ mod tests {
1840 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()2087 p.lanes().into_iter().map(|l| p.lane_spans(l)).collect()
1841 };2088 };
1842 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");2089 assert_eq!(spans(&back), spans(p), "{what}: the placements changed");
2090+ // The prune renumbers the eq table too, so what has to survive
2091+ // is the settings themselves, clip by clip.
2092+ let eqs = |p: &Project| -> Vec<Vec<Option<EqParams>>> {
2093+ p.lanes()
2094+ .into_iter()
2095+ .map(|l| {
2096+ (0..p.lane(l).len())
2097+ .map(|i| p.eq_of(l, i).cloned())
2098+ .collect()
2099+ })
2100+ .collect()
2101+ };
2102+ assert_eq!(eqs(&back), eqs(p), "{what}: the equalizers changed");
1843 }2103 }
1844 }2104 }
1845 }2105 }
@@ -1994,6 +2254,7 @@ mod tests {
1994 out_frame,2254 out_frame,
1995 source: 0,2255 source: 0,
1996 link: Some(link),2256 link: Some(link),
2257+ eq: None,
1997 };2258 };
1998 let lanes = vec![2259 let lanes = vec![
1999 LaneData {2260 LaneData {
@@ -2025,6 +2286,7 @@ mod tests {
2025 out_frame: end,2286 out_frame: end,
2026 source: 0,2287 source: 0,
2027 link: Some(link),2288 link: Some(link),
2289+ eq: None,
2028 };2290 };
2029 // V1, A1, V2, A2 -- one take over [0, 4) on all four.2291 // V1, A1, V2, A2 -- one take over [0, 4) on all four.
2030 let kinds = [2292 let kinds = [
@@ -2072,7 +2334,7 @@ mod tests {
2072 let v2 = p.add_lane(LaneKind::Video);2334 let v2 = p.add_lane(LaneKind::Video);
2073 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));2335 assert!(p.place(v2, 4, clip(0, 20, 32, 0)));
2074 let a2 = p.add_lane(LaneKind::Audio);2336 let a2 = p.add_lane(LaneKind::Audio);
2075- let (sources, lanes) = p.without_orphan_sources();2337+ let (sources, lanes, eq) = p.without_orphan_sources();
2076 assert_eq!(2338 assert_eq!(
2077 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),2339 lanes.iter().map(|(k, _)| *k).collect::<Vec<_>>(),
2078 [2340 [
@@ -2086,7 +2348,7 @@ mod tests {
2086 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");2348 assert_eq!(lanes[2].1, p.lane(v2), "V2's clips are written");
2087 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");2349 assert!(lanes[3].1.is_empty(), "and the empty A2 is still a lane");
2088 // ...and all four load again as the same four.2350 // ...and all four load again as the same four.
2089- let back = Project::from_parts(sources, lanes).expect("four lanes load");2351+ let back = Project::from_parts(sources, lanes, eq).expect("four lanes load");
2090 assert_eq!(back.lanes(), p.lanes());2352 assert_eq!(back.lanes(), p.lanes());
2091 assert_eq!(back.lane(a2), p.lane(a2));2353 assert_eq!(back.lane(a2), p.lane(a2));
2092 2354
@@ -2128,7 +2390,9 @@ mod tests {
2128 .unwrap_or(&clip(0, 0, 5, 0));2390 .unwrap_or(&clip(0, 0, 5, 0));
2129 let lane = lanes[next(3) as usize];2391 let lane = lanes[next(3) as usize];
2130 let idx = next(4) as usize;2392 let idx = next(4) as usize;
2131- let _ = match next(10) {2393+ let _ = match next(12) {
2394+ 10 => p.set_eq(lane, idx, Some(band_at(next(4)))),
2395+ 11 => p.set_eq(lane, idx, None),
2132 0 => p.split(frame),2396 0 => p.split(frame),
2133 1 => p.regroup(frame),2397 1 => p.regroup(frame),
2134 2 => p.lift(lane, idx),2398 2 => p.lift(lane, idx),
crates/engine/tests/audio_export.rsmodified+3 -0
@@ -64,6 +64,7 @@ fn mixed_project() -> Project {
64 out_frame: 30,64 out_frame: 30,
65 source,65 source,
66 link: None,66 link: None,
67+ eq: None,
67 };68 };
68 Project::from_parts(69 Project::from_parts(
69 vec![70 vec![
@@ -82,10 +83,12 @@ fn mixed_project() -> Project {
82 out_frame: 90,83 out_frame: 90,
83 source: 0,84 source: 0,
84 link: None,85 link: None,
86+ eq: None,
85 }],87 }],
86 ),88 ),
87 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),89 (LaneKind::Audio, vec![clip(0, 0), clip(60, 1)]),
88 ],90 ],
91+ Vec::new(),
89 )92 )
90 .expect("a two-source project with a hole in the audio lane")93 .expect("a two-source project with a hole in the audio lane")
91 }94 }
crates/engine/tests/export.rsmodified+2 -0
@@ -191,6 +191,7 @@ fn exports_the_audio_stream_the_timeline_plays() {
191 out_frame: meta.frame_count,191 out_frame: meta.frame_count,
192 source: 0,192 source: 0,
193 link: Some(0),193 link: Some(0),
194+ eq: None,
194 };195 };
195 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz196 // Stream 1 is the 22.05 kHz mono French track; stream 0 is 44.1 kHz
196 // stereo. A project may only hold streams that agree, so this timeline is197 // 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() {
204 (engine::project::LaneKind::Video, vec![whole]),205 (engine::project::LaneKind::Video, vec![whole]),
205 (engine::project::LaneKind::Audio, vec![whole]),206 (engine::project::LaneKind::Audio, vec![whole]),
206 ],207 ],
208+ Vec::new(),
207 )209 )
208 .expect("a one-source project on stream 1");210 .expect("a one-source project on stream 1");
209 let out = out_path("stream1");211 let out = out_path("stream1");
crates/engine/tests/saveload.rsmodified+45 -8
@@ -126,9 +126,9 @@ fn shape(session: &PlaybackSession) -> (Vec<(f64, f64, usize)>, Vec<Source>, f64
126 126
127 /// The version-1 promise: a file written before the lanes existed still opens,127 /// The version-1 promise: a file written before the lanes existed still opens,
128 /// as one grouped video+audio pair per clip laid end to end, and saving it128 /// as one grouped video+audio pair per clip laid end to end, and saving it
129-/// again writes version 4 -- which reopens as the same timeline.129+/// again writes version 5 -- which reopens as the same timeline.
130 #[test]130 #[test]
131-fn a_version_1_project_loads_fully_grouped_and_saves_as_version_4() {131+fn a_version_1_project_loads_fully_grouped_and_saves_as_version_5() {
132 let dir = scratch("v1");132 let dir = scratch("v1");
133 copy_in(&dir, "test_av.mp4");133 copy_in(&dir, "test_av.mp4");
134 let path = dir.join("old.edith");134 let path = dir.join("old.edith");
@@ -156,11 +156,11 @@ fn a_version_1_project_loads_fully_grouped_and_saves_as_version_4() {
156 "playhead kept"156 "playhead kept"
157 );157 );
158 158
159- // Saved again it is v4, and v4 round-trips to the same timeline.159+ // Saved again it is v5, and v5 round-trips to the same timeline.
160 let v2 = dir.join("new.edith");160 let v2 = dir.join("new.edith");
161 loaded.save_project(&v2).expect("save");161 loaded.save_project(&v2).expect("save");
162 let text = std::fs::read_to_string(&v2).expect("read back");162 let text = std::fs::read_to_string(&v2).expect("read back");
163- assert!(text.starts_with("edith 4\n"), "{text}");163+ assert!(text.starts_with("edith 5\n"), "{text}");
164 assert_eq!(164 assert_eq!(
165 text.lines().filter(|l| l.starts_with("video ")).count(),165 text.lines().filter(|l| l.starts_with("video ")).count(),
166 2,166 2,
@@ -237,14 +237,42 @@ fn a_version_4_project_holds_more_than_two_lanes() {
237 );237 );
238 assert_eq!(loaded.timeline_duration(), 60.0 / loaded.meta().frame_rate);238 assert_eq!(loaded.timeline_duration(), 60.0 / loaded.meta().frame_rate);
239 239
240- // ...and saving it writes back the same bytes: the lane list, its order and240+ // ...and saving it writes the v5 twin of what it read: the lane list, its
241- // the empty lane all survive the round trip.241+ // order and the empty lane all survive, each clip now saying it plays flat.
242+ let again = dir.join("again.edith");
243+ loaded.save_project(&again).expect("save");
244+ assert_eq!(
245+ 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"
249+ );
250+}
251+
252+/// What version 5 is for: a clip carries equalizer settings, the file names
253+/// 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+#[test]
256+fn a_version_5_project_carries_per_clip_equalizers() {
257+ let dir = scratch("v5_eq");
258+ copy_in(&dir, "test_av.mp4");
259+ let path = dir.join("eq.edith");
260+ // Two clips on one curve, one on another, one flat.
261+ let text = "edith 5\nplayhead 0\nsource 0 test_av.mp4\n\
262+ eq 80.0:-3.0:0.707:ls 1000.0:4.5:1.0:pk\n\
263+ eq 12000.0:6.25:0.5:hs\n\
264+ video 1 0 0 30 0 - 0\nvideo 1 30 30 60 0 - 1\n\
265+ audio 1 0 0 30 0 - 0\naudio 1 30 30 60 0 - -\n";
266+ std::fs::write(&path, text).expect("write a v5 file");
267+
268+ let loaded = PlaybackSession::open_project(&path).expect("a v5 project opens");
269+ assert_eq!(loaded.lane_clips(engine::project::Lane::V1).len(), 2);
242 let again = dir.join("again.edith");270 let again = dir.join("again.edith");
243 loaded.save_project(&again).expect("save");271 loaded.save_project(&again).expect("save");
244 assert_eq!(272 assert_eq!(
245 std::fs::read_to_string(&again).expect("read back"),273 std::fs::read_to_string(&again).expect("read back"),
246 text,274 text,
247- "a four-lane project is written as it was read"275+ "the equalizer table and every clip's index survive a round trip"
248 );276 );
249 }277 }
250 278
@@ -459,9 +487,18 @@ fn malformed_files_are_numbered_errors_and_never_panics() {
459 487
460 for (text, want) in [488 for (text, want) in [
461 (489 (
462- "edith 5\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 -\n",490+ "edith 6\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - -\n",
463 "line 1",491 "line 1",
464 ),492 ),
493+ // An eq index the table does not hold, and a band shape there is none.
494+ (
495+ "edith 5\nsource 0 test_av.mp4\nvideo 1 0 0 30 0 - 0\n",
496+ "line 3",
497+ ),
498+ (
499+ "edith 5\nsource 0 test_av.mp4\neq 80.0:0.0:0.707:band\nvideo 1 0 0 30 0 - 0\n",
500+ "line 3",
501+ ),
465 // A lane number that skips one of its kind: V2 was never declared.502 // A lane number that skips one of its kind: V2 was never declared.
466 (503 (
467 "edith 4\nsource 0 test_av.mp4\nvideo 2 0 0 30 0 -\n",504 "edith 4\nsource 0 test_av.mp4\nvideo 2 0 0 30 0 -\n",