forge
Explore
Log in

Don't you dare go Hollow

Per-clip equalizer is live in playback and export

Browse files at this commit

4d921557054ee7cc64906436e5652a9595bb1812Ahmet Kaan GümüşParent: 2c7cf37
  • feat
    • per-clip equalizer is live in playback and export
Show full message
✨ feat(audio): per-clip equalizer is live in playback and export

The model, the format and the filter have all existed with no callers. This
wires them: `Project::audio_eqs_from` hands one curve per segment beside the
play list `audio_segments_from` already builds, `open_mixed_streams_eq` gives
each lane's worker those curves, and `emit` -- the one place both readers hand
their samples over -- filters a segment after it is trimmed and before it is
sent. Playback and an audio export therefore get the same filtered stream by
construction rather than by two call sites agreeing.

A parallel list, not a fourth element of the segment tuple: that tuple is what
every opener, the packet-copy path and a dozen tests speak, and an effect is not
part of which samples a segment names. A short list plays flat, so a mismatch
can neither panic nor shift a curve onto the wrong clip.

Live editing needs no channel into a running worker: `set_eq` is an edit and
every edit reseeks, so the workers are rebuilt from the new curves where the
playhead is standing.

An mp4 export copies AAC packets and no filter can reach a copy, so an
equalized clip is refused by name and by timecode rather than written flat.

