Merge branch 'worktree-agent-a232dc4bae73c9b20'
Browse files at this commit7 changed files +1129 -48
- crates/app/src/keymap.rs +40 -6
- crates/app/src/main.rs +482 -25
- crates/engine/src/audio.rs +98 -6
- crates/engine/src/export.rs +43 -5
- crates/engine/src/playback.rs +30 -1
- crates/engine/src/project.rs +59 -5
- crates/engine/tests/eq_audio.rs +377 -0
crates/app/src/keymap.rsmodified+40 -6
| @@ -53,13 +53,14 @@ pub enum ActionId { | ||
| 53 | 53 | ToggleMute, |
| 54 | 54 | VolumeUp, |
| 55 | 55 | VolumeDown, |
| 56 | + Equalizer, | |
| 56 | 57 | CancelExport, |
| 57 | 58 | } |
| 58 | 59 | |
| 59 | 60 | impl ActionId { |
| 60 | 61 | /// Display order everywhere -- the editor lists them in it and |
| 61 | 62 | /// [`Keymap::defaults`] binds them in it. |
| 62 | - pub const ALL: [ActionId; 16] = [ | |
| 63 | + pub const ALL: [ActionId; 17] = [ | |
| 63 | 64 | ActionId::Play, |
| 64 | 65 | ActionId::Export, |
| 65 | 66 | ActionId::Save, |
| @@ -75,6 +76,7 @@ impl ActionId { | ||
| 75 | 76 | ActionId::ToggleMute, |
| 76 | 77 | ActionId::VolumeUp, |
| 77 | 78 | ActionId::VolumeDown, |
| 79 | + ActionId::Equalizer, | |
| 78 | 80 | ActionId::CancelExport, |
| 79 | 81 | ]; |
| 80 | 82 | |
| @@ -96,6 +98,7 @@ impl ActionId { | ||
| 96 | 98 | ActionId::ToggleMute => "Mute / Unmute", |
| 97 | 99 | ActionId::VolumeUp => "Volume up", |
| 98 | 100 | ActionId::VolumeDown => "Volume down", |
| 101 | + ActionId::Equalizer => "Equalizer", | |
| 99 | 102 | ActionId::CancelExport => "Cancel export", |
| 100 | 103 | } |
| 101 | 104 | } |
| @@ -119,6 +122,7 @@ impl ActionId { | ||
| 119 | 122 | ActionId::ToggleMute => "toggle-mute", |
| 120 | 123 | ActionId::VolumeUp => "volume-up", |
| 121 | 124 | ActionId::VolumeDown => "volume-down", |
| 125 | + ActionId::Equalizer => "equalizer", | |
| 122 | 126 | ActionId::CancelExport => "cancel-export", |
| 123 | 127 | } |
| 124 | 128 | } |
| @@ -139,7 +143,10 @@ impl ActionId { | ||
| 139 | 143 | | ActionId::Undo |
| 140 | 144 | | ActionId::AddVideoLane |
| 141 | 145 | | ActionId::AddAudioLane => Category::Editing, |
| 142 | - ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown => Category::Audio, | |
| 146 | + ActionId::ToggleMute | |
| 147 | + | ActionId::VolumeUp | |
| 148 | + | ActionId::VolumeDown | |
| 149 | + | ActionId::Equalizer => Category::Audio, | |
| 143 | 150 | ActionId::Save | ActionId::Export | ActionId::CancelExport => Category::File, |
| 144 | 151 | } |
| 145 | 152 | } |
| @@ -191,7 +198,7 @@ pub struct Fixed { | ||
| 191 | 198 | pub category: Category, |
| 192 | 199 | } |
| 193 | 200 | |
| 194 | -pub const FIXED: [Fixed; 5] = [ | |
| 201 | +pub const FIXED: [Fixed; 9] = [ | |
| 195 | 202 | Fixed { |
| 196 | 203 | chord: "esc", |
| 197 | 204 | label: "Close this card or clip menu, or cancel a capture", |
| @@ -217,6 +224,29 @@ pub const FIXED: [Fixed; 5] = [ | ||
| 217 | 224 | label: "Erase a bitrate digit", |
| 218 | 225 | category: Category::File, |
| 219 | 226 | }, |
| 227 | + // The equalizer card's own input, for the same reason the export card has | |
| 228 | + // its own: a band nothing but a drag can reach is a band half the users of | |
| 229 | + // this editor cannot move at all. Card-local, so none of them is bindable. | |
| 230 | + Fixed { | |
| 231 | + chord: "1–5", | |
| 232 | + label: "Pick an equalizer band", | |
| 233 | + category: Category::Audio, | |
| 234 | + }, | |
| 235 | + Fixed { | |
| 236 | + chord: "up", | |
| 237 | + label: "Raise the picked band 1 dB", | |
| 238 | + category: Category::Audio, | |
| 239 | + }, | |
| 240 | + Fixed { | |
| 241 | + chord: "down", | |
| 242 | + label: "Lower the picked band 1 dB", | |
| 243 | + category: Category::Audio, | |
| 244 | + }, | |
| 245 | + Fixed { | |
| 246 | + chord: "r", | |
| 247 | + label: "Flatten every band", | |
| 248 | + category: Category::Audio, | |
| 249 | + }, | |
| 220 | 250 | ]; |
| 221 | 251 | |
| 222 | 252 | /// A stroke as the key handler sees it: gpui's key name plus the one modifier |
| @@ -333,6 +363,9 @@ impl Keymap { | ||
| 333 | 363 | // player has, without asking for shift to make the "+". |
| 334 | 364 | b(ActionId::VolumeUp, "=", false), |
| 335 | 365 | b(ActionId::VolumeDown, "-", false), |
| 366 | + // The one free letter that says the word: "e" is already the | |
| 367 | + // export and an equalizer is the q in nobody else's way. | |
| 368 | + b(ActionId::Equalizer, "q", false), | |
| 336 | 369 | b(ActionId::CancelExport, "escape", false), |
| 337 | 370 | ], |
| 338 | 371 | } |
| @@ -559,7 +592,7 @@ mod tests { | ||
| 559 | 592 | #[test] |
| 560 | 593 | fn every_default_stroke_reaches_its_action() { |
| 561 | 594 | let k = Keymap::defaults(); |
| 562 | - assert_eq!(k.entries().len(), 18); | |
| 595 | + assert_eq!(k.entries().len(), 19); | |
| 563 | 596 | assert_eq!(k.lookup("space", false), Some(ActionId::Play)); |
| 564 | 597 | assert_eq!(k.lookup("e", false), Some(ActionId::Export)); |
| 565 | 598 | assert_eq!(k.lookup("s", true), Some(ActionId::Save)); |
| @@ -576,6 +609,7 @@ mod tests { | ||
| 576 | 609 | assert_eq!(k.lookup("v", false), Some(ActionId::AddVideoLane)); |
| 577 | 610 | assert_eq!(k.lookup("a", false), Some(ActionId::AddAudioLane)); |
| 578 | 611 | assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); |
| 612 | + assert_eq!(k.lookup("q", false), Some(ActionId::Equalizer)); | |
| 579 | 613 | // The volume pair is the unshifted one, so neither needs a modifier |
| 580 | 614 | // and neither is the "+" gpui reports for shift+=. |
| 581 | 615 | assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp)); |
| @@ -585,7 +619,7 @@ mod tests { | ||
| 585 | 619 | // The modifier is half the chord: ctrl+e is not e. |
| 586 | 620 | assert_eq!(k.lookup("e", true), None); |
| 587 | 621 | assert_eq!(k.lookup("space", true), None); |
| 588 | - assert_eq!(k.lookup("q", false), None); | |
| 622 | + assert_eq!(k.lookup("j", false), None); | |
| 589 | 623 | // Nothing is bound twice, or lookup's first match would be a coin toss. |
| 590 | 624 | for (i, a) in k.entries().iter().enumerate() { |
| 591 | 625 | assert!( |
| @@ -709,7 +743,7 @@ mod tests { | ||
| 709 | 743 | ); |
| 710 | 744 | // The label is the editor's column, and never the file's word for it. |
| 711 | 745 | assert_eq!(ActionId::CancelExport.label(), "Cancel export"); |
| 712 | - assert_eq!(ActionId::ALL.len(), 16); | |
| 746 | + assert_eq!(ActionId::ALL.len(), 17); | |
| 713 | 747 | } |
| 714 | 748 | |
| 715 | 749 | #[test] |
crates/app/src/main.rsmodified+482 -25
| @@ -10,6 +10,7 @@ use std::sync::Arc; | ||
| 10 | 10 | use std::time::{Duration, Instant}; |
| 11 | 11 | |
| 12 | 12 | use engine::audio::StreamInfo; |
| 13 | +use engine::eq::{Band, BandKind, EqParams}; | |
| 13 | 14 | use engine::export::{ExportSettings, Format}; |
| 14 | 15 | use engine::project::{Lane, LaneKind, Source}; |
| 15 | 16 | use engine::{Clip, ExportHandle, Frame, PlaybackSession}; |
| @@ -219,14 +220,28 @@ struct ContextMenu { | ||
| 219 | 220 | /// action a stroke already reaches -- the menu is a second way *to* the actions |
| 220 | 221 | /// and never a second version of them -- so both the label and the hint come |
| 221 | 222 | /// out of the keymap registry and the two can never disagree. |
| 222 | -const MENU_ITEMS: [ActionId; 5] = [ | |
| 223 | +const MENU_ITEMS: [ActionId; 6] = [ | |
| 223 | 224 | ActionId::Cut, |
| 224 | 225 | ActionId::Delete, |
| 225 | 226 | ActionId::Lift, |
| 226 | 227 | ActionId::Regroup, |
| 228 | + ActionId::Equalizer, | |
| 227 | 229 | ActionId::ToggleMute, |
| 228 | 230 | ]; |
| 229 | 231 | |
| 232 | +/// How far a band may be pushed either way, in dB. The engine clamps nothing | |
| 233 | +/// here -- it will filter whatever it is given -- so this is a UI decision: | |
| 234 | +/// past about this a peaking band stops sounding like tone and starts sounding | |
| 235 | +/// like a fault. | |
| 236 | +const EQ_GAIN_LIMIT: f32 = 12.; | |
| 237 | + | |
| 238 | +/// One dB per keystroke, which is roughly the smallest step anyone hears on a | |
| 239 | +/// single band. | |
| 240 | +const EQ_STEP: f32 = 1.; | |
| 241 | + | |
| 242 | +/// The gain bar's height inside a band row. | |
| 243 | +const EQ_BAR_H: f32 = 6.; | |
| 244 | + | |
| 230 | 245 | struct Player { |
| 231 | 246 | /// The timeline, once there is one. A run with no file opens without it and |
| 232 | 247 | /// waits: the first media import or project load is what fills it, and |
| @@ -321,6 +336,26 @@ struct Player { | ||
| 321 | 336 | /// Which file the card will write. Kept across closes like the quality, and |
| 322 | 337 | /// what [`Player::export_path`](Player) is named after. |
| 323 | 338 | format: Format, |
| 339 | + /// The equalizer card is up on this clip -- the lane and index it was | |
| 340 | + /// opened on. Held rather than re-read from `selected` every paint because | |
| 341 | + /// the card is modal: while it is up nothing else can move an index, and | |
| 342 | + /// the one edit it makes (`set_eq`) moves none. | |
| 343 | + eq_open: Option<(Lane, usize)>, | |
| 344 | + /// The curve the card is showing, which is the clip's own or the flat | |
| 345 | + /// five-band default. Edited live and written at the clip once per gesture | |
| 346 | + /// ([`Player::commit_eq`]): the project's equalizer table is append-only, so | |
| 347 | + /// a write per pointer sample would be a table entry -- and an undo step -- | |
| 348 | + /// per pixel. | |
| 349 | + eq_params: EqParams, | |
| 350 | + /// Which band the keyboard moves, and which one a drag is holding. | |
| 351 | + eq_band: usize, | |
| 352 | + /// A band's bar is being dragged. Tracked on the root like `scrubbing`, for | |
| 353 | + /// the same reason: the pointer leaves the 6 px bar immediately. | |
| 354 | + eq_dragging: bool, | |
| 355 | + /// A band bar's own box, recorded at prepaint. One probe for five rows: | |
| 356 | + /// they are laid out identically and only the *x* of a click is read | |
| 357 | + /// ([`frac_along`]), so whichever row painted last answers for all of them. | |
| 358 | + eq_bar: Rc<Cell<Bounds<Pixels>>>, | |
| 324 | 359 | /// The action whose row is waiting for a stroke. The next key that is |
| 325 | 360 | /// neither escape nor a lone modifier becomes the whole of what reaches it. |
| 326 | 361 | rebinding: Option<ActionId>, |
| @@ -437,6 +472,7 @@ impl Player { | ||
| 437 | 472 | ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx), |
| 438 | 473 | ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx), |
| 439 | 474 | ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx), |
| 475 | + ActionId::Equalizer => self.open_eq(cx), | |
| 440 | 476 | // Nothing to cancel while nothing is exporting; the export guard in |
| 441 | 477 | // the key handler is what answers this one while there is. |
| 442 | 478 | ActionId::CancelExport => {} |
| @@ -447,7 +483,103 @@ impl Player { | ||
| 447 | 483 | /// out of reach, so a right-click there opens no menu -- the same rule the |
| 448 | 484 | /// key handler and the drop target already follow. |
| 449 | 485 | fn modal(&self) -> bool { |
| 450 | - self.keys_open || self.export_open || self.exporting().is_some() | |
| 486 | + self.keys_open || self.export_open || self.eq_open.is_some() || self.exporting().is_some() | |
| 487 | + } | |
| 488 | + | |
| 489 | + /// Opens the equalizer on the selected clip. Audio only, and it says so | |
| 490 | + /// rather than opening a card of bands that would reach nothing: a video | |
| 491 | + /// clip carries no sound of its own here (the sound is the audio lane's), | |
| 492 | + /// and the model would take the setting without anything ever playing it. | |
| 493 | + fn open_eq(&mut self, cx: &mut Context<Self>) { | |
| 494 | + if self.exporting().is_some() { | |
| 495 | + return; | |
| 496 | + } | |
| 497 | + let refusal = match (self.selected, &self.session) { | |
| 498 | + (_, None) => Some("NO TIMELINE — open a file first"), | |
| 499 | + (None, _) => Some("NOTHING SELECTED — click an audio clip, then ask again"), | |
| 500 | + (Some((lane, _)), _) if lane.kind != LaneKind::Audio => Some( | |
| 501 | + "NOT AN AUDIO CLIP — the equalizer works on the sound, so pick a clip in an audio lane", | |
| 502 | + ), | |
| 503 | + _ => None, | |
| 504 | + }; | |
| 505 | + if let Some(refusal) = refusal { | |
| 506 | + self.notice = Some(refusal.into()); | |
| 507 | + cx.notify(); | |
| 508 | + return; | |
| 509 | + } | |
| 510 | + let (lane, idx) = self.selected.expect("checked above"); | |
| 511 | + let session = self.session.as_ref().expect("checked above"); | |
| 512 | + // What the clip already plays through, or the flat default -- so the | |
| 513 | + // card opens on the curve that is in force and a reopen shows the last | |
| 514 | + // drag rather than a fresh set of zeroes. | |
| 515 | + self.eq_params = session | |
| 516 | + .eq_of(lane, idx) | |
| 517 | + .cloned() | |
| 518 | + .unwrap_or_else(EqParams::default_layout); | |
| 519 | + self.eq_band = 0; | |
| 520 | + self.eq_dragging = false; | |
| 521 | + self.eq_open = Some((lane, idx)); | |
| 522 | + // One card at a time, the rule the other two already follow. | |
| 523 | + self.keys_open = false; | |
| 524 | + self.export_open = false; | |
| 525 | + self.context_menu = None; | |
| 526 | + cx.notify(); | |
| 527 | + } | |
| 528 | + | |
| 529 | + /// Writes what the card is showing at its clip: one undo step, one entry in | |
| 530 | + /// the append-only equalizer table, so this is called once per *gesture* -- | |
| 531 | + /// the end of a drag, a keystroke -- and never per pointer sample. | |
| 532 | + /// | |
| 533 | + /// A curve that moves nothing is stored as *no* equalizer at all, which is | |
| 534 | + /// what keeps a clip nobody has touched on the identity path through | |
| 535 | + /// playback and export (`engine::eq::EqParams::is_identity`). | |
| 536 | + fn commit_eq(&mut self, cx: &mut Context<Self>) { | |
| 537 | + let Some((lane, idx)) = self.eq_open else { | |
| 538 | + return; | |
| 539 | + }; | |
| 540 | + let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone()); | |
| 541 | + if let Some(session) = &mut self.session { | |
| 542 | + session.set_eq(lane, idx, params); | |
| 543 | + } | |
| 544 | + // `set_eq` reseeks inside the engine -- that is what makes the change | |
| 545 | + // audible at once -- and a reseek is what these flags are about. | |
| 546 | + self.reset_after_reseek(); | |
| 547 | + cx.notify(); | |
| 548 | + } | |
| 549 | + | |
| 550 | + /// Moves one band and says whether anything changed. Live only: the write | |
| 551 | + /// is [`commit_eq`](Player::commit_eq)'s. | |
| 552 | + fn set_band(&mut self, band: usize, gain_db: f32) -> bool { | |
| 553 | + let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT); | |
| 554 | + match self.eq_params.bands.get_mut(band) { | |
| 555 | + Some(b) if b.gain_db != gain_db => { | |
| 556 | + b.gain_db = gain_db; | |
| 557 | + true | |
| 558 | + } | |
| 559 | + _ => false, | |
| 560 | + } | |
| 561 | + } | |
| 562 | + | |
| 563 | + /// The keyboard's version of a drag: one step on the picked band, committed | |
| 564 | + /// straight away -- a keystroke has no release to wait for. | |
| 565 | + fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) { | |
| 566 | + let gain = self | |
| 567 | + .eq_params | |
| 568 | + .bands | |
| 569 | + .get(self.eq_band) | |
| 570 | + .map_or(0., |b| b.gain_db); | |
| 571 | + if self.set_band(self.eq_band, gain + by) { | |
| 572 | + self.commit_eq(cx); | |
| 573 | + } | |
| 574 | + } | |
| 575 | + | |
| 576 | + /// Where the pointer sits along a band's bar, as a gain: the middle is flat | |
| 577 | + /// and the two ends are the limit either way. | |
| 578 | + fn drag_band(&mut self, x: Pixels, cx: &mut Context<Self>) { | |
| 579 | + let gain = (frac_along(x, self.eq_bar.get()) * 2. - 1.) * EQ_GAIN_LIMIT; | |
| 580 | + if self.set_band(self.eq_band, gain) { | |
| 581 | + cx.notify(); | |
| 582 | + } | |
| 451 | 583 | } |
| 452 | 584 | |
| 453 | 585 | /// Jumps the timeline. |
| @@ -1259,6 +1391,38 @@ impl Render for Player { | ||
| 1259 | 1391 | cx.notify(); |
| 1260 | 1392 | return; |
| 1261 | 1393 | } |
| 1394 | + // And the equalizer card, the same way again. Its own strokes | |
| 1395 | + // are the card's input, exactly as the export card's digits | |
| 1396 | + // are: a band reachable only by dragging is a band a keyboard | |
| 1397 | + // cannot move at all, and every one of them is listed in the | |
| 1398 | + // keys menu (keymap.rs `FIXED`) rather than being a secret. | |
| 1399 | + if this.eq_open.is_some() { | |
| 1400 | + if key == ESCAPE { | |
| 1401 | + // Nothing to undo: every change is already at the clip, | |
| 1402 | + // and undo is undo's own key. | |
| 1403 | + this.eq_open = None; | |
| 1404 | + this.eq_dragging = false; | |
| 1405 | + } else if key == "up" { | |
| 1406 | + this.nudge_band(EQ_STEP, cx); | |
| 1407 | + } else if key == "down" { | |
| 1408 | + this.nudge_band(-EQ_STEP, cx); | |
| 1409 | + } else if key == "r" { | |
| 1410 | + for band in &mut this.eq_params.bands { | |
| 1411 | + band.gain_db = 0.; | |
| 1412 | + } | |
| 1413 | + this.commit_eq(cx); | |
| 1414 | + } else if let Ok(digit) = key.parse::<usize>() { | |
| 1415 | + // 1-based, as the rows are numbered on screen; a digit | |
| 1416 | + // past the last band picks nothing rather than panics. | |
| 1417 | + if let Some(band) = digit.checked_sub(1) | |
| 1418 | + && band < this.eq_params.bands.len() | |
| 1419 | + { | |
| 1420 | + this.eq_band = band; | |
| 1421 | + } | |
| 1422 | + } | |
| 1423 | + cx.notify(); | |
| 1424 | + return; | |
| 1425 | + } | |
| 1262 | 1426 | // A clip menu names an index, and every edit below moves |
| 1263 | 1427 | // indices -- so a stroke closes it before it acts. Escape means |
| 1264 | 1428 | // that and nothing else, which is the `esc` the keys menu |
| @@ -1284,7 +1448,7 @@ impl Render for Player { | ||
| 1284 | 1448 | // sibling it can stop. The export card is over the timeline for |
| 1285 | 1449 | // the same reason: importing under it would change the very |
| 1286 | 1450 | // edit list the card is about to write out. |
| 1287 | - if this.keys_open || this.export_open { | |
| 1451 | + if this.keys_open || this.export_open || this.eq_open.is_some() { | |
| 1288 | 1452 | return; |
| 1289 | 1453 | } |
| 1290 | 1454 | for path in paths.paths() { |
| @@ -1300,6 +1464,20 @@ impl Render for Player { | ||
| 1300 | 1464 | // 6 px ruler on the first drag and its own listeners then stop |
| 1301 | 1465 | // firing; the root's hitbox is the whole window. |
| 1302 | 1466 | .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| { |
| 1467 | + // A band's bar is 6 px tall and the pointer leaves it at once, | |
| 1468 | + // so the equalizer drag is tracked here for the ruler's reason. | |
| 1469 | + if this.eq_dragging { | |
| 1470 | + if event.pressed_button == Some(MouseButton::Left) { | |
| 1471 | + this.drag_band(event.position.x, cx); | |
| 1472 | + } else { | |
| 1473 | + // Released outside the window: the up below never came, | |
| 1474 | + // so this is where the gesture ends -- and it still owes | |
| 1475 | + // the one write the whole drag is worth. | |
| 1476 | + this.eq_dragging = false; | |
| 1477 | + this.commit_eq(cx); | |
| 1478 | + } | |
| 1479 | + return; | |
| 1480 | + } | |
| 1303 | 1481 | if !this.scrubbing { |
| 1304 | 1482 | return; |
| 1305 | 1483 | } |
| @@ -1315,6 +1493,13 @@ impl Render for Player { | ||
| 1315 | 1493 | .on_mouse_up( |
| 1316 | 1494 | MouseButton::Left, |
| 1317 | 1495 | cx.listener(|this, event: &MouseUpEvent, _, cx| { |
| 1496 | + if std::mem::take(&mut this.eq_dragging) { | |
| 1497 | + // The release lands exactly, then the gesture is written | |
| 1498 | + // once -- the append-only table's whole reason. | |
| 1499 | + this.drag_band(event.position.x, cx); | |
| 1500 | + this.commit_eq(cx); | |
| 1501 | + return; | |
| 1502 | + } | |
| 1318 | 1503 | if std::mem::take(&mut this.scrubbing) { |
| 1319 | 1504 | this.scrub_to(event.position.x, true, cx); |
| 1320 | 1505 | } |
| @@ -1387,6 +1572,7 @@ impl Render for Player { | ||
| 1387 | 1572 | // column, and only one of the two is ever up. |
| 1388 | 1573 | .children(self.keys_overlay(cx)) |
| 1389 | 1574 | .children(self.export_card(cx)) |
| 1575 | + .children(self.eq_card(cx)) | |
| 1390 | 1576 | } |
| 1391 | 1577 | } |
| 1392 | 1578 | |
| @@ -2261,6 +2447,158 @@ impl Player { | ||
| 2261 | 2447 | ) |
| 2262 | 2448 | } |
| 2263 | 2449 | |
| 2450 | + /// The equalizer of one audio clip: a row per band, each a bar that reads | |
| 2451 | + /// flat in the middle and is dragged either way, and a row that flattens | |
| 2452 | + /// them all. The same scrim, width and rows as the other two cards, and the | |
| 2453 | + /// same plain divs -- nothing here takes focus, so the root keeps the | |
| 2454 | + /// keyboard and the card's own strokes (`1`–`5`, up, down, `r`) reach it. | |
| 2455 | + /// | |
| 2456 | + /// Every change is written at the clip as it is made | |
| 2457 | + /// ([`Player::commit_eq`]), so what the card shows is always what is | |
| 2458 | + /// playing: there is no OK button to forget, and closing it changes | |
| 2459 | + /// nothing. What takes a curve back off is undo, like every other edit. | |
| 2460 | + fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> { | |
| 2461 | + let (lane, idx) = self.eq_open?; | |
| 2462 | + let rows: Vec<_> = self | |
| 2463 | + .eq_params | |
| 2464 | + .bands | |
| 2465 | + .iter() | |
| 2466 | + .enumerate() | |
| 2467 | + .map(|(i, band)| { | |
| 2468 | + let (left, width) = eq_fill(band.gain_db); | |
| 2469 | + div() | |
| 2470 | + .id(("eq-band", i)) | |
| 2471 | + .flex() | |
| 2472 | + .min_h(px(KEYS_ROW_H)) | |
| 2473 | + .items_center() | |
| 2474 | + .gap(px(12.)) | |
| 2475 | + .px(px(6.)) | |
| 2476 | + .rounded(px(3.)) | |
| 2477 | + .cursor_pointer() | |
| 2478 | + .when(i == self.eq_band, |d| d.bg(rgb(SELECTED))) | |
| 2479 | + .hover(|s| s.bg(rgb(HOVER))) | |
| 2480 | + // The press picks the band *and* is already the first | |
| 2481 | + // sample of the drag, so a plain click sets a value. | |
| 2482 | + .on_mouse_down( | |
| 2483 | + MouseButton::Left, | |
| 2484 | + cx.listener(move |this, event: &MouseDownEvent, _, cx| { | |
| 2485 | + this.eq_band = i; | |
| 2486 | + this.eq_dragging = true; | |
| 2487 | + this.drag_band(event.position.x, cx); | |
| 2488 | + }), | |
| 2489 | + ) | |
| 2490 | + .child( | |
| 2491 | + div() | |
| 2492 | + .flex_none() | |
| 2493 | + // Wide enough for "12 kHz high shelf", so the bars | |
| 2494 | + // below each other all start at the same pixel. | |
| 2495 | + .w(px(112.)) | |
| 2496 | + .text_size(px(11.)) | |
| 2497 | + .child(format!("{} {}", i + 1, band_label(band))), | |
| 2498 | + ) | |
| 2499 | + .child( | |
| 2500 | + div() | |
| 2501 | + .flex_1() | |
| 2502 | + .h(px(EQ_BAR_H)) | |
| 2503 | + .rounded(px(3.)) | |
| 2504 | + .bg(rgb(SURFACE)) | |
| 2505 | + .child(bounds_probe(self.eq_bar.clone())) | |
| 2506 | + .child( | |
| 2507 | + div() | |
| 2508 | + .absolute() | |
| 2509 | + .left(relative(left)) | |
| 2510 | + .w(relative(width)) | |
| 2511 | + .h_full() | |
| 2512 | + .rounded(px(3.)) | |
| 2513 | + .bg(rgb(ACCENT)), | |
| 2514 | + ), | |
| 2515 | + ) | |
| 2516 | + .child( | |
| 2517 | + div() | |
| 2518 | + .flex_none() | |
| 2519 | + // Fixed, so a sign or a second digit appearing does | |
| 2520 | + // not shift the bar beside it mid-drag. | |
| 2521 | + .w(px(56.)) | |
| 2522 | + .text_size(px(11.)) | |
| 2523 | + .text_color(rgb(INK_DIM)) | |
| 2524 | + .child(format!("{:+.1} dB", band.gain_db)), | |
| 2525 | + ) | |
| 2526 | + }) | |
| 2527 | + .collect(); | |
| 2528 | + Some( | |
| 2529 | + div() | |
| 2530 | + .absolute() | |
| 2531 | + .inset_0() | |
| 2532 | + .flex() | |
| 2533 | + .justify_center() | |
| 2534 | + .items_center() | |
| 2535 | + .bg(rgba(0x101010cc)) | |
| 2536 | + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { | |
| 2537 | + cx.stop_propagation() | |
| 2538 | + }) | |
| 2539 | + .child( | |
| 2540 | + div() | |
| 2541 | + .w(px(KEYS_W)) | |
| 2542 | + .flex() | |
| 2543 | + .flex_col() | |
| 2544 | + .gap(px(2.)) | |
| 2545 | + .p(px(12.)) | |
| 2546 | + .rounded(px(6.)) | |
| 2547 | + .bg(rgb(SURFACE)) | |
| 2548 | + // Which clip, because the card is modal and the lane it | |
| 2549 | + // was opened from is behind a scrim by the time it is up. | |
| 2550 | + .child(div().flex_none().px(px(6.)).child(format!( | |
| 2551 | + "Equalizer — {} clip {}", | |
| 2552 | + lane.label(), | |
| 2553 | + idx + 1 | |
| 2554 | + ))) | |
| 2555 | + .child( | |
| 2556 | + div() | |
| 2557 | + .flex_none() | |
| 2558 | + .px(px(6.)) | |
| 2559 | + .text_size(px(11.)) | |
| 2560 | + .text_color(rgb(INK_DIM)) | |
| 2561 | + .child(self.notice.clone().unwrap_or_else(|| { | |
| 2562 | + "drag a band, or 1–5 then up/down — esc closes".into() | |
| 2563 | + })), | |
| 2564 | + ) | |
| 2565 | + // Five rows fit a 360 px window, but the layout is data | |
| 2566 | + // (a file may carry any number of bands), so the list | |
| 2567 | + // scrolls like the other two cards' do. | |
| 2568 | + .child( | |
| 2569 | + div() | |
| 2570 | + .id("eq-rows") | |
| 2571 | + .flex() | |
| 2572 | + .flex_col() | |
| 2573 | + .gap(px(2.)) | |
| 2574 | + .max_h(px(EXPORT_ROWS_H)) | |
| 2575 | + .overflow_y_scroll() | |
| 2576 | + .children(rows), | |
| 2577 | + ) | |
| 2578 | + .child( | |
| 2579 | + div() | |
| 2580 | + .id("eq-reset") | |
| 2581 | + .mt(px(4.)) | |
| 2582 | + .flex() | |
| 2583 | + .h(px(CONTROL_H)) | |
| 2584 | + .items_center() | |
| 2585 | + .justify_center() | |
| 2586 | + .rounded(px(3.)) | |
| 2587 | + .bg(rgb(SELECTED)) | |
| 2588 | + .cursor_pointer() | |
| 2589 | + .hover(|s| s.bg(rgb(HOVER))) | |
| 2590 | + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { | |
| 2591 | + for band in &mut this.eq_params.bands { | |
| 2592 | + band.gain_db = 0.; | |
| 2593 | + } | |
| 2594 | + this.commit_eq(cx); | |
| 2595 | + })) | |
| 2596 | + .child("Flatten"), | |
| 2597 | + ), | |
| 2598 | + ), | |
| 2599 | + ) | |
| 2600 | + } | |
| 2601 | + | |
| 2264 | 2602 | /// The menu a right-click on a clip opens: what that clip can be given, |
| 2265 | 2603 | /// each item beside the stroke that does the very same thing, and a |
| 2266 | 2604 | /// turn-over side that says what the clip *is*. An item that would do |
| @@ -2336,7 +2674,7 @@ impl Player { | ||
| 2336 | 2674 | } |
| 2337 | 2675 | } else { |
| 2338 | 2676 | for action in MENU_ITEMS { |
| 2339 | - let enabled = applicable(&clip, action, playhead); | |
| 2677 | + let enabled = applicable(&clip, menu.lane, action, playhead); | |
| 2340 | 2678 | // The one item that is not about this clip says so, and says it |
| 2341 | 2679 | // here rather than in the registry: the stroke is global too, |
| 2342 | 2680 | // but its row in the keys menu is not sitting on a clip. |
| @@ -2856,11 +3194,44 @@ fn frame_at(secs: f64, fps: f64) -> u32 { | ||
| 2856 | 3194 | (secs * fps + 1e-6).floor().max(0.) as u32 |
| 2857 | 3195 | } |
| 2858 | 3196 | |
| 3197 | +/// A band's bar as `(left, width)` in fractions of the track: the fill grows | |
| 3198 | +/// out of the *middle*, which is flat, towards whichever end the gain went -- | |
| 3199 | +/// a bar that filled from the left would read a -12 dB cut as an empty control | |
| 3200 | +/// and 0 dB as a half-off one. The inverse of [`Player::drag_band`]'s reading | |
| 3201 | +/// of a click, and clamped like it, so a curve loaded from a file with a gain | |
| 3202 | +/// past the card's limit paints at the end of the bar rather than outside it. | |
| 3203 | +fn eq_fill(gain_db: f32) -> (f32, f32) { | |
| 3204 | + let at = (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2. + 0.5; | |
| 3205 | + match at >= 0.5 { | |
| 3206 | + true => (0.5, at - 0.5), | |
| 3207 | + false => (at, 0.5 - at), | |
| 3208 | + } | |
| 3209 | +} | |
| 3210 | + | |
| 3211 | +/// What a band row calls itself: the corner or centre frequency, and for a | |
| 3212 | +/// shelf the fact that it tilts everything past it -- which is the difference | |
| 3213 | +/// between "12 kHz" moving the last octave and moving one band inside it. | |
| 3214 | +fn band_label(band: &Band) -> String { | |
| 3215 | + let freq = match band.freq_hz >= 1000. { | |
| 3216 | + true => format!("{:.0} kHz", band.freq_hz / 1000.), | |
| 3217 | + false => format!("{:.0} Hz", band.freq_hz), | |
| 3218 | + }; | |
| 3219 | + match band.kind { | |
| 3220 | + BandKind::LowShelf => format!("{freq} low shelf"), | |
| 3221 | + BandKind::HighShelf => format!("{freq} high shelf"), | |
| 3222 | + BandKind::Peak => freq, | |
| 3223 | + } | |
| 3224 | +} | |
| 3225 | + | |
| 2859 | 3226 | /// Whether the clip menu offers `action` on the clip it was opened on. Two of |
| 2860 | 3227 | /// the items act on the *playhead* rather than on the clip, so a menu opened |
| 2861 | -/// away from it dims them instead of looking broken when they are clicked. | |
| 2862 | -fn applicable(clip: &Clip, action: ActionId, playhead: u32) -> bool { | |
| 3228 | +/// away from it dims them instead of looking broken when they are clicked, and | |
| 3229 | +/// one acts on sound, which only an audio lane's clip has. | |
| 3230 | +fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool { | |
| 2863 | 3231 | match action { |
| 3232 | + // The equalizer filters samples, and a video clip has none of its own | |
| 3233 | + // here: the sound is the audio lane's, clip for clip. | |
| 3234 | + ActionId::Equalizer => lane.kind == LaneKind::Audio, | |
| 2864 | 3235 | // Splits this clip only from inside it: at either edge there is nothing |
| 2865 | 3236 | // to split off (project.rs `splittable`). |
| 2866 | 3237 | ActionId::Cut => clip.start < playhead && playhead < clip.end(), |
| @@ -3580,15 +3951,16 @@ fn timecode(t: f64, fps: f64) -> String { | ||
| 3580 | 3951 | #[cfg(test)] |
| 3581 | 3952 | mod tests { |
| 3582 | 3953 | use super::{ |
| 3583 | - ACCENT, CONTROL_H, Clip, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, | |
| 3584 | - INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, | |
| 3585 | - LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, | |
| 3586 | - Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, | |
| 3587 | - Volume, WAVE_BPS, WAVE_COL, Wave, applicable, can_add, cancels_export, envelope, | |
| 3588 | - export_path, export_settings, format_line, frac_along, frame_at, is_bare_modifier, | |
| 3589 | - is_project, keymap, lane_clips, lanes_h, marked, menu_at, mp4_refusal, normalise, panel_h, | |
| 3590 | - project_path, push_digit, retarget, scrub_due, show_label, source_frames, source_tint, | |
| 3591 | - start_frac, timecode, unseen_paths, unseen_sources, whole_take, width_frac, window_title, | |
| 3954 | + ACCENT, CONTROL_H, Clip, EQ_BAR_H, EQ_GAIN_LIMIT, EXPORT_ROWS_H, FORMATS, Format, | |
| 3955 | + HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, | |
| 3956 | + LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, | |
| 3957 | + MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, | |
| 3958 | + SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label, | |
| 3959 | + can_add, cancels_export, envelope, eq_fill, export_path, export_settings, format_line, | |
| 3960 | + frac_along, frame_at, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked, | |
| 3961 | + menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due, | |
| 3962 | + show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, | |
| 3963 | + whole_take, width_frac, window_title, | |
| 3592 | 3964 | }; |
| 3593 | 3965 | use super::{file_name, library_rows}; |
| 3594 | 3966 | use engine::PlaybackSession; |
| @@ -3808,20 +4180,27 @@ mod tests { | ||
| 3808 | 4180 | }; |
| 3809 | 4181 | assert_eq!(clip.end(), 90); |
| 3810 | 4182 | // Cut splits from inside only: neither edge has anything to split off. |
| 3811 | - assert!(applicable(&clip, ActionId::Cut, 31)); | |
| 3812 | - assert!(applicable(&clip, ActionId::Cut, 89)); | |
| 3813 | - assert!(!applicable(&clip, ActionId::Cut, 30)); | |
| 3814 | - assert!(!applicable(&clip, ActionId::Cut, 90)); | |
| 3815 | - assert!(!applicable(&clip, ActionId::Cut, 200)); | |
| 4183 | + let a1 = Lane::A1; | |
| 4184 | + let v1 = Lane::V1; | |
| 4185 | + assert!(applicable(&clip, v1, ActionId::Cut, 31)); | |
| 4186 | + assert!(applicable(&clip, v1, ActionId::Cut, 89)); | |
| 4187 | + assert!(!applicable(&clip, v1, ActionId::Cut, 30)); | |
| 4188 | + assert!(!applicable(&clip, v1, ActionId::Cut, 90)); | |
| 4189 | + assert!(!applicable(&clip, v1, ActionId::Cut, 200)); | |
| 3816 | 4190 | // Regroup is the other way round: only where this clip meets another. |
| 3817 | - assert!(applicable(&clip, ActionId::Regroup, 30)); | |
| 3818 | - assert!(applicable(&clip, ActionId::Regroup, 90)); | |
| 3819 | - assert!(!applicable(&clip, ActionId::Regroup, 60)); | |
| 4191 | + assert!(applicable(&clip, v1, ActionId::Regroup, 30)); | |
| 4192 | + assert!(applicable(&clip, v1, ActionId::Regroup, 90)); | |
| 4193 | + assert!(!applicable(&clip, v1, ActionId::Regroup, 60)); | |
| 4194 | + // The equalizer is the one item the *lane* decides: it filters samples, | |
| 4195 | + // and a video clip has none of its own. Never the playhead's business. | |
| 4196 | + assert!(applicable(&clip, a1, ActionId::Equalizer, 0)); | |
| 4197 | + assert!(applicable(&clip, a1, ActionId::Equalizer, 60)); | |
| 4198 | + assert!(!applicable(&clip, v1, ActionId::Equalizer, 60)); | |
| 3820 | 4199 | // The rest act on the clip that was clicked, so they always mean |
| 3821 | 4200 | // something -- the engine words its own refusals. |
| 3822 | 4201 | for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { |
| 3823 | - assert!(applicable(&clip, action, 0)); | |
| 3824 | - assert!(applicable(&clip, action, 60)); | |
| 4202 | + assert!(applicable(&clip, v1, action, 0)); | |
| 4203 | + assert!(applicable(&clip, a1, action, 60)); | |
| 3825 | 4204 | } |
| 3826 | 4205 | // The playhead frame is the engine's own rule, boundary included. |
| 3827 | 4206 | assert_eq!(frame_at(1.0, 30.), 30); |
| @@ -4311,6 +4690,77 @@ mod tests { | ||
| 4311 | 4690 | assert!(KEYS_ROW_H >= HIT_MIN); |
| 4312 | 4691 | } |
| 4313 | 4692 | |
| 4693 | + /// The equalizer card: what its bars paint, and that it fits the window the | |
| 4694 | + /// other two cards are sized for. The bar is the one bit of geometry in the | |
| 4695 | + /// card, and it is signed -- a fill that grew from the left would read a cut | |
| 4696 | + /// as an empty control -- so it is checked against the reading of a click, | |
| 4697 | + /// which is the same mapping backwards ([`Player::drag_band`]). | |
| 4698 | + #[test] | |
| 4699 | + fn the_equalizer_bar_grows_out_of_flat_and_the_card_fits_the_smallest_window() { | |
| 4700 | + use engine::eq::{Band, BandKind, EqParams}; | |
| 4701 | + // Flat is the middle and paints nothing: a band nobody has touched must | |
| 4702 | + // not look like one that has been turned down. | |
| 4703 | + assert_eq!(eq_fill(0.), (0.5, 0.)); | |
| 4704 | + // Full boost fills the right half, full cut the left one. | |
| 4705 | + assert_eq!(eq_fill(EQ_GAIN_LIMIT), (0.5, 0.5)); | |
| 4706 | + assert_eq!(eq_fill(-EQ_GAIN_LIMIT), (0., 0.5)); | |
| 4707 | + assert_eq!(eq_fill(EQ_GAIN_LIMIT / 2.), (0.5, 0.25)); | |
| 4708 | + assert_eq!(eq_fill(-EQ_GAIN_LIMIT / 2.), (0.25, 0.25)); | |
| 4709 | + // A file may carry a gain past what this card offers (the format writes | |
| 4710 | + // any finite value): it paints at the end, never off the track. | |
| 4711 | + assert_eq!(eq_fill(400.), (0.5, 0.5)); | |
| 4712 | + assert_eq!(eq_fill(-400.), (0., 0.5)); | |
| 4713 | + | |
| 4714 | + // A click reads back as the gain that paints where it landed, which is | |
| 4715 | + // what makes a drag land where the pointer is. | |
| 4716 | + for gain in [-12., -6., 0., 6., 12.] { | |
| 4717 | + let (left, width) = eq_fill(gain); | |
| 4718 | + let at = if gain >= 0. { left + width } else { left }; | |
| 4719 | + let read = (at * 2. - 1.) * EQ_GAIN_LIMIT; | |
| 4720 | + assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}"); | |
| 4721 | + } | |
| 4722 | + | |
| 4723 | + // Every default band says what it is, and a shelf says so: "12 kHz" | |
| 4724 | + // alone would not tell anyone it tilts the whole top octave. | |
| 4725 | + let labels: Vec<String> = EqParams::default_layout() | |
| 4726 | + .bands | |
| 4727 | + .iter() | |
| 4728 | + .map(band_label) | |
| 4729 | + .collect(); | |
| 4730 | + assert_eq!( | |
| 4731 | + labels, | |
| 4732 | + [ | |
| 4733 | + "80 Hz low shelf", | |
| 4734 | + "250 Hz", | |
| 4735 | + "1 kHz", | |
| 4736 | + "4 kHz", | |
| 4737 | + "12 kHz high shelf" | |
| 4738 | + ] | |
| 4739 | + ); | |
| 4740 | + assert_eq!( | |
| 4741 | + band_label(&Band { | |
| 4742 | + freq_hz: 2600., | |
| 4743 | + gain_db: 0., | |
| 4744 | + q: 1., | |
| 4745 | + kind: BandKind::Peak | |
| 4746 | + }), | |
| 4747 | + "3 kHz", | |
| 4748 | + "rounded, because a band label is not a measurement" | |
| 4749 | + ); | |
| 4750 | + | |
| 4751 | + // The same shape as the other two cards, so it fits where they do. | |
| 4752 | + let (title, status, gaps, padding) = (17., 28., 3. * 2., 24.); | |
| 4753 | + assert!( | |
| 4754 | + title + status + EXPORT_ROWS_H + gaps + padding + CONTROL_H <= 360., | |
| 4755 | + "card too tall" | |
| 4756 | + ); | |
| 4757 | + assert!(KEYS_W <= 640., "card too wide"); | |
| 4758 | + // The rows are dragged, so WCAG 2.5.8 binds them like every other | |
| 4759 | + // target in this window -- the 6 px bar is inside a full-height row. | |
| 4760 | + assert!(KEYS_ROW_H >= HIT_MIN); | |
| 4761 | + assert!(EQ_BAR_H < KEYS_ROW_H); | |
| 4762 | + } | |
| 4763 | + | |
| 4314 | 4764 | /// Mute and level are one control with two states, and the whole point is |
| 4315 | 4765 | /// that mute keeps the level: the user gets back what they had, not 100%. |
| 4316 | 4766 | #[test] |
| @@ -4834,6 +5284,13 @@ fn main() { | ||
| 4834 | 5284 | keymap: keymap.clone(), |
| 4835 | 5285 | keys_open: false, |
| 4836 | 5286 | export_open: false, |
| 5287 | + eq_open: None, | |
| 5288 | + // Replaced by the clip's own curve the moment the card | |
| 5289 | + // opens; nothing reads it before that. | |
| 5290 | + eq_params: EqParams::default(), | |
| 5291 | + eq_band: 0, | |
| 5292 | + eq_dragging: false, | |
| 5293 | + eq_bar: Rc::default(), | |
| 4837 | 5294 | // What an export is until someone says otherwise: the |
| 4838 | 5295 | // bitrate the picture asks for. |
| 4839 | 5296 | quality: Quality::Auto, |
crates/engine/src/audio.rsmodified+98 -6
| @@ -43,6 +43,8 @@ use symphonia_core::packet::Packet; | ||
| 43 | 43 | use symphonia_core::units; |
| 44 | 44 | use symphonia_core::units::{Time, TimeBase}; |
| 45 | 45 | |
| 46 | +use crate::eq::{EqParams, EqState}; | |
| 47 | + | |
| 46 | 48 | /// ffmpeg's AAC-LC encoder delay, used when the file carries no edit list. |
| 47 | 49 | /// (HE-AAC/iTunes files use 2112, but those are rejected as unsupported here.) |
| 48 | 50 | const DEFAULT_PRIMING: u64 = 1024; |
| @@ -211,6 +213,26 @@ impl AudioSession { | ||
| 211 | 213 | pub fn open_multi_streams( |
| 212 | 214 | sources: &[(PathBuf, usize)], |
| 213 | 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 | 236 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 215 | 237 | let Some((path, stream)) = sources.first() else { |
| 216 | 238 | return Ok(None); |
| @@ -282,6 +304,20 @@ impl AudioSession { | ||
| 282 | 304 | // One AAC packet decodes to 1024 frames; at stereo f32 that is 8 KB, so |
| 283 | 305 | // this bound is ~0.75 s of lookahead — enough to ride out decode jitter |
| 284 | 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 | 321 | let (tx, rx) = sync_channel(32); |
| 286 | 322 | thread::Builder::new() |
| 287 | 323 | .name("audio-decode".into()) |
| @@ -290,6 +326,7 @@ impl AudioSession { | ||
| 290 | 326 | tracks, |
| 291 | 327 | channels: meta.channels as usize, |
| 292 | 328 | segments, |
| 329 | + eqs, | |
| 293 | 330 | timeline, |
| 294 | 331 | tx, |
| 295 | 332 | }) |
| @@ -317,19 +354,41 @@ impl AudioSession { | ||
| 317 | 354 | pub fn open_mixed_streams( |
| 318 | 355 | sources: &[(PathBuf, usize)], |
| 319 | 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 | 375 | ) -> crate::Result<Option<(AudioMeta, Receiver<AudioChunk>)>> { |
| 321 | 376 | let [first, rest @ ..] = lanes else { |
| 322 | 377 | return Ok(None); |
| 323 | 378 | }; |
| 324 | 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 | 383 | let mut meta = None; |
| 328 | 384 | let mut rxs = Vec::with_capacity(lanes.len()); |
| 329 | - for segs in lanes { | |
| 385 | + for (i, segs) in lanes.iter().enumerate() { | |
| 330 | 386 | // Every lane probes the same source 0, so the metas agree by |
| 331 | 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 | 392 | return Ok(None); |
| 334 | 393 | }; |
| 335 | 394 | meta = Some(lane_meta); |
| @@ -1240,6 +1299,11 @@ struct Worker { | ||
| 1240 | 1299 | tracks: Vec<Option<Track>>, |
| 1241 | 1300 | channels: usize, |
| 1242 | 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 | 1307 | /// `start_sample` of the first chunk. |
| 1244 | 1308 | timeline: u64, |
| 1245 | 1309 | tx: SyncSender<AudioChunk>, |
| @@ -1317,8 +1381,12 @@ fn run(mut w: Worker) { | ||
| 1317 | 1381 | // Chunk numbering is continuous across every join, source ones included. |
| 1318 | 1382 | let mut timeline = w.timeline; |
| 1319 | 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 | 1390 | let Some(source) = seg.source else { |
| 1323 | 1391 | // A gap: hand the device real silence rather than nothing at all, |
| 1324 | 1392 | // in the same packet-sized chunks decoding produces, so `fed` and |
| @@ -1343,7 +1411,7 @@ fn run(mut w: Worker) { | ||
| 1343 | 1411 | }; |
| 1344 | 1412 | let track = match track { |
| 1345 | 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 | 1415 | return; // consumer went away |
| 1348 | 1416 | } |
| 1349 | 1417 | continue; |
| @@ -1391,6 +1459,7 @@ fn run(mut w: Worker) { | ||
| 1391 | 1459 | &mut interleaved, |
| 1392 | 1460 | channels, |
| 1393 | 1461 | seg, |
| 1462 | + eq.as_mut(), | |
| 1394 | 1463 | pos, |
| 1395 | 1464 | next, |
| 1396 | 1465 | &mut timeline, |
| @@ -1412,10 +1481,18 @@ fn run(mut w: Worker) { | ||
| 1412 | 1481 | /// audio the caller asked for: it is dropped, splitting the buffer that |
| 1413 | 1482 | /// straddles the target. The tail past the segment end goes too — on a short |
| 1414 | 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 | 1491 | fn emit( |
| 1416 | 1492 | interleaved: &mut Vec<f32>, |
| 1417 | 1493 | channels: usize, |
| 1418 | 1494 | seg: &Segment, |
| 1495 | + eq: Option<&mut EqState>, | |
| 1419 | 1496 | pos: u64, |
| 1420 | 1497 | next: u64, |
| 1421 | 1498 | timeline: &mut u64, |
| @@ -1435,6 +1512,9 @@ fn emit( | ||
| 1435 | 1512 | if interleaved.is_empty() { |
| 1436 | 1513 | 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 | 1518 | let chunk = AudioChunk { |
| 1439 | 1519 | start_sample: *timeline, |
| 1440 | 1520 | samples: std::mem::take(interleaved), |
| @@ -1455,6 +1535,7 @@ fn emit( | ||
| 1455 | 1535 | fn run_sym( |
| 1456 | 1536 | track: &mut SymTrack, |
| 1457 | 1537 | seg: &Segment, |
| 1538 | + mut eq: Option<&mut EqState>, | |
| 1458 | 1539 | channels: usize, |
| 1459 | 1540 | timeline: &mut u64, |
| 1460 | 1541 | tx: &SyncSender<AudioChunk>, |
| @@ -1505,7 +1586,18 @@ fn run_sym( | ||
| 1505 | 1586 | }; |
| 1506 | 1587 | buf.copy_to_vec_interleaved::<f32>(&mut interleaved); |
| 1507 | 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 | 1601 | return false; |
| 1510 | 1602 | } |
| 1511 | 1603 | } |
crates/engine/src/export.rsmodified+43 -5
| @@ -235,6 +235,28 @@ fn run( | ||
| 235 | 235 | ) |
| 236 | 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 | 260 | let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?; |
| 239 | 261 | let audio_params = audio.as_ref().map(|(track, _)| AudioParams { |
| 240 | 262 | freq_index: track.freq_index, |
| @@ -303,6 +325,18 @@ fn run( | ||
| 303 | 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 | 340 | /// The audio lanes alone, summed, as a WAV or a FLAC. |
| 307 | 341 | /// |
| 308 | 342 | /// Nothing here re-derives the edit: the play lists are |
| @@ -326,7 +360,13 @@ fn run_audio( | ||
| 326 | 360 | ) -> crate::Result<()> { |
| 327 | 361 | let sources = project.audio_sources(); |
| 328 | 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 | 370 | return Err("this timeline has no audio to export".into()); |
| 331 | 371 | }; |
| 332 | 372 | let channels = usize::from(audio.channels); |
| @@ -341,10 +381,8 @@ fn run_audio( | ||
| 341 | 381 | let mut samples: Vec<i32> = Vec::with_capacity(total); |
| 342 | 382 | for chunk in chunks { |
| 343 | 383 | cancelled(shared)?; |
| 344 | - // ponytail: the per-segment EQ goes here -- `EqState::process` on this | |
| 345 | - // same interleaved f32 buffer, before the quantisation below, which is | |
| 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. | |
| 384 | + // Already equalized: the chunks come out of the per-lane workers, which | |
| 385 | + // filter each segment before the mix (`open_mixed_streams_eq` above). | |
| 348 | 386 | samples.extend( |
| 349 | 387 | chunk |
| 350 | 388 | .samples |
crates/engine/src/playback.rsmodified+30 -1
| @@ -23,6 +23,7 @@ use crate::audio::{AudioChunk, AudioSession}; | ||
| 23 | 23 | use crate::clock::{ClockSource, PlaybackClock}; |
| 24 | 24 | use crate::decode::{DecodeSession, Frame, Worker}; |
| 25 | 25 | use crate::demux::{Demuxer, VideoMeta}; |
| 26 | +use crate::eq::EqParams; | |
| 26 | 27 | use crate::project::{Clip, Lane, LaneKind, Project, Source, Span}; |
| 27 | 28 | |
| 28 | 29 | /// How long the feeder waits out a full ring. The ring holds a second, so this |
| @@ -485,6 +486,27 @@ impl PlaybackSession { | ||
| 485 | 486 | .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate)) |
| 486 | 487 | } |
| 487 | 488 | |
| 489 | + /// What the clip at `idx` of `lane` is equalized with, or `None` for one | |
| 490 | + /// that plays flat -- what a card shows before it lets anyone drag a band. | |
| 491 | + pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> { | |
| 492 | + self.project.eq_of(lane, idx) | |
| 493 | + } | |
| 494 | + | |
| 495 | + /// Gives that clip an equalizer, or takes it off with `None`. One undo step, | |
| 496 | + /// like every other edit -- and, like every other edit, it *reseeks*: the | |
| 497 | + /// audio workers are rebuilt from the new curves right where the playhead | |
| 498 | + /// is, so a band changed during playback is heard from the next chunk on | |
| 499 | + /// rather than at the next play. `false` for a bad index or a non-finite | |
| 500 | + /// band, and nothing changes. | |
| 501 | + /// | |
| 502 | + /// ponytail: the reseek is what makes it live, so the cost of a change is a | |
| 503 | + /// decoder restart -- inaudible at a drag's end, but too much to call once | |
| 504 | + /// per pointer sample (a caller commits one change per gesture). Upgrade | |
| 505 | + /// path is an `Arc` swap the running worker polls per chunk. | |
| 506 | + pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool { | |
| 507 | + self.edit(|p| p.set_eq(lane, idx, params)) | |
| 508 | + } | |
| 509 | + | |
| 488 | 510 | /// Lifts one lane's clip out, leaving a gap: black frames on the video lane, |
| 489 | 511 | /// silence on the audio one, and nothing else moves. Reseeks, because what |
| 490 | 512 | /// the playhead sits on has changed. `false` for a bad index and for the |
| @@ -819,10 +841,17 @@ impl PlaybackSession { | ||
| 819 | 841 | // hears is every lane at once, and a lane's own gaps are silence in |
| 820 | 842 | // it rather than a hole in the count the master clock keeps. |
| 821 | 843 | let segs = self.project.audio_segments_from(target, fps); |
| 844 | + // The equalizers beside them, one per segment: the worker filters a | |
| 845 | + // segment's own samples before the mix, so a clip's curve reaches | |
| 846 | + // that clip and stops. Rebuilt on every seek, which is what makes an | |
| 847 | + // EQ edit audible at once -- `edit` reseeks, so the drag that | |
| 848 | + // changed a band restarts the workers with the new curve already in | |
| 849 | + // them, and no live channel has to reach into a running one. | |
| 850 | + let eqs = self.project.audio_eqs_from(target, fps); | |
| 822 | 851 | // Each source on the stream it was placed with: what plays is what |
| 823 | 852 | // the library row said, and what an export copies (`export::run`). |
| 824 | 853 | let sources = self.project.audio_sources(); |
| 825 | - audio_running = match AudioSession::open_mixed_streams(&sources, &segs) { | |
| 854 | + audio_running = match AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs) { | |
| 826 | 855 | Ok(Some((_, rx))) => audio.spawn_feeder(rx), |
| 827 | 856 | _ => false, |
| 828 | 857 | }; |
crates/engine/src/project.rsmodified+59 -5
| @@ -1091,16 +1091,70 @@ impl Project { | ||
| 1091 | 1091 | timeline_frame: u32, |
| 1092 | 1092 | fps: f64, |
| 1093 | 1093 | ) -> Vec<Vec<(Option<usize>, f64, f64)>> { |
| 1094 | - let lists: Vec<_> = self | |
| 1094 | + self.audio_lanes() | |
| 1095 | + .into_iter() | |
| 1096 | + .map(|lane| self.lane_segments_from(lane, timeline_frame, fps)) | |
| 1097 | + .collect() | |
| 1098 | + } | |
| 1099 | + | |
| 1100 | + /// *Which* lanes [`audio_segments_from`](Project::audio_segments_from) | |
| 1101 | + /// builds a play list for, in the same order. Public because everything | |
| 1102 | + /// asked per audio lane -- which clip a segment's equalizer belongs to, | |
| 1103 | + /// which lane an mp4 export would copy -- has to read the very list the | |
| 1104 | + /// sound comes off, or the two answers drift apart (which is exactly how an | |
| 1105 | + /// `A2`-only project once exported silently, ledger). | |
| 1106 | + pub fn audio_lanes(&self) -> Vec<Lane> { | |
| 1107 | + let lanes: Vec<Lane> = self | |
| 1095 | 1108 | .lanes() |
| 1096 | 1109 | .into_iter() |
| 1097 | 1110 | .filter(|l| l.kind == LaneKind::Audio && !self.lane(*l).is_empty()) |
| 1098 | - .map(|lane| self.lane_segments_from(lane, timeline_frame, fps)) | |
| 1099 | 1111 | .collect(); |
| 1100 | - match lists.is_empty() { | |
| 1101 | - true => vec![self.lane_segments_from(Lane::A1, timeline_frame, fps)], | |
| 1102 | - false => lists, | |
| 1112 | + match lanes.is_empty() { | |
| 1113 | + // The all-gap fallback: `A1`'s own (empty) list, so a timeline with | |
| 1114 | + // no sound still plays silence against the master clock. | |
| 1115 | + true => vec![Lane::A1], | |
| 1116 | + false => lanes, | |
| 1117 | + } | |
| 1118 | + } | |
| 1119 | + | |
| 1120 | + /// The equalizer each of [`audio_segments_from`](Project::audio_segments_from)'s | |
| 1121 | + /// segments plays through: the same lanes in the same order, one entry per | |
| 1122 | + /// segment, `None` where the segment is a gap or its clip plays flat. | |
| 1123 | + /// | |
| 1124 | + /// A parallel list rather than a fourth element of the segment tuple: that | |
| 1125 | + /// tuple is what every opener, the packet-copy path and a dozen tests speak, | |
| 1126 | + /// and an effect is not part of *which samples* a segment names. A short | |
| 1127 | + /// list therefore means "flat from here on" rather than a length mismatch -- | |
| 1128 | + /// see [`crate::AudioSession::open_mixed_streams_eq`]. | |
| 1129 | + pub fn audio_eqs_from(&self, timeline_frame: u32, fps: f64) -> Vec<Vec<Option<EqParams>>> { | |
| 1130 | + self.audio_lanes() | |
| 1131 | + .into_iter() | |
| 1132 | + .map(|lane| self.lane_eqs_from(lane, timeline_frame, fps)) | |
| 1133 | + .collect() | |
| 1134 | + } | |
| 1135 | + | |
| 1136 | + /// [`audio_eqs_from`](Project::audio_eqs_from) for one lane, matching | |
| 1137 | + /// [`lane_segments_from`](Project::lane_segments_from) entry for entry -- | |
| 1138 | + /// same walk, same `fps` refusal, so the two lists cannot come out different | |
| 1139 | + /// lengths. | |
| 1140 | + pub fn lane_eqs_from( | |
| 1141 | + &self, | |
| 1142 | + lane: Lane, | |
| 1143 | + timeline_frame: u32, | |
| 1144 | + fps: f64, | |
| 1145 | + ) -> Vec<Option<EqParams>> { | |
| 1146 | + if !(fps.is_finite() && fps > 0.0) { | |
| 1147 | + return Vec::new(); | |
| 1103 | 1148 | } |
| 1149 | + self.spans_from(lane, timeline_frame) | |
| 1150 | + .iter() | |
| 1151 | + // A span off a clip covers that clip's frames and no others, so its | |
| 1152 | + // own start names the clip -- the index a [`Span`] does not carry. | |
| 1153 | + .map(|span| { | |
| 1154 | + self.map(lane, span.start) | |
| 1155 | + .and_then(|(idx, _)| self.eq_of(lane, idx).cloned()) | |
| 1156 | + }) | |
| 1157 | + .collect() | |
| 1104 | 1158 | } |
| 1105 | 1159 | |
| 1106 | 1160 | /// 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 | +} |