Volume and mute for the monitoring output
Browse files at this commitbb07bdc3c81dc187fc00f0fb339ecc54313386a4Parent: 935d5f0- feat
- volume and mute for the monitoring output
6 changed files +403 -19
- crates/app/src/keymap.rs +27 -3
- crates/app/src/main.rs +210 -14
- crates/engine-audio/src/lib.rs +87 -1
- crates/engine/src/ao.rs +15 -1
- crates/engine/src/playback.rs +19 -0
- crates/engine/tests/ao_output.rs +45 -0
crates/app/src/keymap.rsmodified+27 -3
| @@ -46,13 +46,16 @@ pub enum ActionId { | ||
| 46 | 46 | Cut, |
| 47 | 47 | Delete, |
| 48 | 48 | Undo, |
| 49 | + ToggleMute, | |
| 50 | + VolumeUp, | |
| 51 | + VolumeDown, | |
| 49 | 52 | CancelExport, |
| 50 | 53 | } |
| 51 | 54 | |
| 52 | 55 | impl ActionId { |
| 53 | 56 | /// Display order everywhere -- the editor lists them in it and |
| 54 | 57 | /// [`Keymap::defaults`] binds them in it. |
| 55 | - pub const ALL: [ActionId; 9] = [ | |
| 58 | + pub const ALL: [ActionId; 12] = [ | |
| 56 | 59 | ActionId::Play, |
| 57 | 60 | ActionId::Export, |
| 58 | 61 | ActionId::Save, |
| @@ -61,6 +64,9 @@ impl ActionId { | ||
| 61 | 64 | ActionId::Cut, |
| 62 | 65 | ActionId::Delete, |
| 63 | 66 | ActionId::Undo, |
| 67 | + ActionId::ToggleMute, | |
| 68 | + ActionId::VolumeUp, | |
| 69 | + ActionId::VolumeDown, | |
| 64 | 70 | ActionId::CancelExport, |
| 65 | 71 | ]; |
| 66 | 72 | |
| @@ -75,6 +81,9 @@ impl ActionId { | ||
| 75 | 81 | ActionId::Cut => "Cut", |
| 76 | 82 | ActionId::Delete => "Delete", |
| 77 | 83 | ActionId::Undo => "Undo", |
| 84 | + ActionId::ToggleMute => "Mute / Unmute", | |
| 85 | + ActionId::VolumeUp => "Volume up", | |
| 86 | + ActionId::VolumeDown => "Volume down", | |
| 78 | 87 | ActionId::CancelExport => "Cancel export", |
| 79 | 88 | } |
| 80 | 89 | } |
| @@ -91,6 +100,9 @@ impl ActionId { | ||
| 91 | 100 | ActionId::Cut => "cut", |
| 92 | 101 | ActionId::Delete => "delete", |
| 93 | 102 | ActionId::Undo => "undo", |
| 103 | + ActionId::ToggleMute => "toggle-mute", | |
| 104 | + ActionId::VolumeUp => "volume-up", | |
| 105 | + ActionId::VolumeDown => "volume-down", | |
| 94 | 106 | ActionId::CancelExport => "cancel-export", |
| 95 | 107 | } |
| 96 | 108 | } |
| @@ -199,6 +211,12 @@ impl Keymap { | ||
| 199 | 211 | b(ActionId::Delete, "delete", false), |
| 200 | 212 | b(ActionId::Undo, "z", false), |
| 201 | 213 | b(ActionId::Undo, "z", true), |
| 214 | + b(ActionId::ToggleMute, "m", false), | |
| 215 | + // The unshifted pair, which is what gpui reports for those two | |
| 216 | + // keys ("=" and "-", platform.rs:862): the volume keys every | |
| 217 | + // player has, without asking for shift to make the "+". | |
| 218 | + b(ActionId::VolumeUp, "=", false), | |
| 219 | + b(ActionId::VolumeDown, "-", false), | |
| 202 | 220 | b(ActionId::CancelExport, "escape", false), |
| 203 | 221 | ], |
| 204 | 222 | } |
| @@ -425,7 +443,7 @@ mod tests { | ||
| 425 | 443 | #[test] |
| 426 | 444 | fn every_default_stroke_reaches_its_action() { |
| 427 | 445 | let k = Keymap::defaults(); |
| 428 | - assert_eq!(k.entries().len(), 11); | |
| 446 | + assert_eq!(k.entries().len(), 14); | |
| 429 | 447 | assert_eq!(k.lookup("space", false), Some(ActionId::Play)); |
| 430 | 448 | assert_eq!(k.lookup("e", false), Some(ActionId::Export)); |
| 431 | 449 | assert_eq!(k.lookup("s", true), Some(ActionId::Save)); |
| @@ -436,6 +454,12 @@ mod tests { | ||
| 436 | 454 | assert_eq!(k.lookup("delete", false), Some(ActionId::Delete)); |
| 437 | 455 | assert_eq!(k.lookup("z", false), Some(ActionId::Undo)); |
| 438 | 456 | assert_eq!(k.lookup("z", true), Some(ActionId::Undo)); |
| 457 | + assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); | |
| 458 | + // The volume pair is the unshifted one, so neither needs a modifier | |
| 459 | + // and neither is the "+" gpui reports for shift+=. | |
| 460 | + assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp)); | |
| 461 | + assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown)); | |
| 462 | + assert_eq!(k.lookup("+", false), None); | |
| 439 | 463 | assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport)); |
| 440 | 464 | // The modifier is half the chord: ctrl+e is not e. |
| 441 | 465 | assert_eq!(k.lookup("e", true), None); |
| @@ -564,7 +588,7 @@ mod tests { | ||
| 564 | 588 | ); |
| 565 | 589 | // The label is the editor's column, and never the file's word for it. |
| 566 | 590 | assert_eq!(ActionId::CancelExport.label(), "Cancel export"); |
| 567 | - assert_eq!(ActionId::ALL.len(), 9); | |
| 591 | + assert_eq!(ActionId::ALL.len(), 12); | |
| 568 | 592 | } |
| 569 | 593 | |
| 570 | 594 | #[test] |
crates/app/src/main.rsmodified+210 -14
| @@ -60,6 +60,10 @@ const TIME_W: f32 = 200.; | ||
| 60 | 60 | /// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too. |
| 61 | 61 | const KEYS_W: f32 = 320.; |
| 62 | 62 | const KEYS_ROW_H: f32 = HIT_MIN; |
| 63 | +/// How much of the row list is on screen at once; past this it scrolls. What | |
| 64 | +/// keeps the card inside the smallest window no matter how many actions the | |
| 65 | +/// editor grows -- ten rows fit here, and the eleventh is a scroll away. | |
| 66 | +const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; | |
| 63 | 67 | |
| 64 | 68 | /// The one key name this file still spells out, and gpui's spelling of it: it |
| 65 | 69 | /// is the way out of a capture and out of the overlay, and both have to work |
| @@ -67,6 +71,68 @@ const KEYS_ROW_H: f32 = HIT_MIN; | ||
| 67 | 71 | /// through the keymap to find it. |
| 68 | 72 | const ESCAPE: &str = "escape"; |
| 69 | 73 | |
| 74 | +/// What the monitoring output is set to. Two things, not one: the level the | |
| 75 | +/// user picked, and whether it is being held silent -- so unmuting comes back | |
| 76 | +/// to the level rather than to a guess. | |
| 77 | +/// | |
| 78 | +/// The level counts steps rather than carrying an `f32`, because 5% at a time | |
| 79 | +/// down and back up again through a float would not land on the number it | |
| 80 | +/// started from, and the label would eventually read `79%`. | |
| 81 | +/// | |
| 82 | +/// Volume and mute stay independent on purpose: turning the level down while | |
| 83 | +/// muted must not be what makes sound come out. Only the mute key unmutes, and | |
| 84 | +/// the button says both things at once ("Muted 80%") so neither is a surprise. | |
| 85 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | |
| 86 | +struct Volume { | |
| 87 | + steps: u8, | |
| 88 | + muted: bool, | |
| 89 | +} | |
| 90 | + | |
| 91 | +impl Volume { | |
| 92 | + /// 5% a press: twenty of them across the range. | |
| 93 | + const MAX_STEPS: u8 = 20; | |
| 94 | + | |
| 95 | + /// What the device is set to: mute wins, and the level is what it returns | |
| 96 | + /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts. | |
| 97 | + fn gain(self) -> f32 { | |
| 98 | + if self.muted { | |
| 99 | + 0. | |
| 100 | + } else { | |
| 101 | + f32::from(self.steps) / f32::from(Self::MAX_STEPS) | |
| 102 | + } | |
| 103 | + } | |
| 104 | + | |
| 105 | + /// One press up or down, clamped at both ends -- saturating, so the count | |
| 106 | + /// cannot wrap past silence into full volume. | |
| 107 | + fn step(&mut self, up: bool) { | |
| 108 | + self.steps = if up { | |
| 109 | + self.steps.saturating_add(1).min(Self::MAX_STEPS) | |
| 110 | + } else { | |
| 111 | + self.steps.saturating_sub(1) | |
| 112 | + }; | |
| 113 | + } | |
| 114 | + | |
| 115 | + /// What the button reads. The level shows while muted too: it is what the | |
| 116 | + /// next press of the mute key brings back. | |
| 117 | + fn label(self) -> String { | |
| 118 | + let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS); | |
| 119 | + if self.muted { | |
| 120 | + format!("Muted {percent}%") | |
| 121 | + } else { | |
| 122 | + format!("Vol {percent}%") | |
| 123 | + } | |
| 124 | + } | |
| 125 | +} | |
| 126 | + | |
| 127 | +impl Default for Volume { | |
| 128 | + fn default() -> Self { | |
| 129 | + Self { | |
| 130 | + steps: Self::MAX_STEPS, | |
| 131 | + muted: false, | |
| 132 | + } | |
| 133 | + } | |
| 134 | +} | |
| 135 | + | |
| 70 | 136 | struct Player { |
| 71 | 137 | /// The timeline, once there is one. A run with no file opens without it and |
| 72 | 138 | /// waits: the first media import or project load is what fills it, and |
| @@ -117,6 +183,12 @@ struct Player { | ||
| 117 | 183 | /// Which stroke means what, and what every shortcut on screen is called. |
| 118 | 184 | /// The one place either question is answered. |
| 119 | 185 | keymap: Keymap, |
| 186 | + /// How loud the monitoring is, and whether it is muted. Lives here rather | |
| 187 | + /// than in the session so it survives closing one file and opening the | |
| 188 | + /// next -- it is a setting of the player, not of the timeline, which is | |
| 189 | + /// also why it is not written to the project file and cannot reach an | |
| 190 | + /// export. [`Player::apply_volume`] is what pushes it at a session. | |
| 191 | + volume: Volume, | |
| 120 | 192 | /// The keybindings overlay is up. While it is, it owns the keyboard and the |
| 121 | 193 | /// pointer: a stroke or a click meant for a row must not also cut the |
| 122 | 194 | /// timeline. |
| @@ -322,6 +394,9 @@ impl Player { | ||
| 322 | 394 | Ok(session) => { |
| 323 | 395 | self.fps = session.meta().frame_rate; |
| 324 | 396 | self.session = Some(session); |
| 397 | + // A fresh session comes up at full volume; the player's own | |
| 398 | + // setting outlives the file, so it is pushed at every new one. | |
| 399 | + self.apply_volume(); | |
| 325 | 400 | self.export_path = export_path(path); |
| 326 | 401 | self.project_path = project_path(path); |
| 327 | 402 | self.name = file_name(path).into(); |
| @@ -376,6 +451,7 @@ impl Player { | ||
| 376 | 451 | // media: that is the only place an export has ever landed. |
| 377 | 452 | self.export_path = export_path(&session.sources()[0]); |
| 378 | 453 | self.session = Some(session); |
| 454 | + self.apply_volume(); | |
| 379 | 455 | self.project_path = path.to_path_buf(); |
| 380 | 456 | self.name = file_name(path).into(); |
| 381 | 457 | // A copied clip names its source by index, which means a |
| @@ -472,6 +548,26 @@ impl Player { | ||
| 472 | 548 | |
| 473 | 549 | /// The play binding and the transport button share it: once the timeline is finished |
| 474 | 550 | /// the only sensible "play" is from the top. |
| 551 | + /// Pushes the current volume at the session, which is the only place it is | |
| 552 | + /// ever pushed: after a change here, and after a session arrives. A session | |
| 553 | + /// starts at full volume, so a file opened while muted has to be told -- | |
| 554 | + /// that is the whole reason this is not just called from the key handler. | |
| 555 | + /// Silent no-op with no timeline, or with a run that has no audio device. | |
| 556 | + fn apply_volume(&self) { | |
| 557 | + if let Some(session) = &self.session { | |
| 558 | + session.set_gain(self.volume.gain()); | |
| 559 | + } | |
| 560 | + } | |
| 561 | + | |
| 562 | + /// The mute key and the two volume keys, and the click on the button. The | |
| 563 | + /// picture is not touched: silencing the output is not pausing it, so the | |
| 564 | + /// clock -- which the device still drives -- runs straight through. | |
| 565 | + fn set_volume(&mut self, change: impl FnOnce(&mut Volume), cx: &mut Context<Self>) { | |
| 566 | + change(&mut self.volume); | |
| 567 | + self.apply_volume(); | |
| 568 | + cx.notify(); | |
| 569 | + } | |
| 570 | + | |
| 475 | 571 | fn toggle_or_restart(&mut self, cx: &mut Context<Self>) { |
| 476 | 572 | if self.exporting().is_some() { |
| 477 | 573 | return; |
| @@ -729,6 +825,11 @@ impl Render for Player { | ||
| 729 | 825 | Some(ActionId::Cut) => this.cut(cx), |
| 730 | 826 | Some(ActionId::Delete) => this.delete_selected(cx), |
| 731 | 827 | Some(ActionId::Undo) => this.undo(cx), |
| 828 | + Some(ActionId::ToggleMute) => { | |
| 829 | + this.set_volume(|volume| volume.muted = !volume.muted, cx) | |
| 830 | + } | |
| 831 | + Some(ActionId::VolumeUp) => this.set_volume(|volume| volume.step(true), cx), | |
| 832 | + Some(ActionId::VolumeDown) => this.set_volume(|volume| volume.step(false), cx), | |
| 732 | 833 | // Nothing to cancel while nothing is exporting. |
| 733 | 834 | Some(ActionId::CancelExport) | None => {} |
| 734 | 835 | } |
| @@ -931,6 +1032,24 @@ impl Player { | ||
| 931 | 1032 | live && self.selected.is_some(), |
| 932 | 1033 | cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)), |
| 933 | 1034 | )) |
| 1035 | + // With the transport, not the edit group: it changes what | |
| 1036 | + // the file sounds like, never what it is. Reads as its own | |
| 1037 | + // state, so muted is legible without a tooltip. | |
| 1038 | + .child(control( | |
| 1039 | + "volume", | |
| 1040 | + None, | |
| 1041 | + self.volume.label(), | |
| 1042 | + format!( | |
| 1043 | + "{} mutes · {} louder · {} quieter", | |
| 1044 | + key(ActionId::ToggleMute), | |
| 1045 | + key(ActionId::VolumeUp), | |
| 1046 | + key(ActionId::VolumeDown) | |
| 1047 | + ), | |
| 1048 | + live, | |
| 1049 | + cx.listener(|this, _: &ClickEvent, _, cx| { | |
| 1050 | + this.set_volume(|volume| volume.muted = !volume.muted, cx) | |
| 1051 | + }), | |
| 1052 | + )) | |
| 934 | 1053 | .child(separator()) |
| 935 | 1054 | .child(control( |
| 936 | 1055 | "import", |
| @@ -1164,9 +1283,9 @@ impl Player { | ||
| 1164 | 1283 | // two, and the notice bar it would otherwise appear in is |
| 1165 | 1284 | // under the scrim. |
| 1166 | 1285 | // |
| 1167 | - // ponytail: a refusal long enough to wrap to three lines | |
| 1168 | - // pushes the card past a 360 px tall window. The upgrade | |
| 1169 | - // path is a scrolling row list, not a shorter message. | |
| 1286 | + // The row list below is capped and scrolls, so neither a | |
| 1287 | + // wrapped refusal here nor another action added to `ALL` | |
| 1288 | + // can push the card past a 360 px window any more. | |
| 1170 | 1289 | .child( |
| 1171 | 1290 | div() |
| 1172 | 1291 | .flex_none() |
| @@ -1179,7 +1298,19 @@ impl Player { | ||
| 1179 | 1298 | .unwrap_or_else(|| "click a row, then press a key".into()), |
| 1180 | 1299 | ), |
| 1181 | 1300 | ) |
| 1182 | - .children(rows), | |
| 1301 | + // Capped and scrolling rather than as tall as the action | |
| 1302 | + // list happens to be: the list grows with the editor, | |
| 1303 | + // the smallest window does not. | |
| 1304 | + .child( | |
| 1305 | + div() | |
| 1306 | + .id("keys-rows") | |
| 1307 | + .flex() | |
| 1308 | + .flex_col() | |
| 1309 | + .gap(px(2.)) | |
| 1310 | + .max_h(px(KEYS_ROWS_H)) | |
| 1311 | + .overflow_y_scroll() | |
| 1312 | + .children(rows), | |
| 1313 | + ), | |
| 1183 | 1314 | ), |
| 1184 | 1315 | ) |
| 1185 | 1316 | } |
| @@ -1576,11 +1707,13 @@ fn width_frac(len: f64, total: f64) -> f32 { | ||
| 1576 | 1707 | fn control( |
| 1577 | 1708 | id: &'static str, |
| 1578 | 1709 | glyph: Option<AnyElement>, |
| 1579 | - label: &'static str, | |
| 1710 | + // Not `&'static str`: the volume button's label is its state. | |
| 1711 | + label: impl Into<SharedString>, | |
| 1580 | 1712 | shortcut: String, |
| 1581 | 1713 | enabled: bool, |
| 1582 | 1714 | on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, |
| 1583 | 1715 | ) -> impl IntoElement { |
| 1716 | + let label = label.into(); | |
| 1584 | 1717 | let tip: SharedString = format!("{label} — {shortcut}").into(); |
| 1585 | 1718 | div() |
| 1586 | 1719 | .id(id) |
| @@ -1762,9 +1895,10 @@ fn timecode(t: f64, fps: f64) -> String { | ||
| 1762 | 1895 | #[cfg(test)] |
| 1763 | 1896 | mod tests { |
| 1764 | 1897 | use super::{ |
| 1765 | - CONTROL_H, HIT_MIN, KEYS_ROW_H, KEYS_W, LANE_H, Quality, RULER_HIT_H, SOURCE_TINTS, | |
| 1766 | - SURFACE, cancels_export, export_path, export_settings, frac_along, is_bare_modifier, | |
| 1767 | - is_project, keymap, project_path, push_digit, scrub_due, source_tint, timecode, width_frac, | |
| 1898 | + CONTROL_H, HIT_MIN, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LANE_H, Quality, RULER_HIT_H, | |
| 1899 | + SOURCE_TINTS, SURFACE, Volume, cancels_export, export_path, export_settings, frac_along, | |
| 1900 | + is_bare_modifier, is_project, keymap, project_path, push_digit, scrub_due, source_tint, | |
| 1901 | + timecode, width_frac, | |
| 1768 | 1902 | }; |
| 1769 | 1903 | use gpui::{Bounds, Pixels, point, px, size}; |
| 1770 | 1904 | use std::time::Duration; |
| @@ -1908,24 +2042,83 @@ mod tests { | ||
| 1908 | 2042 | |
| 1909 | 2043 | #[test] |
| 1910 | 2044 | fn the_keybindings_card_fits_the_smallest_window() { |
| 1911 | - // A row per action -- not per binding, which is why the count is | |
| 1912 | - // `ALL` -- under a title and a status line, inside the 640x360 the rest | |
| 1913 | - // of the layout is already sized for. | |
| 1914 | - let rows = keymap::ActionId::ALL.len() as f32; | |
| 2045 | + // The row list is capped and scrolls, so the card's height no longer | |
| 2046 | + // depends on how many actions there are: a title, a status line and the | |
| 2047 | + // viewport, inside the 640x360 the rest of the layout is sized for. | |
| 1915 | 2048 | let title = 17.; // 13 px text on its own line |
| 1916 | 2049 | let status = 28.; // 11 px text, two lines: a refusal wraps |
| 1917 | - let gaps = (rows + 1.) * 2.; | |
| 2050 | + let gaps = 3. * 2.; | |
| 1918 | 2051 | let padding = 24.; |
| 1919 | 2052 | assert!( |
| 1920 | - title + status + rows * KEYS_ROW_H + gaps + padding <= 360., | |
| 2053 | + title + status + KEYS_ROWS_H + gaps + padding <= 360., | |
| 1921 | 2054 | "card too tall" |
| 1922 | 2055 | ); |
| 2056 | + // The cap is only honest if it is the taller list that scrolls, not the | |
| 2057 | + // card that grows: every action must be reachable by scrolling, and | |
| 2058 | + // enough of them visible that the list reads as a list. | |
| 2059 | + assert!( | |
| 2060 | + KEYS_ROWS_H / KEYS_ROW_H >= 8., | |
| 2061 | + "too few rows visible to scan" | |
| 2062 | + ); | |
| 1923 | 2063 | assert!(KEYS_W <= 640., "card too wide"); |
| 1924 | 2064 | // The rows are clickable, so WCAG 2.5.8 binds them like every other |
| 1925 | 2065 | // target in this window. |
| 1926 | 2066 | assert!(KEYS_ROW_H >= HIT_MIN); |
| 1927 | 2067 | } |
| 1928 | 2068 | |
| 2069 | + /// Mute and level are one control with two states, and the whole point is | |
| 2070 | + /// that mute keeps the level: the user gets back what they had, not 100%. | |
| 2071 | + #[test] | |
| 2072 | + fn muting_keeps_the_level_it_comes_back_to() { | |
| 2073 | + let mut volume = Volume::default(); | |
| 2074 | + assert_eq!(volume.gain(), 1.0); | |
| 2075 | + assert_eq!(volume.label(), "Vol 100%"); | |
| 2076 | + | |
| 2077 | + // Four presses down, then muted: the gain is silence but the level is | |
| 2078 | + // still what it was, and the button keeps saying so. | |
| 2079 | + for _ in 0..4 { | |
| 2080 | + volume.step(false); | |
| 2081 | + } | |
| 2082 | + assert_eq!(volume.gain(), 0.8); | |
| 2083 | + volume.muted = true; | |
| 2084 | + assert_eq!(volume.gain(), 0.0); | |
| 2085 | + assert_eq!(volume.label(), "Muted 80%"); | |
| 2086 | + | |
| 2087 | + // Turning it down while muted stays muted -- the one thing a mute | |
| 2088 | + // button must never do is get louder because you asked for quieter. | |
| 2089 | + volume.step(false); | |
| 2090 | + assert_eq!(volume.gain(), 0.0); | |
| 2091 | + assert!(volume.muted); | |
| 2092 | + | |
| 2093 | + // Unmute returns to the level, including the step taken while silent. | |
| 2094 | + volume.muted = false; | |
| 2095 | + assert_eq!(volume.gain(), 0.75); | |
| 2096 | + } | |
| 2097 | + | |
| 2098 | + /// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`, | |
| 2099 | + /// and a wrapped step count would hand it something else. | |
| 2100 | + #[test] | |
| 2101 | + fn the_volume_stops_at_both_ends() { | |
| 2102 | + let mut volume = Volume::default(); | |
| 2103 | + for _ in 0..40 { | |
| 2104 | + volume.step(true); | |
| 2105 | + } | |
| 2106 | + assert_eq!(volume.gain(), 1.0); | |
| 2107 | + assert_eq!(volume.steps, Volume::MAX_STEPS); | |
| 2108 | + | |
| 2109 | + for _ in 0..40 { | |
| 2110 | + volume.step(false); | |
| 2111 | + } | |
| 2112 | + assert_eq!(volume.gain(), 0.0); | |
| 2113 | + assert_eq!(volume.label(), "Vol 0%"); | |
| 2114 | + | |
| 2115 | + // Silent by the level rather than by the flag is still not muted: the | |
| 2116 | + // button says which, because only one of them survives a step up. | |
| 2117 | + assert!(!volume.muted); | |
| 2118 | + volume.step(true); | |
| 2119 | + assert_eq!(volume.gain(), 0.05); | |
| 2120 | + } | |
| 2121 | + | |
| 1929 | 2122 | #[test] |
| 1930 | 2123 | fn a_quality_row_is_the_bitrate_it_promises() { |
| 1931 | 2124 | // Auto is the one row that says nothing: the exporter derives it, and |
| @@ -2106,6 +2299,9 @@ fn main() { | ||
| 2106 | 2299 | // screen. An empty window has none to wait for. |
| 2107 | 2300 | pending_seek: session.is_some(), |
| 2108 | 2301 | session, |
| 2302 | + // Full and unmuted, which is what the session it was just | |
| 2303 | + // handed is already set to: nothing to push at startup. | |
| 2304 | + volume: Volume::default(), | |
| 2109 | 2305 | // Only ever used with a timeline; 30 keeps the empty |
| 2110 | 2306 | // timecode reading in frames rather than in NaN. |
| 2111 | 2307 | fps: meta.map_or(30., |meta| meta.frame_rate), |
crates/engine-audio/src/lib.rsmodified+87 -1
| @@ -91,6 +91,27 @@ impl Ring { | ||
| 91 | 91 | } |
| 92 | 92 | } |
| 93 | 93 | |
| 94 | +/// Multiplies the little-endian f32 samples in `dst` by `gain`, in place. | |
| 95 | +/// | |
| 96 | +/// This is how the editor's volume and mute are applied, rather than through | |
| 97 | +/// the stream's PipeWire volume control: the session manager persists every | |
| 98 | +/// change to a node's Props into its restore state (measured: WirePlumber | |
| 99 | +/// writes the bucket ~2 s after the change), so a mute keypress here would | |
| 100 | +/// become "edith is muted" in the system mixer tomorrow, and a quit while | |
| 101 | +/// muted would come back muted with nothing in the app to explain it. Scaling | |
| 102 | +/// the samples is invisible to the daemon, costs one multiply each, and -- | |
| 103 | +/// because the frames are still consumed and still handed over -- leaves the | |
| 104 | +/// device clock, and so the whole A/V sync, exactly where it was. | |
| 105 | +fn scale(dst: &mut [u8], gain: f32) { | |
| 106 | + if gain == 1.0 { | |
| 107 | + return; | |
| 108 | + } | |
| 109 | + for sample in dst.chunks_exact_mut(4) { | |
| 110 | + let scaled = f32::from_le_bytes(sample.try_into().unwrap_or([0; 4])) * gain; | |
| 111 | + sample.copy_from_slice(&scaled.to_le_bytes()); | |
| 112 | + } | |
| 113 | +} | |
| 114 | + | |
| 94 | 115 | /// The consumer half of a flush: drops everything queued, then pops as usual. |
| 95 | 116 | /// Doing it here rather than in `ao_flush` keeps the ring single-consumer -- |
| 96 | 117 | /// only the RT thread ever moves `read` -- and means a flush asked for while |
| @@ -132,6 +153,9 @@ struct Shared { | ||
| 132 | 153 | /// graph clock keeps ticking while the stream is inactive, and that time |
| 133 | 154 | /// was never played. |
| 134 | 155 | resumed: AtomicBool, |
| 156 | + /// Output gain as f32 bits, 1.0 until the caller says otherwise. Read once | |
| 157 | + /// per callback on the RT thread, so it is an atomic rather than a lock. | |
| 158 | + gain: AtomicU32, | |
| 135 | 159 | underruns: AtomicU64, |
| 136 | 160 | } |
| 137 | 161 | |
| @@ -228,6 +252,13 @@ fn run( | ||
| 228 | 252 | slice[got * 4..want * 4].fill(0); |
| 229 | 253 | shared.underruns.fetch_add(1, Ordering::Relaxed); |
| 230 | 254 | } |
| 255 | + // After the fill, so the silence stays silent whatever | |
| 256 | + // the gain is, and the underrun count keeps meaning | |
| 257 | + // "the decoder was late" rather than "the user muted". | |
| 258 | + scale( | |
| 259 | + &mut slice[..want * 4], | |
| 260 | + f32::from_bits(shared.gain.load(Ordering::Relaxed)), | |
| 261 | + ); | |
| 231 | 262 | frames |
| 232 | 263 | } |
| 233 | 264 | None => 0, |
| @@ -377,6 +408,7 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { | ||
| 377 | 408 | dead: AtomicBool::new(false), |
| 378 | 409 | flush: AtomicBool::new(false), |
| 379 | 410 | resumed: AtomicBool::new(false), |
| 411 | + gain: AtomicU32::new(1.0f32.to_bits()), | |
| 380 | 412 | underruns: AtomicU64::new(0), |
| 381 | 413 | }); |
| 382 | 414 | let (ready_tx, ready_rx) = mpsc::channel(); |
| @@ -471,6 +503,32 @@ pub unsafe extern "C" fn ao_set_active(session: *mut c_void, active: u32) -> i32 | ||
| 471 | 503 | .unwrap_or(-1) |
| 472 | 504 | } |
| 473 | 505 | |
| 506 | +/// Sets the output gain: 0.0 is silence, 1.0 is the samples as written. One | |
| 507 | +/// knob for both the editor's volume and its mute -- mute is a gain of 0.0 | |
| 508 | +/// pushed down, and which of the two the user is looking at is the caller's | |
| 509 | +/// business. Takes effect on the next callback (~23 ms), and the position keeps | |
| 510 | +/// advancing throughout: this silences the output, it does not pause it. | |
| 511 | +/// 0 on success, negative on failure or a gain that is not in `0.0..=1.0`. | |
| 512 | +/// | |
| 513 | +/// # Safety | |
| 514 | +/// `session` must come from [`ao_open`]. | |
| 515 | +#[unsafe(no_mangle)] | |
| 516 | +pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 { | |
| 517 | + catch_unwind(AssertUnwindSafe(|| { | |
| 518 | + // A NaN would compare false against every bound and then multiply every | |
| 519 | + // sample into a NaN, which is a loud fault in a speaker: refuse it here, | |
| 520 | + // at the ABI, rather than let it reach the RT thread. | |
| 521 | + if session.is_null() || !(0.0..=1.0).contains(&gain) { | |
| 522 | + return -1; | |
| 523 | + } | |
| 524 | + // SAFETY: caller-guaranteed live session. | |
| 525 | + let session = unsafe { &*(session as *const Session) }; | |
| 526 | + session.shared.gain.store(gain.to_bits(), Ordering::Relaxed); | |
| 527 | + 0 | |
| 528 | + })) | |
| 529 | + .unwrap_or(-1) | |
| 530 | +} | |
| 531 | + | |
| 474 | 532 | /// Drops every queued sample, so playback resumes from whatever is written |
| 475 | 533 | /// next: what a seek needs. Takes effect on the next process callback (or the |
| 476 | 534 | /// first one after a resume), and leaves the played position alone -- the |
| @@ -509,7 +567,35 @@ pub unsafe extern "C" fn ao_close(session: *mut c_void) { | ||
| 509 | 567 | |
| 510 | 568 | #[cfg(test)] |
| 511 | 569 | mod tests { |
| 512 | - use super::{AtomicBool, Ordering, Ring, accept, consume}; | |
| 570 | + use super::{AtomicBool, Ordering, Ring, accept, consume, scale}; | |
| 571 | + | |
| 572 | + /// The gain is applied to the bytes the device is about to play, so silence | |
| 573 | + /// really is silence and a partial gain really is quieter -- and 1.0 must | |
| 574 | + /// leave the samples bit-identical, since that is every callback's path. | |
| 575 | + #[test] | |
| 576 | + fn gain_scales_the_samples_the_device_sees() { | |
| 577 | + let sample = | |
| 578 | + |bytes: &[u8], i: usize| f32::from_le_bytes(bytes[i..i + 4].try_into().unwrap()); | |
| 579 | + | |
| 580 | + let mut buf = Vec::new(); | |
| 581 | + for v in [1.0f32, -0.5, 0.25] { | |
| 582 | + buf.extend_from_slice(&v.to_le_bytes()); | |
| 583 | + } | |
| 584 | + | |
| 585 | + // Unity is the no-op the common case walks through. | |
| 586 | + let untouched = buf.clone(); | |
| 587 | + scale(&mut buf, 1.0); | |
| 588 | + assert_eq!(buf, untouched); | |
| 589 | + | |
| 590 | + // Half volume, sign kept. | |
| 591 | + scale(&mut buf, 0.5); | |
| 592 | + assert_eq!(sample(&buf, 0), 0.5); | |
| 593 | + assert_eq!(sample(&buf, 4), -0.25); | |
| 594 | + | |
| 595 | + // Mute is a gain of zero: every sample gone, none left ringing. | |
| 596 | + scale(&mut buf, 0.0); | |
| 597 | + assert!(buf.chunks_exact(4).all(|s| sample(s, 0) == 0.0)); | |
| 598 | + } | |
| 513 | 599 | |
| 514 | 600 | /// The paused-seek ordering: a flush requested with no RT callbacks running |
| 515 | 601 | /// must not let the writer queue new audio behind the pending discard. |
crates/engine/src/ao.rsmodified+15 -1
| @@ -18,6 +18,7 @@ struct Plugin { | ||
| 18 | 18 | write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize, |
| 19 | 19 | position: unsafe extern "C" fn(*mut c_void) -> i64, |
| 20 | 20 | set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, |
| 21 | + set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32, | |
| 21 | 22 | flush: unsafe extern "C" fn(*mut c_void) -> i32, |
| 22 | 23 | close: unsafe extern "C" fn(*mut c_void), |
| 23 | 24 | // Never dropped (lives in a static), so the fn pointers above stay valid. |
| @@ -56,7 +57,11 @@ fn load() -> Option<Plugin> { | ||
| 56 | 57 | position: *lib.get(b"ao_position\0").ok()?, |
| 57 | 58 | set_active: *lib.get(b"ao_set_active\0").ok()?, |
| 58 | 59 | // Required, so a plugin predating seek is rejected whole |
| 59 | - // and we play muted rather than half-working. | |
| 60 | + // and we play muted rather than half-working. Volume is | |
| 61 | + // required on the same terms: the two ship from one build, | |
| 62 | + // and a mute button that does nothing is worse than a run | |
| 63 | + // with no sound at all, which at least says so. | |
| 64 | + set_volume: *lib.get(b"ao_set_volume\0").ok()?, | |
| 60 | 65 | flush: *lib.get(b"ao_flush\0").ok()?, |
| 61 | 66 | close: *lib.get(b"ao_close\0").ok()?, |
| 62 | 67 | _lib: lib, |
| @@ -123,6 +128,15 @@ impl AoSession { | ||
| 123 | 128 | unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 } |
| 124 | 129 | } |
| 125 | 130 | |
| 131 | + /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's | |
| 132 | + /// volume and its mute are the same knob by the time they get here. The | |
| 133 | + /// clock is unaffected -- a silenced stream still plays, so the picture | |
| 134 | + /// keeps running against it. `false` for a gain outside the range. | |
| 135 | + pub fn set_volume(&self, gain: f32) -> bool { | |
| 136 | + // SAFETY: `handle` came from `ao_open` and is still open. | |
| 137 | + unsafe { (self.plugin.set_volume)(self.handle, gain) == 0 } | |
| 138 | + } | |
| 139 | + | |
| 126 | 140 | /// Drops everything still queued, so the next samples written play right |
| 127 | 141 | /// away -- what a seek needs. The played position keeps counting. |
| 128 | 142 | pub fn flush(&self) -> bool { |
crates/engine/src/playback.rsmodified+19 -0
| @@ -465,6 +465,25 @@ impl PlaybackSession { | ||
| 465 | 465 | } |
| 466 | 466 | } |
| 467 | 467 | |
| 468 | + /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0: | |
| 469 | + /// one knob, because muting and turning it down are the same thing to the | |
| 470 | + /// device, and *which* the user meant is a question only the UI can answer | |
| 471 | + /// -- it keeps the level to come back to. | |
| 472 | + /// | |
| 473 | + /// Deliberately not session state: nothing here remembers it, so a caller | |
| 474 | + /// pushes it once per session and an export -- which renders the file | |
| 475 | + /// rather than what the speakers are doing -- can never pick it up. Silent | |
| 476 | + /// with no audio device, which is also the only honest answer there. | |
| 477 | + /// | |
| 478 | + /// Mute is not pause: the samples are still consumed and the device clock | |
| 479 | + /// still runs, so the picture keeps playing against it. | |
| 480 | + pub fn set_gain(&self, gain: f32) -> bool { | |
| 481 | + match &self.audio { | |
| 482 | + Some(audio) => audio.ao.lock().unwrap().set_volume(gain), | |
| 483 | + None => false, | |
| 484 | + } | |
| 485 | + } | |
| 486 | + | |
| 468 | 487 | /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode |
| 469 | 488 | /// workers are replaced rather than steered: a fresh channel cannot hold a |
| 470 | 489 | /// stale frame, and it works just as well after EOF, where the old workers |
crates/engine/tests/ao_output.rsmodified+45 -0
| @@ -88,6 +88,51 @@ fn plays_and_tracks_position() { | ||
| 88 | 88 | ); |
| 89 | 89 | } |
| 90 | 90 | |
| 91 | +/// Muting is not pausing: the device keeps consuming and the master clock keeps | |
| 92 | +/// running, which is the whole reason the picture can play on through a mute. | |
| 93 | +/// That the samples really go quiet is the plugin's own `scale` unit test -- | |
| 94 | +/// nothing out here can hear the device. | |
| 95 | +#[test] | |
| 96 | +#[ignore = "needs libengine_audio.so and a PipeWire daemon"] | |
| 97 | +fn muting_silences_without_stopping_the_clock() { | |
| 98 | + assert!(AoSession::probe(), "plugin not loadable"); | |
| 99 | + let mut ao = AoSession::open(RATE, CHANNELS).expect("no PipeWire playback available"); | |
| 100 | + | |
| 101 | + let samples = tone(); | |
| 102 | + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); | |
| 103 | + let first = wait_for_playback(&ao, Duration::from_secs(2)); | |
| 104 | + | |
| 105 | + // Mute, then keep it fed: the position must move exactly as it would have. | |
| 106 | + assert!(ao.set_volume(0.0), "mute rejected"); | |
| 107 | + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); | |
| 108 | + std::thread::sleep(Duration::from_millis(300)); | |
| 109 | + let muted = ao.position().expect("position went unknown"); | |
| 110 | + let advanced = muted - first; | |
| 111 | + let expected = RATE as i64 * 300 / 1000; | |
| 112 | + eprintln!("clock advanced {advanced} samples in 300 ms while muted (expected ~{expected})"); | |
| 113 | + assert!( | |
| 114 | + (advanced - expected).abs() < expected / 5, | |
| 115 | + "the clock stalled while muted: {advanced} samples in 300 ms" | |
| 116 | + ); | |
| 117 | + | |
| 118 | + // Every level in range is taken, and the two ends are in range. | |
| 119 | + for gain in [0.0, 0.5, 1.0] { | |
| 120 | + assert!(ao.set_volume(gain), "gain {gain} rejected"); | |
| 121 | + } | |
| 122 | + // Out of range is refused at the ABI rather than multiplied into the | |
| 123 | + // speakers -- a NaN would otherwise reach the RT thread and stay there. | |
| 124 | + for gain in [-0.1, 1.5, f32::NAN, f32::INFINITY] { | |
| 125 | + assert!(!ao.set_volume(gain), "gain {gain} accepted"); | |
| 126 | + } | |
| 127 | + // ...and a refusal changes nothing: the last accepted gain still stands. | |
| 128 | + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); | |
| 129 | + std::thread::sleep(Duration::from_millis(100)); | |
| 130 | + assert!( | |
| 131 | + ao.position().expect("position went unknown") > muted, | |
| 132 | + "clock stopped after a refused gain" | |
| 133 | + ); | |
| 134 | +} | |
| 135 | + | |
| 91 | 136 | /// No reachable daemon must fail the open cleanly and quickly, never hang. |
| 92 | 137 | #[test] |
| 93 | 138 | #[ignore = "needs libengine_audio.so and a PipeWire daemon"] |