The card is the third of its kind (same scrim, width and rows as keys and
export): a row per band, dragged from the middle out, with `q` to open it and
1-5 / up / down / r as its own keyboard, every one of them listed in the keys
menu by the registry the guard test reads.
crates/app/src/keymap.rsmodified+40 -6
@@ -51,13 +51,14 @@ pub enum ActionId {
51 ToggleMute,51 ToggleMute,
52 VolumeUp,52 VolumeUp,
53 VolumeDown,53 VolumeDown,
54+ Equalizer,
54 CancelExport,55 CancelExport,
55 }56 }
56 57
57 impl ActionId {58 impl ActionId {
58 /// Display order everywhere -- the editor lists them in it and59 /// Display order everywhere -- the editor lists them in it and
59 /// [`Keymap::defaults`] binds them in it.60 /// [`Keymap::defaults`] binds them in it.
60- pub const ALL: [ActionId; 14] = [61+ pub const ALL: [ActionId; 15] = [
61 ActionId::Play,62 ActionId::Play,
62 ActionId::Export,63 ActionId::Export,
63 ActionId::Save,64 ActionId::Save,
@@ -71,6 +72,7 @@ impl ActionId {
71 ActionId::ToggleMute,72 ActionId::ToggleMute,
72 ActionId::VolumeUp,73 ActionId::VolumeUp,
73 ActionId::VolumeDown,74 ActionId::VolumeDown,
75+ ActionId::Equalizer,
74 ActionId::CancelExport,76 ActionId::CancelExport,
75 ];77 ];
76 78
@@ -90,6 +92,7 @@ impl ActionId {
90 ActionId::ToggleMute => "Mute / Unmute",92 ActionId::ToggleMute => "Mute / Unmute",
91 ActionId::VolumeUp => "Volume up",93 ActionId::VolumeUp => "Volume up",
92 ActionId::VolumeDown => "Volume down",94 ActionId::VolumeDown => "Volume down",
95+ ActionId::Equalizer => "Equalizer",
93 ActionId::CancelExport => "Cancel export",96 ActionId::CancelExport => "Cancel export",
94 }97 }
95 }98 }
@@ -111,6 +114,7 @@ impl ActionId {
111 ActionId::ToggleMute => "toggle-mute",114 ActionId::ToggleMute => "toggle-mute",
112 ActionId::VolumeUp => "volume-up",115 ActionId::VolumeUp => "volume-up",
113 ActionId::VolumeDown => "volume-down",116 ActionId::VolumeDown => "volume-down",
117+ ActionId::Equalizer => "equalizer",
114 ActionId::CancelExport => "cancel-export",118 ActionId::CancelExport => "cancel-export",
115 }119 }
116 }120 }
@@ -127,7 +131,10 @@ impl ActionId {
127 ActionId::Play => Category::Playback,131 ActionId::Play => Category::Playback,
128 ActionId::Copy | ActionId::Paste | ActionId::Delete | ActionId::Lift => Category::Clips,132 ActionId::Copy | ActionId::Paste | ActionId::Delete | ActionId::Lift => Category::Clips,
129 ActionId::Cut | ActionId::Regroup | ActionId::Undo => Category::Editing,133 ActionId::Cut | ActionId::Regroup | ActionId::Undo => Category::Editing,
130- ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown => Category::Audio,134+ ActionId::ToggleMute
135+ | ActionId::VolumeUp
136+ | ActionId::VolumeDown
137+ | ActionId::Equalizer => Category::Audio,
131 ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File,138 ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File,
132 }139 }
133 }140 }
@@ -179,7 +186,7 @@ pub struct Fixed {
179 pub category: Category,186 pub category: Category,
180 }187 }
181 188
182-pub const FIXED: [Fixed; 5] = [189+pub const FIXED: [Fixed; 9] = [
183 Fixed {190 Fixed {
184 chord: "esc",191 chord: "esc",
185 label: "Close this card or clip menu, or cancel a capture",192 label: "Close this card or clip menu, or cancel a capture",
@@ -205,6 +212,29 @@ pub const FIXED: [Fixed; 5] = [
205 label: "Erase a bitrate digit",212 label: "Erase a bitrate digit",
206 category: Category::File,213 category: Category::File,
207 },214 },
215+ // The equalizer card's own input, for the same reason the export card has
216+ // its own: a band nothing but a drag can reach is a band half the users of
217+ // this editor cannot move at all. Card-local, so none of them is bindable.
218+ Fixed {
219+ chord: "1–5",
220+ label: "Pick an equalizer band",
221+ category: Category::Audio,
222+ },
223+ Fixed {
224+ chord: "up",
225+ label: "Raise the picked band 1 dB",
226+ category: Category::Audio,
227+ },
228+ Fixed {
229+ chord: "down",
230+ label: "Lower the picked band 1 dB",
231+ category: Category::Audio,
232+ },
233+ Fixed {
234+ chord: "r",
235+ label: "Flatten every band",
236+ category: Category::Audio,
237+ },
208 ];238 ];
209 239
210 /// A stroke as the key handler sees it: gpui's key name plus the one modifier240 /// A stroke as the key handler sees it: gpui's key name plus the one modifier
@@ -316,6 +346,9 @@ impl Keymap {
316 // player has, without asking for shift to make the "+".346 // player has, without asking for shift to make the "+".
317 b(ActionId::VolumeUp, "=", false),347 b(ActionId::VolumeUp, "=", false),
318 b(ActionId::VolumeDown, "-", false),348 b(ActionId::VolumeDown, "-", false),
349+ // The one free letter that says the word: "e" is already the
350+ // export and an equalizer is the q in nobody else's way.
351+ b(ActionId::Equalizer, "q", false),
319 b(ActionId::CancelExport, "escape", false),352 b(ActionId::CancelExport, "escape", false),
320 ],353 ],
321 }354 }
@@ -542,7 +575,7 @@ mod tests {
542 #[test]575 #[test]
543 fn every_default_stroke_reaches_its_action() {576 fn every_default_stroke_reaches_its_action() {
544 let k = Keymap::defaults();577 let k = Keymap::defaults();
545- assert_eq!(k.entries().len(), 16);578+ assert_eq!(k.entries().len(), 17);
546 assert_eq!(k.lookup("space", false), Some(ActionId::Play));579 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
547 assert_eq!(k.lookup("e", false), Some(ActionId::Export));580 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
548 assert_eq!(k.lookup("s", true), Some(ActionId::Save));581 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
@@ -556,6 +589,7 @@ mod tests {
556 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));589 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
557 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));590 assert_eq!(k.lookup("z", true), Some(ActionId::Undo));
558 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));591 assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute));
592+ assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer));
559 // The volume pair is the unshifted one, so neither needs a modifier593 // The volume pair is the unshifted one, so neither needs a modifier
560 // and neither is the "+" gpui reports for shift+=.594 // and neither is the "+" gpui reports for shift+=.
561 assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp));595 assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp));
@@ -565,7 +599,7 @@ mod tests {
565 // The modifier is half the chord: ctrl+e is not e.599 // The modifier is half the chord: ctrl+e is not e.
566 assert_eq!(k.lookup("e", true), None);600 assert_eq!(k.lookup("e", true), None);
567 assert_eq!(k.lookup("space", true), None);601 assert_eq!(k.lookup("space", true), None);
568- assert_eq!(k.lookup("q", false), None);602+ assert_eq!(k.lookup("j", false), None);
569 // Nothing is bound twice, or lookup's first match would be a coin toss.603 // Nothing is bound twice, or lookup's first match would be a coin toss.
570 for (i, a) in k.entries().iter().enumerate() {604 for (i, a) in k.entries().iter().enumerate() {
571 assert!(605 assert!(
@@ -689,7 +723,7 @@ mod tests {
689 );723 );
690 // The label is the editor's column, and never the file's word for it.724 // The label is the editor's column, and never the file's word for it.
691 assert_eq!(ActionId::CancelExport.label(), "Cancel export");725 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
692- assert_eq!(ActionId::ALL.len(), 14);726+ assert_eq!(ActionId::ALL.len(), 15);
693 }727 }
694 728
695 #[test]729 #[test]
crates/app/src/main.rsmodified+481 -25
@@ -10,6 +10,7 @@ use std::sync::Arc;
10 use std::time::{Duration, Instant};10 use std::time::{Duration, Instant};
11 11
12 use engine::audio::StreamInfo;12 use engine::audio::StreamInfo;
13+use engine::eq::{Band, BandKind, EqParams};
13 use engine::export::{ExportSettings, Format};14 use engine::export::{ExportSettings, Format};
14 use engine::project::{Lane, LaneKind, Source};15 use engine::project::{Lane, LaneKind, Source};
15 use engine::{Clip, ExportHandle, Frame, PlaybackSession};16 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
@@ -215,14 +216,28 @@ struct ContextMenu {
215 /// action a stroke already reaches -- the menu is a second way *to* the actions216 /// action a stroke already reaches -- the menu is a second way *to* the actions
216 /// and never a second version of them -- so both the label and the hint come217 /// and never a second version of them -- so both the label and the hint come
217 /// out of the keymap registry and the two can never disagree.218 /// out of the keymap registry and the two can never disagree.
218-const MENU_ITEMS: [ActionId; 5] = [219+const MENU_ITEMS: [ActionId; 6] = [
219 ActionId::Cut,220 ActionId::Cut,
220 ActionId::Delete,221 ActionId::Delete,
221 ActionId::Lift,222 ActionId::Lift,
222 ActionId::Regroup,223 ActionId::Regroup,
224+ ActionId::Equalizer,
223 ActionId::ToggleMute,225 ActionId::ToggleMute,
224 ];226 ];
225 227
228+/// How far a band may be pushed either way, in dB. The engine clamps nothing
229+/// here -- it will filter whatever it is given -- so this is a UI decision:
230+/// past about this a peaking band stops sounding like tone and starts sounding
231+/// like a fault.
232+const EQ_GAIN_LIMIT: f32 = 12.;
233+
234+/// One dB per keystroke, which is roughly the smallest step anyone hears on a
235+/// single band.
236+const EQ_STEP: f32 = 1.;
237+
238+/// The gain bar's height inside a band row.
239+const EQ_BAR_H: f32 = 6.;
240+
226 struct Player {241 struct Player {
227 /// The timeline, once there is one. A run with no file opens without it and242 /// The timeline, once there is one. A run with no file opens without it and
228 /// waits: the first media import or project load is what fills it, and243 /// waits: the first media import or project load is what fills it, and
@@ -317,6 +332,26 @@ struct Player {
317 /// Which file the card will write. Kept across closes like the quality, and332 /// Which file the card will write. Kept across closes like the quality, and
318 /// what [`Player::export_path`](Player) is named after.333 /// what [`Player::export_path`](Player) is named after.
319 format: Format,334 format: Format,
335+ /// The equalizer card is up on this clip -- the lane and index it was
336+ /// opened on. Held rather than re-read from `selected` every paint because
337+ /// the card is modal: while it is up nothing else can move an index, and
338+ /// the one edit it makes (`set_eq`) moves none.
339+ eq_open: Option<(Lane, usize)>,
340+ /// The curve the card is showing, which is the clip's own or the flat
341+ /// five-band default. Edited live and written at the clip once per gesture
342+ /// ([`Player::commit_eq`]): the project's equalizer table is append-only, so
343+ /// a write per pointer sample would be a table entry -- and an undo step --
344+ /// per pixel.
345+ eq_params: EqParams,
346+ /// Which band the keyboard moves, and which one a drag is holding.
347+ eq_band: usize,
348+ /// A band's bar is being dragged. Tracked on the root like `scrubbing`, for
349+ /// the same reason: the pointer leaves the 6 px bar immediately.
350+ eq_dragging: bool,
351+ /// A band bar's own box, recorded at prepaint. One probe for five rows:
352+ /// they are laid out identically and only the *x* of a click is read
353+ /// ([`frac_along`]), so whichever row painted last answers for all of them.
354+ eq_bar: Rc<Cell<Bounds<Pixels>>>,
320 /// The action whose row is waiting for a stroke. The next key that is355 /// The action whose row is waiting for a stroke. The next key that is
321 /// neither escape nor a lone modifier becomes the whole of what reaches it.356 /// neither escape nor a lone modifier becomes the whole of what reaches it.
322 rebinding: Option<ActionId>,357 rebinding: Option<ActionId>,
@@ -431,6 +466,7 @@ impl Player {
431 ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),466 ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),
432 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),467 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
433 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),468 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
469+ ActionId::Equalizer => self.open_eq(cx),
434 // Nothing to cancel while nothing is exporting; the export guard in470 // Nothing to cancel while nothing is exporting; the export guard in
435 // the key handler is what answers this one while there is.471 // the key handler is what answers this one while there is.
436 ActionId::CancelExport => {}472 ActionId::CancelExport => {}
@@ -441,7 +477,103 @@ impl Player {
441 /// out of reach, so a right-click there opens no menu -- the same rule the477 /// out of reach, so a right-click there opens no menu -- the same rule the
442 /// key handler and the drop target already follow.478 /// key handler and the drop target already follow.
443 fn modal(&self) -> bool {479 fn modal(&self) -> bool {
444- self.keys_open || self.export_open || self.exporting().is_some()480+ self.keys_open || self.export_open || self.eq_open.is_some() || self.exporting().is_some()
481+ }
482+
483+ /// Opens the equalizer on the selected clip. Audio only, and it says so
484+ /// rather than opening a card of bands that would reach nothing: a video
485+ /// clip carries no sound of its own here (the sound is the audio lane's),
486+ /// and the model would take the setting without anything ever playing it.
487+ fn open_eq(&mut self, cx: &mut Context<Self>) {
488+ if self.exporting().is_some() {
489+ return;
490+ }
491+ let refusal = match (self.selected, &self.session) {
492+ (_, None) => Some("NO TIMELINE — open a file first"),
493+ (None, _) => Some("NOTHING SELECTED — click an audio clip, then ask again"),
494+ (Some((lane, _)), _) if lane.kind != LaneKind::Audio => Some(
495+ "NOT AN AUDIO CLIP — the equalizer works on the sound, so pick a clip in an audio lane",
496+ ),
497+ _ => None,
498+ };
499+ if let Some(refusal) = refusal {
500+ self.notice = Some(refusal.into());
501+ cx.notify();
502+ return;
503+ }
504+ let (lane, idx) = self.selected.expect("checked above");
505+ let session = self.session.as_ref().expect("checked above");
506+ // What the clip already plays through, or the flat default -- so the
507+ // card opens on the curve that is in force and a reopen shows the last
508+ // drag rather than a fresh set of zeroes.
509+ self.eq_params = session
510+ .eq_of(lane, idx)
511+ .cloned()
512+ .unwrap_or_else(EqParams::default_layout);
513+ self.eq_band = 0;
514+ self.eq_dragging = false;
515+ self.eq_open = Some((lane, idx));
516+ // One card at a time, the rule the other two already follow.
517+ self.keys_open = false;
518+ self.export_open = false;
519+ self.context_menu = None;
520+ cx.notify();
521+ }
522+
523+ /// Writes what the card is showing at its clip: one undo step, one entry in
524+ /// the append-only equalizer table, so this is called once per *gesture* --
525+ /// the end of a drag, a keystroke -- and never per pointer sample.
526+ ///
527+ /// A curve that moves nothing is stored as *no* equalizer at all, which is
528+ /// what keeps a clip nobody has touched on the identity path through
529+ /// playback and export (`engine::eq::EqParams::is_identity`).
530+ fn commit_eq(&mut self, cx: &mut Context<Self>) {
531+ let Some((lane, idx)) = self.eq_open else {
532+ return;
533+ };
534+ let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone());
535+ if let Some(session) = &mut self.session {
536+ session.set_eq(lane, idx, params);
537+ }
538+ // `set_eq` reseeks inside the engine -- that is what makes the change
539+ // audible at once -- and a reseek is what these flags are about.
540+ self.reset_after_reseek();
541+ cx.notify();
542+ }
543+
544+ /// Moves one band and says whether anything changed. Live only: the write
545+ /// is [`commit_eq`](Player::commit_eq)'s.
546+ fn set_band(&mut self, band: usize, gain_db: f32) -> bool {
547+ let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
548+ match self.eq_params.bands.get_mut(band) {
549+ Some(b) if b.gain_db != gain_db => {
550+ b.gain_db = gain_db;
551+ true
552+ }
553+ _ => false,
554+ }
555+ }
556+
557+ /// The keyboard's version of a drag: one step on the picked band, committed
558+ /// straight away -- a keystroke has no release to wait for.
559+ fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) {
560+ let gain = self
561+ .eq_params
562+ .bands
563+ .get(self.eq_band)
564+ .map_or(0., |b| b.gain_db);
565+ if self.set_band(self.eq_band, gain + by) {
566+ self.commit_eq(cx);
567+ }
568+ }
569+
570+ /// Where the pointer sits along a band's bar, as a gain: the middle is flat
571+ /// and the two ends are the limit either way.
572+ fn drag_band(&mut self, x: Pixels, cx: &mut Context<Self>) {
573+ let gain = (frac_along(x, self.eq_bar.get()) * 2. - 1.) * EQ_GAIN_LIMIT;
574+ if self.set_band(self.eq_band, gain) {
575+ cx.notify();
576+ }
445 }577 }
446 578
447 /// Jumps the timeline.579 /// Jumps the timeline.
@@ -1231,6 +1363,38 @@ impl Render for Player {
1231 cx.notify();1363 cx.notify();
1232 return;1364 return;
1233 }1365 }
1366+ // And the equalizer card, the same way again. Its own strokes
1367+ // are the card's input, exactly as the export card's digits
1368+ // are: a band reachable only by dragging is a band a keyboard
1369+ // cannot move at all, and every one of them is listed in the
1370+ // keys menu (keymap.rs `FIXED`) rather than being a secret.
1371+ if this.eq_open.is_some() {
1372+ if key == ESCAPE {
1373+ // Nothing to undo: every change is already at the clip,
1374+ // and undo is undo's own key.
1375+ this.eq_open = None;
1376+ this.eq_dragging = false;
1377+ } else if key == "up" {
1378+ this.nudge_band(EQ_STEP, cx);
1379+ } else if key == "down" {
1380+ this.nudge_band(-EQ_STEP, cx);
1381+ } else if key == "r" {
1382+ for band in &mut this.eq_params.bands {
1383+ band.gain_db = 0.;
1384+ }
1385+ this.commit_eq(cx);
1386+ } else if let Ok(digit) = key.parse::<usize>() {
1387+ // 1-based, as the rows are numbered on screen; a digit
1388+ // past the last band picks nothing rather than panics.
1389+ if let Some(band) = digit.checked_sub(1)
1390+ && band < this.eq_params.bands.len()
1391+ {
1392+ this.eq_band = band;
1393+ }
1394+ }
1395+ cx.notify();
1396+ return;
1397+ }
1234 // A clip menu names an index, and every edit below moves1398 // A clip menu names an index, and every edit below moves
1235 // indices -- so a stroke closes it before it acts. Escape means1399 // indices -- so a stroke closes it before it acts. Escape means
1236 // that and nothing else, which is the `esc` the keys menu1400 // that and nothing else, which is the `esc` the keys menu
@@ -1256,7 +1420,7 @@ impl Render for Player {
1256 // sibling it can stop. The export card is over the timeline for1420 // sibling it can stop. The export card is over the timeline for
1257 // the same reason: importing under it would change the very1421 // the same reason: importing under it would change the very
1258 // edit list the card is about to write out.1422 // edit list the card is about to write out.
1259- if this.keys_open || this.export_open {1423+ if this.keys_open || this.export_open || this.eq_open.is_some() {
1260 return;1424 return;
1261 }1425 }
1262 for path in paths.paths() {1426 for path in paths.paths() {
@@ -1272,6 +1436,20 @@ impl Render for Player {
1272 // 6 px ruler on the first drag and its own listeners then stop1436 // 6 px ruler on the first drag and its own listeners then stop
1273 // firing; the root's hitbox is the whole window.1437 // firing; the root's hitbox is the whole window.
1274 .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {1438 .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {
1439+ // A band's bar is 6 px tall and the pointer leaves it at once,
1440+ // so the equalizer drag is tracked here for the ruler's reason.
1441+ if this.eq_dragging {
1442+ if event.pressed_button == Some(MouseButton::Left) {
1443+ this.drag_band(event.position.x, cx);
1444+ } else {
1445+ // Released outside the window: the up below never came,
1446+ // so this is where the gesture ends -- and it still owes
1447+ // the one write the whole drag is worth.
1448+ this.eq_dragging = false;
1449+ this.commit_eq(cx);
1450+ }
1451+ return;
1452+ }
1275 if !this.scrubbing {1453 if !this.scrubbing {
1276 return;1454 return;
1277 }1455 }
@@ -1287,6 +1465,13 @@ impl Render for Player {
1287 .on_mouse_up(1465 .on_mouse_up(
1288 MouseButton::Left,1466 MouseButton::Left,
1289 cx.listener(|this, event: &MouseUpEvent, _, cx| {1467 cx.listener(|this, event: &MouseUpEvent, _, cx| {
1468+ if std::mem::take(&mut this.eq_dragging) {
1469+ // The release lands exactly, then the gesture is written
1470+ // once -- the append-only table's whole reason.
1471+ this.drag_band(event.position.x, cx);
1472+ this.commit_eq(cx);
1473+ return;
1474+ }
1290 if std::mem::take(&mut this.scrubbing) {1475 if std::mem::take(&mut this.scrubbing) {
1291 this.scrub_to(event.position.x, true, cx);1476 this.scrub_to(event.position.x, true, cx);
1292 }1477 }
@@ -1359,6 +1544,7 @@ impl Render for Player {
1359 // column, and only one of the two is ever up.1544 // column, and only one of the two is ever up.
1360 .children(self.keys_overlay(cx))1545 .children(self.keys_overlay(cx))
1361 .children(self.export_card(cx))1546 .children(self.export_card(cx))
1547+ .children(self.eq_card(cx))
1362 }1548 }
1363 }1549 }
1364 1550
@@ -2167,6 +2353,158 @@ impl Player {
2167 )2353 )
2168 }2354 }
2169 2355
2356+ /// The equalizer of one audio clip: a row per band, each a bar that reads
2357+ /// flat in the middle and is dragged either way, and a row that flattens
2358+ /// them all. The same scrim, width and rows as the other two cards, and the
2359+ /// same plain divs -- nothing here takes focus, so the root keeps the
2360+ /// keyboard and the card's own strokes (`1`–`5`, up, down, `r`) reach it.
2361+ ///
2362+ /// Every change is written at the clip as it is made
2363+ /// ([`Player::commit_eq`]), so what the card shows is always what is
2364+ /// playing: there is no OK button to forget, and closing it changes
2365+ /// nothing. What takes a curve back off is undo, like every other edit.
2366+ fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2367+ let (lane, idx) = self.eq_open?;
2368+ let rows: Vec<_> = self
2369+ .eq_params
2370+ .bands
2371+ .iter()
2372+ .enumerate()
2373+ .map(|(i, band)| {
2374+ let (left, width) = eq_fill(band.gain_db);
2375+ div()
2376+ .id(("eq-band", i))
2377+ .flex()
2378+ .min_h(px(KEYS_ROW_H))
2379+ .items_center()
2380+ .gap(px(12.))
2381+ .px(px(6.))
2382+ .rounded(px(3.))
2383+ .cursor_pointer()
2384+ .when(i == self.eq_band, |d| d.bg(rgb(SELECTED)))
2385+ .hover(|s| s.bg(rgb(HOVER)))
2386+ // The press picks the band *and* is already the first
2387+ // sample of the drag, so a plain click sets a value.
2388+ .on_mouse_down(
2389+ MouseButton::Left,
2390+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
2391+ this.eq_band = i;
2392+ this.eq_dragging = true;
2393+ this.drag_band(event.position.x, cx);
2394+ }),
2395+ )
2396+ .child(
2397+ div()
2398+ .flex_none()
2399+ // Wide enough for "12 kHz high shelf", so the bars
2400+ // below each other all start at the same pixel.
2401+ .w(px(112.))
2402+ .text_size(px(11.))
2403+ .child(format!("{} {}", i + 1, band_label(band))),
2404+ )
2405+ .child(
2406+ div()
2407+ .flex_1()
2408+ .h(px(EQ_BAR_H))
2409+ .rounded(px(3.))
2410+ .bg(rgb(SURFACE))
2411+ .child(bounds_probe(self.eq_bar.clone()))
2412+ .child(
2413+ div()
2414+ .absolute()
2415+ .left(relative(left))
2416+ .w(relative(width))
2417+ .h_full()
2418+ .rounded(px(3.))
2419+ .bg(rgb(ACCENT)),
2420+ ),
2421+ )
2422+ .child(
2423+ div()
2424+ .flex_none()
2425+ // Fixed, so a sign or a second digit appearing does
2426+ // not shift the bar beside it mid-drag.
2427+ .w(px(56.))
2428+ .text_size(px(11.))
2429+ .text_color(rgb(INK_DIM))
2430+ .child(format!("{:+.1} dB", band.gain_db)),
2431+ )
2432+ })
2433+ .collect();
2434+ Some(
2435+ div()
2436+ .absolute()
2437+ .inset_0()
2438+ .flex()
2439+ .justify_center()
2440+ .items_center()
2441+ .bg(rgba(0x101010cc))
2442+ .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
2443+ cx.stop_propagation()
2444+ })
2445+ .child(
2446+ div()
2447+ .w(px(KEYS_W))
2448+ .flex()
2449+ .flex_col()
2450+ .gap(px(2.))
2451+ .p(px(12.))
2452+ .rounded(px(6.))
2453+ .bg(rgb(SURFACE))
2454+ // Which clip, because the card is modal and the lane it
2455+ // was opened from is behind a scrim by the time it is up.
2456+ .child(div().flex_none().px(px(6.)).child(format!(
2457+ "Equalizer — {} clip {}",
2458+ lane.label(),
2459+ idx + 1
2460+ )))
2461+ .child(
2462+ div()
2463+ .flex_none()
2464+ .px(px(6.))
2465+ .text_size(px(11.))
2466+ .text_color(rgb(INK_DIM))
2467+ .child(self.notice.clone().unwrap_or_else(|| {
2468+ "drag a band, or 1–5 then up/down — esc closes".into()
2469+ })),
2470+ )
2471+ // Five rows fit a 360 px window, but the layout is data
2472+ // (a file may carry any number of bands), so the list
2473+ // scrolls like the other two cards' do.
2474+ .child(
2475+ div()
2476+ .id("eq-rows")
2477+ .flex()
2478+ .flex_col()
2479+ .gap(px(2.))
2480+ .max_h(px(EXPORT_ROWS_H))
2481+ .overflow_y_scroll()
2482+ .children(rows),
2483+ )
2484+ .child(
2485+ div()
2486+ .id("eq-reset")
2487+ .mt(px(4.))
2488+ .flex()
2489+ .h(px(CONTROL_H))
2490+ .items_center()
2491+ .justify_center()
2492+ .rounded(px(3.))
2493+ .bg(rgb(SELECTED))
2494+ .cursor_pointer()
2495+ .hover(|s| s.bg(rgb(HOVER)))
2496+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2497+ for band in &mut this.eq_params.bands {
2498+ band.gain_db = 0.;
2499+ }
2500+ this.commit_eq(cx);
2501+ }))
2502+ .child("Flatten"),
2503+ ),
2504+ ),
2505+ )
2506+ }
2507+
2170 /// The menu a right-click on a clip opens: what that clip can be given,2508 /// The menu a right-click on a clip opens: what that clip can be given,
2171 /// each item beside the stroke that does the very same thing, and a2509 /// each item beside the stroke that does the very same thing, and a
2172 /// turn-over side that says what the clip *is*. An item that would do2510 /// turn-over side that says what the clip *is*. An item that would do
@@ -2242,7 +2580,7 @@ impl Player {
2242 }2580 }
2243 } else {2581 } else {
2244 for action in MENU_ITEMS {2582 for action in MENU_ITEMS {
2245- let enabled = applicable(&clip, action, playhead);2583+ let enabled = applicable(&clip, menu.lane, action, playhead);
2246 // The one item that is not about this clip says so, and says it2584 // The one item that is not about this clip says so, and says it
2247 // here rather than in the registry: the stroke is global too,2585 // here rather than in the registry: the stroke is global too,
2248 // but its row in the keys menu is not sitting on a clip.2586 // but its row in the keys menu is not sitting on a clip.
@@ -2750,11 +3088,44 @@ fn frame_at(secs: f64, fps: f64) -> u32 {
2750 (secs * fps + 1e-6).floor().max(0.) as u323088 (secs * fps + 1e-6).floor().max(0.) as u32
2751 }3089 }
2752 3090
3091+/// A band's bar as `(left, width)` in fractions of the track: the fill grows
3092+/// out of the *middle*, which is flat, towards whichever end the gain went --
3093+/// a bar that filled from the left would read a -12 dB cut as an empty control
3094+/// and 0 dB as a half-off one. The inverse of [`Player::drag_band`]'s reading
3095+/// of a click, and clamped like it, so a curve loaded from a file with a gain
3096+/// past the card's limit paints at the end of the bar rather than outside it.
3097+fn eq_fill(gain_db: f32) -> (f32, f32) {
3098+ let at = (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2. + 0.5;
3099+ match at >= 0.5 {
3100+ true => (0.5, at - 0.5),
3101+ false => (at, 0.5 - at),
3102+ }
3103+}
3104+
3105+/// What a band row calls itself: the corner or centre frequency, and for a
3106+/// shelf the fact that it tilts everything past it -- which is the difference
3107+/// between "12 kHz" moving the last octave and moving one band inside it.
3108+fn band_label(band: &Band) -> String {
3109+ let freq = match band.freq_hz >= 1000. {
3110+ true => format!("{:.0} kHz", band.freq_hz / 1000.),
3111+ false => format!("{:.0} Hz", band.freq_hz),
3112+ };
3113+ match band.kind {
3114+ BandKind::LowShelf => format!("{freq} low shelf"),
3115+ BandKind::HighShelf => format!("{freq} high shelf"),
3116+ BandKind::Peak => freq,
3117+ }
3118+}
3119+
2753 /// Whether the clip menu offers `action` on the clip it was opened on. Two of3120 /// Whether the clip menu offers `action` on the clip it was opened on. Two of
2754 /// the items act on the *playhead* rather than on the clip, so a menu opened3121 /// the items act on the *playhead* rather than on the clip, so a menu opened
2755-/// away from it dims them instead of looking broken when they are clicked.3122+/// away from it dims them instead of looking broken when they are clicked, and
2756-fn applicable(clip: &Clip, action: ActionId, playhead: u32) -> bool {3123+/// one acts on sound, which only an audio lane's clip has.
3124+fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool {
2757 match action {3125 match action {
3126+ // The equalizer filters samples, and a video clip has none of its own
3127+ // here: the sound is the audio lane's, clip for clip.
3128+ ActionId::Equalizer => lane.kind == LaneKind::Audio,
2758 // Splits this clip only from inside it: at either edge there is nothing3129 // Splits this clip only from inside it: at either edge there is nothing
2759 // to split off (project.rs `splittable`).3130 // to split off (project.rs `splittable`).
2760 ActionId::Cut => clip.start < playhead && playhead < clip.end(),3131 ActionId::Cut => clip.start < playhead && playhead < clip.end(),
@@ -3427,15 +3798,15 @@ fn timecode(t: f64, fps: f64) -> String {
3427 #[cfg(test)]3798 #[cfg(test)]
3428 mod tests {3799 mod tests {
3429 use super::{3800 use super::{
3430- ACCENT, CONTROL_H, Clip, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN,3801+ ACCENT, CONTROL_H, Clip, EQ_BAR_H, EQ_GAIN_LIMIT, EXPORT_ROWS_H, FORMATS, Format,
3431- INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX,3802+ HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H,
3432- LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,3803+ LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W,
3433- RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,3804+ NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W,
3434- WAVE_BPS, WAVE_COL, Wave, applicable, can_add, cancels_export, envelope, export_path,3805+ Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add,
3435- export_settings, format_line, frac_along, frame_at, is_bare_modifier, is_project, keymap,3806+ cancels_export, envelope, eq_fill, export_path, export_settings, format_line, frac_along,
3436- lane_clips, marked, menu_at, normalise, project_path, push_digit, retarget, scrub_due,3807+ frame_at, is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise,
3437- show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources,3808+ project_path, push_digit, retarget, scrub_due, show_label, source_frames, source_tint,
3438- width_frac, window_title,3809+ start_frac, timecode, unseen_paths, unseen_sources, width_frac, window_title,
3439 };3810 };
3440 use super::{file_name, library_rows};3811 use super::{file_name, library_rows};
3441 use engine::PlaybackSession;3812 use engine::PlaybackSession;
@@ -3655,20 +4026,27 @@ mod tests {
3655 };4026 };
3656 assert_eq!(clip.end(), 90);4027 assert_eq!(clip.end(), 90);
3657 // Cut splits from inside only: neither edge has anything to split off.4028 // Cut splits from inside only: neither edge has anything to split off.
3658- assert!(applicable(&clip, ActionId::Cut, 31));4029+ let a1 = Lane::A1;
3659- assert!(applicable(&clip, ActionId::Cut, 89));4030+ let v1 = Lane::V1;
3660- assert!(!applicable(&clip, ActionId::Cut, 30));4031+ assert!(applicable(&clip, v1, ActionId::Cut, 31));
3661- assert!(!applicable(&clip, ActionId::Cut, 90));4032+ assert!(applicable(&clip, v1, ActionId::Cut, 89));
3662- assert!(!applicable(&clip, ActionId::Cut, 200));4033+ assert!(!applicable(&clip, v1, ActionId::Cut, 30));
4034+ assert!(!applicable(&clip, v1, ActionId::Cut, 90));
4035+ assert!(!applicable(&clip, v1, ActionId::Cut, 200));
3663 // Regroup is the other way round: only where this clip meets another.4036 // Regroup is the other way round: only where this clip meets another.
3664- assert!(applicable(&clip, ActionId::Regroup, 30));4037+ assert!(applicable(&clip, v1, ActionId::Regroup, 30));
3665- assert!(applicable(&clip, ActionId::Regroup, 90));4038+ assert!(applicable(&clip, v1, ActionId::Regroup, 90));
3666- assert!(!applicable(&clip, ActionId::Regroup, 60));4039+ assert!(!applicable(&clip, v1, ActionId::Regroup, 60));
4040+ // The equalizer is the one item the *lane* decides: it filters samples,
4041+ // and a video clip has none of its own. Never the playhead's business.
4042+ assert!(applicable(&clip, a1, ActionId::Equalizer, 0));
4043+ assert!(applicable(&clip, a1, ActionId::Equalizer, 60));
4044+ assert!(!applicable(&clip, v1, ActionId::Equalizer, 60));
3667 // The rest act on the clip that was clicked, so they always mean4045 // The rest act on the clip that was clicked, so they always mean
3668 // something -- the engine words its own refusals.4046 // something -- the engine words its own refusals.
3669 for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {4047 for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {
3670- assert!(applicable(&clip, action, 0));4048+ assert!(applicable(&clip, v1, action, 0));
3671- assert!(applicable(&clip, action, 60));4049+ assert!(applicable(&clip, a1, action, 60));
3672 }4050 }
3673 // The playhead frame is the engine's own rule, boundary included.4051 // The playhead frame is the engine's own rule, boundary included.
3674 assert_eq!(frame_at(1.0, 30.), 30);4052 assert_eq!(frame_at(1.0, 30.), 30);
@@ -4090,6 +4468,77 @@ mod tests {
4090 assert!(KEYS_ROW_H >= HIT_MIN);4468 assert!(KEYS_ROW_H >= HIT_MIN);
4091 }4469 }
4092 4470
4471+ /// The equalizer card: what its bars paint, and that it fits the window the
4472+ /// other two cards are sized for. The bar is the one bit of geometry in the
4473+ /// card, and it is signed -- a fill that grew from the left would read a cut
4474+ /// as an empty control -- so it is checked against the reading of a click,
4475+ /// which is the same mapping backwards ([`Player::drag_band`]).
4476+ #[test]
4477+ fn the_equalizer_bar_grows_out_of_flat_and_the_card_fits_the_smallest_window() {
4478+ use engine::eq::{Band, BandKind, EqParams};
4479+ // Flat is the middle and paints nothing: a band nobody has touched must
4480+ // not look like one that has been turned down.
4481+ assert_eq!(eq_fill(0.), (0.5, 0.));
4482+ // Full boost fills the right half, full cut the left one.
4483+ assert_eq!(eq_fill(EQ_GAIN_LIMIT), (0.5, 0.5));
4484+ assert_eq!(eq_fill(-EQ_GAIN_LIMIT), (0., 0.5));
4485+ assert_eq!(eq_fill(EQ_GAIN_LIMIT / 2.), (0.5, 0.25));
4486+ assert_eq!(eq_fill(-EQ_GAIN_LIMIT / 2.), (0.25, 0.25));
4487+ // A file may carry a gain past what this card offers (the format writes
4488+ // any finite value): it paints at the end, never off the track.
4489+ assert_eq!(eq_fill(400.), (0.5, 0.5));
4490+ assert_eq!(eq_fill(-400.), (0., 0.5));
4491+
4492+ // A click reads back as the gain that paints where it landed, which is
4493+ // what makes a drag land where the pointer is.
4494+ for gain in [-12., -6., 0., 6., 12.] {
4495+ let (left, width) = eq_fill(gain);
4496+ let at = if gain >= 0. { left + width } else { left };
4497+ let read = (at * 2. - 1.) * EQ_GAIN_LIMIT;
4498+ assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}");
4499+ }
4500+
4501+ // Every default band says what it is, and a shelf says so: "12 kHz"
4502+ // alone would not tell anyone it tilts the whole top octave.
4503+ let labels: Vec<String> = EqParams::default_layout()
4504+ .bands
4505+ .iter()
4506+ .map(band_label)
4507+ .collect();
4508+ assert_eq!(
4509+ labels,
4510+ [
4511+ "80 Hz low shelf",
4512+ "250 Hz",
4513+ "1 kHz",
4514+ "4 kHz",
4515+ "12 kHz high shelf"
4516+ ]
4517+ );
4518+ assert_eq!(
4519+ band_label(&Band {
4520+ freq_hz: 2600.,
4521+ gain_db: 0.,
4522+ q: 1.,
4523+ kind: BandKind::Peak
4524+ }),
4525+ "3 kHz",
4526+ "rounded, because a band label is not a measurement"
4527+ );
4528+
4529+ // The same shape as the other two cards, so it fits where they do.
4530+ let (title, status, gaps, padding) = (17., 28., 3. * 2., 24.);
4531+ assert!(
4532+ title + status + EXPORT_ROWS_H + gaps + padding + CONTROL_H <= 360.,
4533+ "card too tall"
4534+ );
4535+ assert!(KEYS_W <= 640., "card too wide");
4536+ // The rows are dragged, so WCAG 2.5.8 binds them like every other
4537+ // target in this window -- the 6 px bar is inside a full-height row.
4538+ assert!(KEYS_ROW_H >= HIT_MIN);
4539+ assert!(EQ_BAR_H < KEYS_ROW_H);
4540+ }
4541+
4093 /// Mute and level are one control with two states, and the whole point is4542 /// Mute and level are one control with two states, and the whole point is
4094 /// that mute keeps the level: the user gets back what they had, not 100%.4543 /// that mute keeps the level: the user gets back what they had, not 100%.
4095 #[test]4544 #[test]
@@ -4597,6 +5046,13 @@ fn main() {
4597 keymap: keymap.clone(),5046 keymap: keymap.clone(),
4598 keys_open: false,5047 keys_open: false,
4599 export_open: false,5048 export_open: false,
5049+ eq_open: None,
5050+ // Replaced by the clip's own curve the moment the card
5051+ // opens; nothing reads it before that.
5052+ eq_params: EqParams::default(),
5053+ eq_band: 0,
5054+ eq_dragging: false,
5055+ eq_bar: Rc::default(),
4600 // What an export is until someone says otherwise: the5056 // What an export is until someone says otherwise: the
4601 // bitrate the picture asks for.5057 // bitrate the picture asks for.
4602 quality: Quality::Auto,5058 quality: Quality::Auto,
crates/engine/src/audio.rsmodified+98 -6
@@ -43,6 +43,8 @@ use symphonia_core::packet::Packet;
43 use symphonia_core::units;43 use symphonia_core::units;
44 use symphonia_core::units::{Time, TimeBase};44 use symphonia_core::units::{Time, TimeBase};
45 45
46+use crate::eq::{EqParams, EqState};
47+
46 /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.48 /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list.
47 /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)49 /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.)
48 const DEFAULT_PRIMING: u64 = 1024;50 const DEFAULT_PRIMING: u64 = 1024;
@@ -211,6 +213,26 @@ impl AudioSession {
211 pub fn open_multi_streams(213 pub fn open_multi_streams(
212 sources: &[(PathBuf, usize)],214 sources: &[(PathBuf, usize)],
213 segs: &[(Option<usize>, f64, f64)],215 segs: &[(Option<usize>, f64, f64)],
216+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
217+ Self::open_multi_streams_eq(sources, segs, &[])
218+ }
219+
220+ /// [`open_multi_streams`](Self::open_multi_streams) with an equalizer per
221+ /// segment: `eqs[i]` is what segment `i` plays through, `None` for one that
222+ /// plays flat. Filtering happens **per segment**, inside the worker, before
223+ /// anything is mixed -- two clips with different curves must not be blurred
224+ /// into one another, and a segment's filter memory starts clean and dies
225+ /// with it, which is also what makes a seek a reset for free.
226+ ///
227+ /// A parallel list, not a fourth tuple element: see
228+ /// [`crate::Project::audio_eqs_from`], which is what builds it. A list
229+ /// shorter than `segs` (the empty one every plain caller passes) means the
230+ /// rest play flat, so a mismatch cannot panic and cannot silently shift a
231+ /// curve onto the wrong clip.
232+ pub fn open_multi_streams_eq(
233+ sources: &[(PathBuf, usize)],
234+ segs: &[(Option<usize>, f64, f64)],
235+ eqs: &[Option<EqParams>],
214 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {236 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
215 let Some((path, stream)) = sources.first() else {237 let Some((path, stream)) = sources.first() else {
216 return Ok(None);238 return Ok(None);
@@ -282,6 +304,20 @@ impl AudioSession {
282 // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so304 // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so
283 // this bound is ~0.75 s of lookahead — enough to ride out decode jitter305 // this bound is ~0.75 s of lookahead — enough to ride out decode jitter
284 // without making a pause take a second to bite.306 // without making a pause take a second to bite.
307+ // One filter per segment, built here where the rate and the layout are
308+ // known and off the thread that will run it. An identity curve costs a
309+ // branch and nothing else ([`EqState::process`]), and a segment with no
310+ // curve at all is not even that.
311+ let eqs: Vec<Option<EqState>> = segments
312+ .iter()
313+ .enumerate()
314+ .map(|(i, _)| {
315+ eqs.get(i)
316+ .and_then(Option::as_ref)
317+ .map(|p| EqState::new(p, meta.sample_rate, meta.channels))
318+ })
319+ .collect();
320+
285 let (tx, rx) = sync_channel(32);321 let (tx, rx) = sync_channel(32);
286 thread::Builder::new()322 thread::Builder::new()
287 .name("audio-decode".into())323 .name("audio-decode".into())
@@ -290,6 +326,7 @@ impl AudioSession {
290 tracks,326 tracks,
291 channels: meta.channels as usize,327 channels: meta.channels as usize,
292 segments,328 segments,
329+ eqs,
293 timeline,330 timeline,
294 tx,331 tx,
295 })332 })
@@ -317,19 +354,41 @@ impl AudioSession {
317 pub fn open_mixed_streams(354 pub fn open_mixed_streams(
318 sources: &[(PathBuf, usize)],355 sources: &[(PathBuf, usize)],
319 lanes: &[Vec<(Option<usize>, f64, f64)>],356 lanes: &[Vec<(Option<usize>, f64, f64)>],
357+ ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
358+ Self::open_mixed_streams_eq(sources, lanes, &[])
359+ }
360+
361+ /// [`open_mixed_streams`](Self::open_mixed_streams) with
362+ /// [`open_multi_streams_eq`](Self::open_multi_streams_eq)'s per-segment
363+ /// equalizers, one list per lane -- [`crate::Project::audio_eqs_from`] is
364+ /// what shapes them.
365+ ///
366+ /// Filtering is each lane's worker's own business and therefore happens
367+ /// **before** the sum: a clip's curve reaches that clip's samples and stops
368+ /// there, where filtering the mix would smear every lane's curve over
369+ /// everything playing at the same instant. A missing or short list plays
370+ /// flat, as it does one lane down.
371+ pub fn open_mixed_streams_eq(
372+ sources: &[(PathBuf, usize)],
373+ lanes: &[Vec<(Option<usize>, f64, f64)>],
374+ eqs: &[Vec<Option<EqParams>>],
320 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {375 ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> {
321 let [first, rest @ ..] = lanes else {376 let [first, rest @ ..] = lanes else {
322 return Ok(None);377 return Ok(None);
323 };378 };
324 if rest.is_empty() {379 if rest.is_empty() {
325- return Self::open_multi_streams(sources, first);380+ let flat = Vec::new();
381+ return Self::open_multi_streams_eq(sources, first, eqs.first().unwrap_or(&flat));
326 }382 }
327 let mut meta = None;383 let mut meta = None;
328 let mut rxs = Vec::with_capacity(lanes.len());384 let mut rxs = Vec::with_capacity(lanes.len());
329- for segs in lanes {385+ for (i, segs) in lanes.iter().enumerate() {
330 // Every lane probes the same source 0, so the metas agree by386 // Every lane probes the same source 0, so the metas agree by
331 // construction; `None` from any of them is a silent timeline.387 // construction; `None` from any of them is a silent timeline.
332- let Some((lane_meta, rx)) = Self::open_multi_streams(sources, segs)? else {388+ let flat = Vec::new();
389+ let Some((lane_meta, rx)) =
390+ Self::open_multi_streams_eq(sources, segs, eqs.get(i).unwrap_or(&flat))?
391+ else {
333 return Ok(None);392 return Ok(None);
334 };393 };
335 meta = Some(lane_meta);394 meta = Some(lane_meta);
@@ -1240,6 +1299,11 @@ struct Worker {
1240 tracks: Vec<Option<Track>>,1299 tracks: Vec<Option<Track>>,
1241 channels: usize,1300 channels: usize,
1242 segments: Vec<Segment>,1301 segments: Vec<Segment>,
1302+ /// One per entry of `segments`, in the same order: the filter that segment's
1303+ /// samples pass through on the way out, or `None` for one that plays flat.
1304+ /// Beside the segments rather than inside them so the emit path can hold the
1305+ /// window rules and the filter memory at once without splitting a borrow.
1306+ eqs: Vec<Option<EqState>>,
1243 /// `start_sample` of the first chunk.1307 /// `start_sample` of the first chunk.
1244 timeline: u64,1308 timeline: u64,
1245 tx: SyncSender<AudioChunk>,1309 tx: SyncSender<AudioChunk>,
@@ -1317,8 +1381,12 @@ fn run(mut w: Worker) {
1317 // Chunk numbering is continuous across every join, source ones included.1381 // Chunk numbering is continuous across every join, source ones included.
1318 let mut timeline = w.timeline;1382 let mut timeline = w.timeline;
1319 let segments = std::mem::take(&mut w.segments);1383 let segments = std::mem::take(&mut w.segments);
1384+ let mut eqs = std::mem::take(&mut w.eqs);
1385+ // A short list is "flat from here on" (`open_multi_streams_eq`), which this
1386+ // pads out so the zip below still walks every segment.
1387+ eqs.resize_with(segments.len(), || None);
1320 1388
1321- for seg in &segments {1389+ for (seg, eq) in segments.iter().zip(eqs.iter_mut()) {
1322 let Some(source) = seg.source else {1390 let Some(source) = seg.source else {
1323 // A gap: hand the device real silence rather than nothing at all,1391 // A gap: hand the device real silence rather than nothing at all,
1324 // in the same packet-sized chunks decoding produces, so `fed` and1392 // in the same packet-sized chunks decoding produces, so `fed` and
@@ -1343,7 +1411,7 @@ fn run(mut w: Worker) {
1343 };1411 };
1344 let track = match track {1412 let track = match track {
1345 Track::Sym(track) => {1413 Track::Sym(track) => {
1346- if !run_sym(track, seg, channels, &mut timeline, &w.tx) {1414+ if !run_sym(track, seg, eq.as_mut(), channels, &mut timeline, &w.tx) {
1347 return; // consumer went away1415 return; // consumer went away
1348 }1416 }
1349 continue;1417 continue;
@@ -1391,6 +1459,7 @@ fn run(mut w: Worker) {
1391 &mut interleaved,1459 &mut interleaved,
1392 channels,1460 channels,
1393 seg,1461 seg,
1462+ eq.as_mut(),
1394 pos,1463 pos,
1395 next,1464 next,
1396 &mut timeline,1465 &mut timeline,
@@ -1412,10 +1481,18 @@ fn run(mut w: Worker) {
1412 /// audio the caller asked for: it is dropped, splitting the buffer that1481 /// audio the caller asked for: it is dropped, splitting the buffer that
1413 /// straddles the target. The tail past the segment end goes too — on a short1482 /// straddles the target. The tail past the segment end goes too — on a short
1414 /// segment that is this same buffer, trimmed at both ends.1483 /// segment that is this same buffer, trimmed at both ends.
1484+///
1485+/// The segment's equalizer runs here, on the trimmed buffer and nowhere else:
1486+/// this is the one place both readers hand their samples over, so playback and
1487+/// an audio export get the same filtered stream by construction rather than by
1488+/// two call sites agreeing. Trimmed first, so the pre-roll a listener never
1489+/// hears cannot ring the filter either. Nothing is allocated -- the device
1490+/// callback is two hand-offs downstream of here in any case.
1415 fn emit(1491 fn emit(
1416 interleaved: &mut Vec<f32>,1492 interleaved: &mut Vec<f32>,
1417 channels: usize,1493 channels: usize,
1418 seg: &Segment,1494 seg: &Segment,
1495+ eq: Option<&mut EqState>,
1419 pos: u64,1496 pos: u64,
1420 next: u64,1497 next: u64,
1421 timeline: &mut u64,1498 timeline: &mut u64,
@@ -1435,6 +1512,9 @@ fn emit(
1435 if interleaved.is_empty() {1512 if interleaved.is_empty() {
1436 return true; // nothing left of it; the loop head ends the segment1513 return true; // nothing left of it; the loop head ends the segment
1437 }1514 }
1515+ if let Some(eq) = eq {
1516+ eq.process(interleaved);
1517+ }
1438 let chunk = AudioChunk {1518 let chunk = AudioChunk {
1439 start_sample: *timeline,1519 start_sample: *timeline,
1440 samples: std::mem::take(interleaved),1520 samples: std::mem::take(interleaved),
@@ -1455,6 +1535,7 @@ fn emit(
1455 fn run_sym(1535 fn run_sym(
1456 track: &mut SymTrack,1536 track: &mut SymTrack,
1457 seg: &Segment,1537 seg: &Segment,
1538+ mut eq: Option<&mut EqState>,
1458 channels: usize,1539 channels: usize,
1459 timeline: &mut u64,1540 timeline: &mut u64,
1460 tx: &SyncSender<AudioChunk>,1541 tx: &SyncSender<AudioChunk>,
@@ -1505,7 +1586,18 @@ fn run_sym(
1505 };1586 };
1506 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);1587 buf.copy_to_vec_interleaved::<f32>(&mut interleaved);
1507 let next = pos + (interleaved.len() / channels) as u64;1588 let next = pos + (interleaved.len() / channels) as u64;
1508- if !emit(&mut interleaved, channels, seg, pos, next, timeline, tx) {1589+ // Reborrowed per packet: the filter memory has to carry across the
1590+ // packet boundary, so this is one `EqState` for the whole segment.
1591+ if !emit(
1592+ &mut interleaved,
1593+ channels,
1594+ seg,
1595+ eq.as_deref_mut(),
1596+ pos,
1597+ next,
1598+ timeline,
1599+ tx,
1600+ ) {
1509 return false;1601 return false;
1510 }1602 }
1511 }1603 }
crates/engine/src/export.rsmodified+43 -5
@@ -235,6 +235,28 @@ fn run(
235 )235 )
236 .into());236 .into());
237 };237 };
238+ // ...and the same list decides which clips this would be copying, which is
239+ // the only way to ask whether any of them carries an equalizer. An EQ is
240+ // sample math and a copy never decodes: exporting it here would write the
241+ // clip flat, silently -- the same failure a missing audio track is. Named by
242+ // where it sits on the timeline, because "some clip" is not a thing a user
243+ // can go and fix.
244+ let lane = project.audio_lanes()[0];
245+ if let Some((at, _)) = project
246+ .lane(lane)
247+ .iter()
248+ .enumerate()
249+ .find(|(idx, _)| project.eq_of(lane, *idx).is_some())
250+ .map(|(idx, clip)| (clip.start, idx))
251+ {
252+ return Err(format!(
253+ "the clip at {} has an equalizer and an mp4 export copies AAC packets, \
254+ which no filter can reach: export WAV or FLAC, which are decoded and \
255+ mixed, or clear the equalizer",
256+ timecode(at, meta.frame_rate)
257+ )
258+ .into());
259+ }
238 let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?;260 let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?;
239 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {261 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
240 freq_index: track.freq_index,262 freq_index: track.freq_index,
@@ -303,6 +325,18 @@ fn run(
303 Ok(())325 Ok(())
304 }326 }
305 327
328+/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short
329+/// enough to sit inside a refusal and exact enough to go and find the clip.
330+/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a
331+/// `00:00:12:07` in the middle of a sentence is a serial number.
332+fn timecode(frame: u32, fps: f64) -> String {
333+ let secs = match fps.is_finite() && fps > 0.0 {
334+ true => (f64::from(frame) / fps) as u32,
335+ false => 0,
336+ };
337+ format!("{:02}:{:02}", secs / 60, secs % 60)
338+}
339+
306 /// The audio lanes alone, summed, as a WAV or a FLAC.340 /// The audio lanes alone, summed, as a WAV or a FLAC.
307 ///341 ///
308 /// Nothing here re-derives the edit: the play lists are342 /// Nothing here re-derives the edit: the play lists are
@@ -326,7 +360,13 @@ fn run_audio(
326 ) -> crate::Result<()> {360 ) -> crate::Result<()> {
327 let sources = project.audio_sources();361 let sources = project.audio_sources();
328 let segs = project.audio_segments_from(0, meta.frame_rate);362 let segs = project.audio_segments_from(0, meta.frame_rate);
329- let Some((audio, chunks)) = AudioSession::open_mixed_streams(&sources, &segs)? else {363+ // The equalizers with them, so what is written is what is heard down to the
364+ // filter: the worker applies them per segment before the lanes are summed
365+ // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
366+ // playback's feeder reads from -- there is no second place here that could
367+ // apply them differently.
368+ let eqs = project.audio_eqs_from(0, meta.frame_rate);
369+ let Some((audio, chunks)) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs)? else {
330 return Err("this timeline has no audio to export".into());370 return Err("this timeline has no audio to export".into());
331 };371 };
332 let channels = usize::from(audio.channels);372 let channels = usize::from(audio.channels);
@@ -341,10 +381,8 @@ fn run_audio(
341 let mut samples: Vec<i32> = Vec::with_capacity(total);381 let mut samples: Vec<i32> = Vec::with_capacity(total);
342 for chunk in chunks {382 for chunk in chunks {
343 cancelled(shared)?;383 cancelled(shared)?;
344- // ponytail: the per-segment EQ goes here -- `EqState::process` on this384+ // Already equalized: the chunks come out of the per-lane workers, which
345- // same interleaved f32 buffer, before the quantisation below, which is385+ // filter each segment before the mix (`open_mixed_streams_eq` above).
346- // the point playback's feeder will call it from too. Not wired: the EQ
347- // slice owns that, this is only the seat kept for it.
348 samples.extend(386 samples.extend(
349 chunk387 chunk
350 .samples388 .samples
crates/engine/src/playback.rsmodified+30 -1
@@ -23,6 +23,7 @@ use crate::audio::{AudioChunk, AudioSession};
23 use crate::clock::{ClockSource, PlaybackClock};23 use crate::clock::{ClockSource, PlaybackClock};
24 use crate::decode::{DecodeSession, Frame, Worker};24 use crate::decode::{DecodeSession, Frame, Worker};
25 use crate::demux::{Demuxer, VideoMeta};25 use crate::demux::{Demuxer, VideoMeta};
26+use crate::eq::EqParams;
26 use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};27 use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};
27 28
28 /// How long the feeder waits out a full ring. The ring holds a second, so this29 /// How long the feeder waits out a full ring. The ring holds a second, so this
@@ -472,6 +473,27 @@ impl PlaybackSession {
472 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))473 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
473 }474 }
474 475
476+ /// What the clip at `idx` of `lane` is equalized with, or `None` for one
477+ /// that plays flat -- what a card shows before it lets anyone drag a band.
478+ pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
479+ self.project.eq_of(lane, idx)
480+ }
481+
482+ /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
483+ /// like every other edit -- and, like every other edit, it *reseeks*: the
484+ /// audio workers are rebuilt from the new curves right where the playhead
485+ /// is, so a band changed during playback is heard from the next chunk on
486+ /// rather than at the next play. `false` for a bad index or a non-finite
487+ /// band, and nothing changes.
488+ ///
489+ /// ponytail: the reseek is what makes it live, so the cost of a change is a
490+ /// decoder restart -- inaudible at a drag's end, but too much to call once
491+ /// per pointer sample (a caller commits one change per gesture). Upgrade
492+ /// path is an `Arc` swap the running worker polls per chunk.
493+ pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
494+ self.edit(|p| p.set_eq(lane, idx, params))
495+ }
496+
475 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,497 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
476 /// silence on the audio one, and nothing else moves. Reseeks, because what498 /// silence on the audio one, and nothing else moves. Reseeks, because what
477 /// the playhead sits on has changed. `false` for a bad index and for the499 /// the playhead sits on has changed. `false` for a bad index and for the
@@ -783,10 +805,17 @@ impl PlaybackSession {
783 // hears is every lane at once, and a lane's own gaps are silence in805 // hears is every lane at once, and a lane's own gaps are silence in
784 // it rather than a hole in the count the master clock keeps.806 // it rather than a hole in the count the master clock keeps.
785 let segs = self.project.audio_segments_from(target, fps);807 let segs = self.project.audio_segments_from(target, fps);
808+ // The equalizers beside them, one per segment: the worker filters a
809+ // segment's own samples before the mix, so a clip's curve reaches
810+ // that clip and stops. Rebuilt on every seek, which is what makes an
811+ // EQ edit audible at once -- `edit` reseeks, so the drag that
812+ // changed a band restarts the workers with the new curve already in
813+ // them, and no live channel has to reach into a running one.
814+ let eqs = self.project.audio_eqs_from(target, fps);
786 // Each source on the stream it was placed with: what plays is what815 // Each source on the stream it was placed with: what plays is what
787 // the library row said, and what an export copies (`export::run`).816 // the library row said, and what an export copies (`export::run`).
788 let sources = self.project.audio_sources();817 let sources = self.project.audio_sources();
789- audio_running = match AudioSession::open_mixed_streams(&sources, &segs) {818+ audio_running = match AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs) {
790 Ok(Some((_, rx))) => audio.spawn_feeder(rx),819 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
791 _ => false,820 _ => false,
792 };821 };
crates/engine/src/project.rsmodified+59 -5
@@ -1070,16 +1070,70 @@ impl Project {
1070 timeline_frame: u32,1070 timeline_frame: u32,
1071 fps: f64,1071 fps: f64,
1072 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {1072 ) -> Vec<Vec<(Option<usize>, f64, f64)>> {
1073- let lists: Vec<_> = self1073+ self.audio_lanes()
1074+ .into_iter()
1075+ .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
1076+ .collect()
1077+ }
1078+
1079+ /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from)
1080+ /// builds a play list for, in the same order. Public because everything
1081+ /// asked per audio lane -- which clip a segment's equalizer belongs to,
1082+ /// which lane an mp4 export would copy -- has to read the very list the
1083+ /// sound comes off, or the two answers drift apart (which is exactly how an
1084+ /// `A2`-only project once exported silently, ledger).
1085+ pub fn audio_lanes(&self) -> Vec<Lane> {
1086+ let lanes: Vec<Lane> = self
1074 .lanes()1087 .lanes()
1075 .into_iter()1088 .into_iter()
1076 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())1089 .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty())
1077- .map(|lane| self.lane_segments_from(lane, timeline_frame, fps))
1078 .collect();1090 .collect();
1079- match lists.is_empty() {1091+ match lanes.is_empty() {
1080- true => vec![self.lane_segments_from(Lane::A1, timeline_frame, fps)],1092+ // The all-gap fallback: `A1`'s own (empty) list, so a timeline with
1081- false => lists,1093+ // no sound still plays silence against the master clock.
1094+ true => vec![Lane::A1],
1095+ false => lanes,
1096+ }
1097+ }
1098+
1099+ /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s
1100+ /// segments plays through: the same lanes in the same order, one entry per
1101+ /// segment, `None` where the segment is a gap or its clip plays flat.
1102+ ///
1103+ /// A parallel list rather than a fourth element of the segment tuple: that
1104+ /// tuple is what every opener, the packet-copy path and a dozen tests speak,
1105+ /// and an effect is not part of *which samples* a segment names. A short
1106+ /// list therefore means "flat from here on" rather than a length mismatch --
1107+ /// see [`crate::AudioSession::open_mixed_streams_eq`].
1108+ pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> {
1109+ self.audio_lanes()
1110+ .into_iter()
1111+ .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps))
1112+ .collect()
1113+ }
1114+
1115+ /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching
1116+ /// [`lane_segments_from`](Project::lane_segments_from) entry for entry --
1117+ /// same walk, same `fps` refusal, so the two lists cannot come out different
1118+ /// lengths.
1119+ pub fn lane_eqs_from(
1120+ &self,
1121+ lane: Lane,
1122+ timeline_frame: u32,
1123+ fps: f64,
1124+ ) -> Vec<Option<EqParams>> {
1125+ if !(fps.is_finite() && fps > 0.0) {
1126+ return Vec::new();
1082 }1127 }
1128+ self.spans_from(lane, timeline_frame)
1129+ .iter()
1130+ // A span off a clip covers that clip's frames and no others, so its
1131+ // own start names the clip -- the index a [`Span`] does not carry.
1132+ .map(|span| {
1133+ self.map(lane, span.start)
1134+ .and_then(|(idx, _)| self.eq_of(lane, idx).cloned())
1135+ })
1136+ .collect()
1083 }1137 }
1084 1138
1085 /// Pushes the undo snapshot. Every mutating method calls this once, *after*1139 /// Pushes the undo snapshot. Every mutating method calls this once, *after*
crates/engine/tests/eq_audio.rsadded+377 -0
@@ -0,0 +1,377 @@
1+//! The per-clip equalizer where it has to be true: in the samples playback
2+//! feeds the device and in the samples an export writes, which are the same
3+//! samples by construction — both come off `AudioSession::open_mixed_streams_eq`
4+//! and the filter runs inside the per-lane worker, per segment, before the mix.
5+//!
6+//! Everything here goes through the *front door*: a `Project` is edited with
7+//! `set_eq` and then read exactly as `PlaybackSession::seek` reads it
8+//! (`audio_segments_from` + `audio_eqs_from` handed to the same opener), or
9+//! exported through `engine::export::start`. Nothing calls `EqState` directly —
10+//! `eq.rs`'s own unit tests own the filter maths; what is checked here is the
11+//! wiring: that a curve reaches its clip, only its clip, and reaches it the same
12+//! way in both directions.
13+//!
14+//! The fixtures are a 440 Hz / 880 Hz stereo tone (`gen_fixtures.sh`), so a low
15+//! shelf with its corner above both tones is a flat +12 dB on everything
16+//! audible: the expected RMS ratio is 10^(12/20) ≈ 3.98, and it is asserted as a
17+//! ratio, never as a level.
18+//!
19+//! No picture is decoded, so nothing here needs the hardware plugin.
20+
21+use std::path::{Path, PathBuf};
22+use std::time::{Duration, Instant};
23+
24+use engine::eq::{Band, BandKind, EqParams};
25+use engine::export::{ExportSettings, Format};
26+use engine::project::{Lane, LaneKind, Source};
27+use engine::{AudioSession, Clip, ExportHandle, Project};
28+
29+const RATE: u32 = 44_100;
30+const FPS: f64 = 30.0;
31+
32+/// +12 dB below 2 kHz: above both fixture tones, so every audible sample in
33+/// them is lifted by the shelf's full gain.
34+const BOOST_DB: f32 = 12.0;
35+
36+fn asset(name: &str) -> PathBuf {
37+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
38+ .join("../../assets")
39+ .join(name)
40+}
41+
42+fn boost() -> EqParams {
43+ EqParams {
44+ bands: vec![Band {
45+ freq_hz: 2000.0,
46+ gain_db: BOOST_DB,
47+ q: 0.707,
48+ kind: BandKind::LowShelf,
49+ }],
50+ }
51+}
52+
53+fn clip(start: u32, source: usize, frames: u32) -> Clip {
54+ Clip {
55+ start,
56+ in_frame: 0,
57+ out_frame: frames,
58+ source,
59+ link: None,
60+ eq: None,
61+ color: None,
62+ }
63+}
64+
65+/// One video clip and `audio` on `A1`, from `test_av.mp4` alone.
66+fn project(audio: Vec<Clip>) -> Project {
67+ let frames = audio.iter().map(Clip::end).max().unwrap_or(30);
68+ Project::from_parts(
69+ vec![Source::new(asset("test_av.mp4"), 0)],
70+ vec![
71+ (LaneKind::Video, vec![clip(0, 0, frames)]),
72+ (LaneKind::Audio, audio),
73+ ],
74+ Vec::new(),
75+ Vec::new(),
76+ )
77+ .expect("a one-source project")
78+}
79+
80+/// What the device would be fed: the exact call `PlaybackSession::seek` makes,
81+/// drained to the end. This *is* the feeder path minus the ring buffer.
82+fn play(project: &Project) -> Vec<f32> {
83+ let sources = project.audio_sources();
84+ let segs = project.audio_segments_from(0, FPS);
85+ let eqs = project.audio_eqs_from(0, FPS);
86+ let (meta, chunks) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs)
87+ .expect("open the timeline's audio")
88+ .expect("the timeline has audio");
89+ assert_eq!((meta.sample_rate, meta.channels), (RATE, 2));
90+ let mut samples = Vec::new();
91+ for chunk in chunks {
92+ samples.extend(chunk.samples);
93+ }
94+ samples
95+}
96+
97+/// Root mean square of `[from, to)` seconds of the interleaved stereo stream.
98+fn rms(samples: &[f32], from: f64, to: f64) -> f64 {
99+ let at = |secs: f64| (secs * f64::from(RATE)) as usize * 2;
100+ let window = &samples[at(from).min(samples.len())..at(to).min(samples.len())];
101+ assert!(!window.is_empty(), "no samples in [{from}, {to})");
102+ (window
103+ .iter()
104+ .map(|s| f64::from(*s) * f64::from(*s))
105+ .sum::<f64>()
106+ / window.len() as f64)
107+ .sqrt()
108+}
109+
110+/// The shelf's own gain, to within a fifth of a dB either way -- the filter is
111+/// exact, the tone is not perfectly band-limited, and the fixtures' 1 Hz pulse
112+/// makes any window a mixture.
113+fn assert_boosted(ratio: f64, what: &str) {
114+ let db = 20.0 * ratio.log10();
115+ println!("{what}: ratio {ratio:.3} = {db:+.2} dB");
116+ assert!(
117+ (db - f64::from(BOOST_DB)).abs() < 0.5,
118+ "{what} measured {db:+.2} dB, the band asks for {BOOST_DB:+.1}"
119+ );
120+}
121+
122+fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> {
123+ let started = Instant::now();
124+ while !handle.is_finished() {
125+ assert!(
126+ started.elapsed() < limit,
127+ "export did not finish in {limit:?}"
128+ );
129+ std::thread::sleep(Duration::from_millis(10));
130+ }
131+ handle.result().expect("a finished export has an outcome")
132+}
133+
134+fn out_path(name: &str, ext: &str) -> PathBuf {
135+ let path = std::env::temp_dir().join(format!("ve_eq_{name}_{}.{ext}", std::process::id()));
136+ let _ = std::fs::remove_file(&path);
137+ path
138+}
139+
140+fn meta() -> engine::VideoMeta {
141+ engine::demux::Demuxer::open(&asset("test_av.mp4"))
142+ .expect("open test_av")
143+ .0
144+}
145+
146+/// Samples of a written file back through the engine's own reader.
147+fn decode(path: &Path) -> Vec<f32> {
148+ let (_, chunks) = AudioSession::open(path)
149+ .expect("reopen the export")
150+ .expect("the export has audio");
151+ let mut samples = Vec::new();
152+ for chunk in chunks {
153+ samples.extend(chunk.samples);
154+ }
155+ samples
156+}
157+
158+/// The whole claim in one line: a clip given a band comes out of the feeder
159+/// path that much louder than the same clip without it -- and a project nobody
160+/// has equalized comes out of the *new* opener bit for bit what the old one
161+/// gave, which is the identity promise the rest of the engine rests on.
162+#[test]
163+fn an_equalized_clip_plays_that_much_louder_and_a_flat_one_not_at_all() {
164+ let flat = project(vec![clip(0, 0, 30)]);
165+ let mut eqd = flat.clone();
166+ assert!(eqd.set_eq(Lane::A1, 0, Some(boost())));
167+
168+ let plain = play(&flat);
169+ let boosted = play(&eqd);
170+ assert_eq!(
171+ plain.len(),
172+ boosted.len(),
173+ "the edit is a filter, not a trim"
174+ );
175+ assert_boosted(
176+ rms(&boosted, 0.05, 0.95) / rms(&plain, 0.05, 0.95),
177+ "playback",
178+ );
179+
180+ // No equalizer anywhere: the samples are the ones the opener gave before
181+ // there was an equalizer at all, to the bit.
182+ let sources = flat.audio_sources();
183+ let segs = flat.audio_segments_from(0, FPS);
184+ let (_, chunks) = AudioSession::open_mixed_streams(&sources, &segs)
185+ .expect("open")
186+ .expect("has audio");
187+ let old: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
188+ assert_eq!(old, plain, "an EQ-less project must decode bit-identically");
189+
190+ // ...and so does one carrying a curve that moves nothing: `is_identity`
191+ // short-circuits inside `EqState::process`, and this is the path that says
192+ // the short-circuit is really on.
193+ let mut identity = flat.clone();
194+ assert!(identity.set_eq(Lane::A1, 0, Some(EqParams::default_layout())));
195+ assert!(identity.eq_of(Lane::A1, 0).is_some(), "the curve is stored");
196+ assert_eq!(
197+ play(&identity),
198+ plain,
199+ "a flat curve must not touch a sample"
200+ );
201+}
202+
203+/// The reason the filter lives in the worker and not over the mix: two clips
204+/// with different settings must not bleed into each other. One second boosted,
205+/// one second not, on one lane, out of one decoder.
206+#[test]
207+fn a_band_reaches_its_own_clip_and_stops_at_the_cut() {
208+ let mut p = project(vec![clip(0, 0, 30), clip(30, 0, 30)]);
209+ let plain = play(&p);
210+ assert!(p.set_eq(Lane::A1, 1, Some(boost())));
211+ let boosted = play(&p);
212+
213+ assert_boosted(
214+ rms(&boosted, 1.05, 1.95) / rms(&plain, 1.05, 1.95),
215+ "the equalized second clip",
216+ );
217+ // The clip before it is untouched -- and untouched to the *bit*, not merely
218+ // to a level: a filter whose memory carried across the join would show up
219+ // here as a fraction of a dB and pass any ratio test.
220+ let second = (1.0 * f64::from(RATE)) as usize * 2;
221+ assert_eq!(
222+ boosted[..second],
223+ plain[..second],
224+ "the flat clip before the cut moved"
225+ );
226+}
227+
228+/// Two lanes, a band on one of them: the sum must differ by exactly what that
229+/// lane's own samples changed by, which is only true if each lane is filtered
230+/// before it is added. Filtering the mix instead would smear the curve over the
231+/// other lane as well, and this is the difference that would show it.
232+#[test]
233+fn a_lane_is_equalized_before_the_mix_and_never_after_it() {
234+ let mut p = Project::from_parts(
235+ vec![Source::new(asset("test_av.mp4"), 0)],
236+ vec![
237+ (LaneKind::Video, vec![clip(0, 0, 30)]),
238+ (LaneKind::Audio, vec![clip(0, 0, 30)]),
239+ (LaneKind::Audio, vec![clip(0, 0, 30)]),
240+ ],
241+ Vec::new(),
242+ Vec::new(),
243+ )
244+ .expect("a two-audio-lane project");
245+ assert_eq!(p.audio_lanes().len(), 2, "both lanes hold something");
246+
247+ let mixed = play(&p);
248+ let a2 = Lane::new(LaneKind::Audio, 1);
249+ assert!(p.set_eq(a2, 0, Some(boost())));
250+ let mixed_eqd = play(&p);
251+
252+ // What A2 alone sounds like either way, taken off the single-lane path.
253+ let lone = project(vec![clip(0, 0, 30)]);
254+ let mut lone_eqd = lone.clone();
255+ assert!(lone_eqd.set_eq(Lane::A1, 0, Some(boost())));
256+ let (flat, boosted) = (play(&lone), play(&lone_eqd));
257+
258+ let n = mixed
259+ .len()
260+ .min(mixed_eqd.len())
261+ .min(flat.len())
262+ .min(boosted.len());
263+ let mut worst = 0.0f32;
264+ for i in 0..n {
265+ worst = worst.max(((mixed_eqd[i] - mixed[i]) - (boosted[i] - flat[i])).abs());
266+ }
267+ println!("mix-vs-lane worst difference: {worst:e}");
268+ // Not zero: the two runs decode the same source twice and AAC's noise
269+ // substitution reseeds per decoder (`open_segments`, measured below 1e-3).
270+ assert!(
271+ worst < 1e-3,
272+ "the mix changed by {worst} more than the equalized lane did -- the filter is on the sum"
273+ );
274+}
275+
276+/// The export half of the same claim, through `export::start`: what is written
277+/// is what is heard, so the WAV carries the boost at the same ratio the feeder
278+/// path measured.
279+#[test]
280+fn a_wav_export_carries_the_same_boost_playback_does() {
281+ let flat = project(vec![clip(0, 0, 30)]);
282+ let mut eqd = flat.clone();
283+ assert!(eqd.set_eq(Lane::A1, 0, Some(boost())));
284+
285+ let mut written = Vec::new();
286+ for (name, project) in [("flat", &flat), ("eqd", &eqd)] {
287+ let out = out_path(name, "wav");
288+ let handle = engine::export::start(
289+ project.clone(),
290+ meta(),
291+ &out,
292+ &ExportSettings {
293+ format: Format::Wav,
294+ ..Default::default()
295+ },
296+ );
297+ wait(&handle, Duration::from_secs(60)).expect("wav export");
298+ written.push(decode(&out));
299+ std::fs::remove_file(&out).unwrap();
300+ }
301+ let [plain, boosted] = &written[..] else {
302+ unreachable!("two exports")
303+ };
304+ assert_boosted(
305+ rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95),
306+ "wav export",
307+ );
308+ // ...and the same number to the ear: the export is not a second, kinder
309+ // filter run at a different point in the chain.
310+ let played = rms(&play(&eqd), 0.05, 0.95) / rms(&play(&flat), 0.05, 0.95);
311+ let exported = rms(boosted, 0.05, 0.95) / rms(plain, 0.05, 0.95);
312+ assert!(
313+ (played - exported).abs() < 0.05,
314+ "playback boosted by {played:.3} and the export by {exported:.3}"
315+ );
316+}
317+
318+/// An mp4 export *copies* AAC packets, and no filter can reach a packet copy.
319+/// Refused by name, with the clip's own position in it -- silently writing the
320+/// clip flat is the one failure nobody would notice.
321+#[test]
322+fn an_mp4_export_refuses_an_equalized_clip_and_names_where_it_is() {
323+ let mut p = project(vec![clip(0, 0, 30), clip(30, 0, 30)]);
324+ assert!(p.set_eq(Lane::A1, 1, Some(boost())));
325+
326+ let out = out_path("refused", "mp4");
327+ let handle = engine::export::start(p.clone(), meta(), &out, &ExportSettings::default());
328+ let err = wait(&handle, Duration::from_secs(60))
329+ .expect_err("an equalized clip cannot leave through the copy path")
330+ .to_string();
331+ println!("mp4 refusal: {err}");
332+ assert!(err.contains("00:01"), "the refusal names the clip: {err}");
333+ assert!(err.contains("equalizer"), "{err}");
334+ assert!(err.contains("WAV or FLAC"), "and the way out: {err}");
335+ assert!(!out.exists(), "a refused export leaves no file");
336+
337+ // Taking the curve off is all it takes -- the refusal is about the setting,
338+ // never about the clip having once had one.
339+ assert!(p.set_eq(Lane::A1, 1, None));
340+ let handle = engine::export::start(p, meta(), &out, &ExportSettings::default());
341+ wait(&handle, Duration::from_secs(120)).expect("a flat timeline exports as mp4");
342+ std::fs::remove_file(&out).unwrap();
343+}
344+
345+/// A band moved while the timeline is playing: `PlaybackSession::set_eq` writes
346+/// the project and reseeks, and a reseek rebuilds the workers from
347+/// `audio_eqs_from`. This is that mechanism without a sound device -- the edit,
348+/// then the very list the reopen is built from, then the samples it yields.
349+#[test]
350+fn a_band_changed_mid_play_is_in_the_next_chunk_the_worker_makes() {
351+ let mut p = project(vec![clip(0, 0, 30)]);
352+ assert!(
353+ p.audio_eqs_from(0, FPS)[0][0].is_none(),
354+ "flat to begin with"
355+ );
356+ let before = play(&p);
357+
358+ assert!(p.set_eq(Lane::A1, 0, Some(boost())));
359+ // The reopen list is rebuilt from the project every seek, so the edit is in
360+ // it the moment it lands -- no channel has to reach into a running worker.
361+ assert_eq!(
362+ p.audio_eqs_from(0, FPS)[0][0].as_ref(),
363+ Some(&boost()),
364+ "the seek's own list carries the new curve"
365+ );
366+ let after = play(&p);
367+ assert_ne!(before, after, "the samples changed");
368+ assert_boosted(
369+ rms(&after, 0.05, 0.95) / rms(&before, 0.05, 0.95),
370+ "after the edit",
371+ );
372+
373+ // And undo is the way back, one step, samples and all.
374+ assert!(p.undo());
375+ assert!(p.audio_eqs_from(0, FPS)[0][0].is_none());
376+ assert_eq!(play(&p), before, "undo puts the flat samples back");
377+}