forge
Explore
Log in

Don't you dare go Hollow

Volume and mute for the monitoring output

Browse files at this commit

bb07bdc3c81dc187fc00f0fb339ecc54313386a4Ahmet Kaan GümüşParent: 935d5f0
  • feat
    • volume and mute for the monitoring output
Show full message
🔊 feat(audio): volume and mute for the monitoring output

One knob down the stack: `ao_set_volume(handle, gain)` scales the samples
in the RT callback, and mute is a gain of 0.0. Not the stream's PipeWire
volume control -- WirePlumber persists every Props change into its restore
state (measured on this box: the bucket gains `mute:true` ~2 s later), so
a mute keypress would have become "edith has no sound" in tomorrow's
system mixer, which is the bug 9ab4ebd just finished removing.

Volume and mute stay independent: turning the level down while muted must
not be what makes sound come out. The button says both at once.

Mute is not pause -- the frames are still consumed, so the device clock,
and with it the picture, runs straight through.

The keybindings card's row list now scrolls inside a cap, which is the
upgrade path its own ponytail named: three more actions no longer fit a
360 px window, and now no number of them can stop fitting.
crates/app/src/keymap.rsmodified+27 -3
@@ -46,13 +46,16 @@ pub enum ActionId {
4646 Cut,
4747 Delete,
4848 Undo,
49+ ToggleMute,
50+ VolumeUp,
51+ VolumeDown,
4952 CancelExport,
5053 }
5154
5255 impl ActionId {
5356 /// Display order everywhere -- the editor lists them in it and
5457 /// [`Keymap::defaults`] binds them in it.
55- pub const ALL: [ActionId; 9] = [
58+ pub const ALL: [ActionId; 12] = [
5659 ActionId::Play,
5760 ActionId::Export,
5861 ActionId::Save,
@@ -61,6 +64,9 @@ impl ActionId {
6164 ActionId::Cut,
6265 ActionId::Delete,
6366 ActionId::Undo,
67+ ActionId::ToggleMute,
68+ ActionId::VolumeUp,
69+ ActionId::VolumeDown,
6470 ActionId::CancelExport,
6571 ];
6672
@@ -75,6 +81,9 @@ impl ActionId {
7581 ActionId::Cut => "Cut",
7682 ActionId::Delete => "Delete",
7783 ActionId::Undo => "Undo",
84+ ActionId::ToggleMute => "Mute / Unmute",
85+ ActionId::VolumeUp => "Volume up",
86+ ActionId::VolumeDown => "Volume down",
7887 ActionId::CancelExport => "Cancel export",
7988 }
8089 }
@@ -91,6 +100,9 @@ impl ActionId {
91100 ActionId::Cut => "cut",
92101 ActionId::Delete => "delete",
93102 ActionId::Undo => "undo",
103+ ActionId::ToggleMute => "toggle-mute",
104+ ActionId::VolumeUp => "volume-up",
105+ ActionId::VolumeDown => "volume-down",
94106 ActionId::CancelExport => "cancel-export",
95107 }
96108 }
@@ -199,6 +211,12 @@ impl Keymap {
199211 b(ActionId::Delete, "delete", false),
200212 b(ActionId::Undo, "z", false),
201213 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),
202220 b(ActionId::CancelExport, "escape", false),
203221 ],
204222 }
@@ -425,7 +443,7 @@ mod tests {
425443 #[test]
426444 fn every_default_stroke_reaches_its_action() {
427445 let k = Keymap::defaults();
428- assert_eq!(k.entries().len(), 11);
446+ assert_eq!(k.entries().len(), 14);
429447 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
430448 assert_eq!(k.lookup("e", false), Some(ActionId::Export));
431449 assert_eq!(k.lookup("s", true), Some(ActionId::Save));
@@ -436,6 +454,12 @@ mod tests {
436454 assert_eq!(k.lookup("delete", false), Some(ActionId::Delete));
437455 assert_eq!(k.lookup("z", false), Some(ActionId::Undo));
438456 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);
439463 assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport));
440464 // The modifier is half the chord: ctrl+e is not e.
441465 assert_eq!(k.lookup("e", true), None);
@@ -564,7 +588,7 @@ mod tests {
564588 );
565589 // The label is the editor's column, and never the file's word for it.
566590 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
567- assert_eq!(ActionId::ALL.len(), 9);
591+ assert_eq!(ActionId::ALL.len(), 12);
568592 }
569593
570594 #[test]
crates/app/src/main.rsmodified+210 -14
@@ -60,6 +60,10 @@ const TIME_W: f32 = 200.;
6060 /// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too.
6161 const KEYS_W: f32 = 320.;
6262 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;
6367
6468 /// The one key name this file still spells out, and gpui's spelling of it: it
6569 /// 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;
6771 /// through the keymap to find it.
6872 const ESCAPE: &str = "escape";
6973
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+
70136 struct Player {
71137 /// The timeline, once there is one. A run with no file opens without it and
72138 /// waits: the first media import or project load is what fills it, and
@@ -117,6 +183,12 @@ struct Player {
117183 /// Which stroke means what, and what every shortcut on screen is called.
118184 /// The one place either question is answered.
119185 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,
120192 /// The keybindings overlay is up. While it is, it owns the keyboard and the
121193 /// pointer: a stroke or a click meant for a row must not also cut the
122194 /// timeline.
@@ -322,6 +394,9 @@ impl Player {
322394 Ok(session) => {
323395 self.fps = session.meta().frame_rate;
324396 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();
325400 self.export_path = export_path(path);
326401 self.project_path = project_path(path);
327402 self.name = file_name(path).into();
@@ -376,6 +451,7 @@ impl Player {
376451 // media: that is the only place an export has ever landed.
377452 self.export_path = export_path(&session.sources()[0]);
378453 self.session = Some(session);
454+ self.apply_volume();
379455 self.project_path = path.to_path_buf();
380456 self.name = file_name(path).into();
381457 // A copied clip names its source by index, which means a
@@ -472,6 +548,26 @@ impl Player {
472548
473549 /// The play binding and the transport button share it: once the timeline is finished
474550 /// 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+
475571 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {
476572 if self.exporting().is_some() {
477573 return;
@@ -729,6 +825,11 @@ impl Render for Player {
729825 Some(ActionId::Cut) => this.cut(cx),
730826 Some(ActionId::Delete) => this.delete_selected(cx),
731827 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),
732833 // Nothing to cancel while nothing is exporting.
733834 Some(ActionId::CancelExport) | None => {}
734835 }
@@ -931,6 +1032,24 @@ impl Player {
9311032 live && self.selected.is_some(),
9321033 cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)),
9331034 ))
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+ ))
9341053 .child(separator())
9351054 .child(control(
9361055 "import",
@@ -1164,9 +1283,9 @@ impl Player {
11641283 // two, and the notice bar it would otherwise appear in is
11651284 // under the scrim.
11661285 //
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.
11701289 .child(
11711290 div()
11721291 .flex_none()
@@ -1179,7 +1298,19 @@ impl Player {
11791298 .unwrap_or_else(|| "click a row, then press a key".into()),
11801299 ),
11811300 )
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+ ),
11831314 ),
11841315 )
11851316 }
@@ -1576,11 +1707,13 @@ fn width_frac(len: f64, total: f64) -> f32 {
15761707 fn control(
15771708 id: &'static str,
15781709 glyph: Option<AnyElement>,
1579- label: &'static str,
1710+ // Not `&'static str`: the volume button's label is its state.
1711+ label: impl Into<SharedString>,
15801712 shortcut: String,
15811713 enabled: bool,
15821714 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
15831715 ) -> impl IntoElement {
1716+ let label = label.into();
15841717 let tip: SharedString = format!("{label} — {shortcut}").into();
15851718 div()
15861719 .id(id)
@@ -1762,9 +1895,10 @@ fn timecode(t: f64, fps: f64) -> String {
17621895 #[cfg(test)]
17631896 mod tests {
17641897 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,
17681902 };
17691903 use gpui::{Bounds, Pixels, point, px, size};
17701904 use std::time::Duration;
@@ -1908,24 +2042,83 @@ mod tests {
19082042
19092043 #[test]
19102044 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.
19152048 let title = 17.; // 13 px text on its own line
19162049 let status = 28.; // 11 px text, two lines: a refusal wraps
1917- let gaps = (rows + 1.) * 2.;
2050+ let gaps = 3. * 2.;
19182051 let padding = 24.;
19192052 assert!(
1920- title + status + rows * KEYS_ROW_H + gaps + padding <= 360.,
2053+ title + status + KEYS_ROWS_H + gaps + padding <= 360.,
19212054 "card too tall"
19222055 );
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+ );
19232063 assert!(KEYS_W <= 640., "card too wide");
19242064 // The rows are clickable, so WCAG 2.5.8 binds them like every other
19252065 // target in this window.
19262066 assert!(KEYS_ROW_H >= HIT_MIN);
19272067 }
19282068
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+
19292122 #[test]
19302123 fn a_quality_row_is_the_bitrate_it_promises() {
19312124 // Auto is the one row that says nothing: the exporter derives it, and
@@ -2106,6 +2299,9 @@ fn main() {
21062299 // screen. An empty window has none to wait for.
21072300 pending_seek: session.is_some(),
21082301 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(),
21092305 // Only ever used with a timeline; 30 keeps the empty
21102306 // timecode reading in frames rather than in NaN.
21112307 fps: meta.map_or(30., |meta| meta.frame_rate),
crates/engine-audio/src/lib.rsmodified+87 -1
@@ -91,6 +91,27 @@ impl Ring {
9191 }
9292 }
9393
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+
94115 /// The consumer half of a flush: drops everything queued, then pops as usual.
95116 /// Doing it here rather than in `ao_flush` keeps the ring single-consumer --
96117 /// only the RT thread ever moves `read` -- and means a flush asked for while
@@ -132,6 +153,9 @@ struct Shared {
132153 /// graph clock keeps ticking while the stream is inactive, and that time
133154 /// was never played.
134155 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,
135159 underruns: AtomicU64,
136160 }
137161
@@ -228,6 +252,13 @@ fn run(
228252 slice[got * 4..want * 4].fill(0);
229253 shared.underruns.fetch_add(1, Ordering::Relaxed);
230254 }
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+ );
231262 frames
232263 }
233264 None => 0,
@@ -377,6 +408,7 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void {
377408 dead: AtomicBool::new(false),
378409 flush: AtomicBool::new(false),
379410 resumed: AtomicBool::new(false),
411+ gain: AtomicU32::new(1.0f32.to_bits()),
380412 underruns: AtomicU64::new(0),
381413 });
382414 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
471503 .unwrap_or(-1)
472504 }
473505
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+
474532 /// Drops every queued sample, so playback resumes from whatever is written
475533 /// next: what a seek needs. Takes effect on the next process callback (or the
476534 /// 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) {
509567
510568 #[cfg(test)]
511569 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+ }
513599
514600 /// The paused-seek ordering: a flush requested with no RT callbacks running
515601 /// 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 {
1818 write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize,
1919 position: unsafe extern "C" fn(*mut c_void) -> i64,
2020 set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32,
21+ set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32,
2122 flush: unsafe extern "C" fn(*mut c_void) -> i32,
2223 close: unsafe extern "C" fn(*mut c_void),
2324 // Never dropped (lives in a static), so the fn pointers above stay valid.
@@ -56,7 +57,11 @@ fn load() -> Option<Plugin> {
5657 position: *lib.get(b"ao_position\0").ok()?,
5758 set_active: *lib.get(b"ao_set_active\0").ok()?,
5859 // 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()?,
6065 flush: *lib.get(b"ao_flush\0").ok()?,
6166 close: *lib.get(b"ao_close\0").ok()?,
6267 _lib: lib,
@@ -123,6 +128,15 @@ impl AoSession {
123128 unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 }
124129 }
125130
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+
126140 /// Drops everything still queued, so the next samples written play right
127141 /// away -- what a seek needs. The played position keeps counting.
128142 pub fn flush(&self) -> bool {
crates/engine/src/playback.rsmodified+19 -0
@@ -465,6 +465,25 @@ impl PlaybackSession {
465465 }
466466 }
467467
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+
468487 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
469488 /// workers are replaced rather than steered: a fresh channel cannot hold a
470489 /// 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() {
8888 );
8989 }
9090
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+
91136 /// No reachable daemon must fail the open cleanly and quickly, never hang.
92137 #[test]
93138 #[ignore = "needs libengine_audio.so and a PipeWire daemon"]