diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 4d7da28..12c454a 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -46,13 +46,16 @@ pub enum ActionId { Cut, Delete, Undo, + ToggleMute, + VolumeUp, + VolumeDown, CancelExport, } impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 9] = [ + pub const ALL: [ActionId; 12] = [ ActionId::Play, ActionId::Export, ActionId::Save, @@ -61,6 +64,9 @@ impl ActionId { ActionId::Cut, ActionId::Delete, ActionId::Undo, + ActionId::ToggleMute, + ActionId::VolumeUp, + ActionId::VolumeDown, ActionId::CancelExport, ]; @@ -75,6 +81,9 @@ impl ActionId { ActionId::Cut => "Cut", ActionId::Delete => "Delete", ActionId::Undo => "Undo", + ActionId::ToggleMute => "Mute / Unmute", + ActionId::VolumeUp => "Volume up", + ActionId::VolumeDown => "Volume down", ActionId::CancelExport => "Cancel export", } } @@ -91,6 +100,9 @@ impl ActionId { ActionId::Cut => "cut", ActionId::Delete => "delete", ActionId::Undo => "undo", + ActionId::ToggleMute => "toggle-mute", + ActionId::VolumeUp => "volume-up", + ActionId::VolumeDown => "volume-down", ActionId::CancelExport => "cancel-export", } } @@ -199,6 +211,12 @@ impl Keymap { b(ActionId::Delete, "delete", false), b(ActionId::Undo, "z", false), b(ActionId::Undo, "z", true), + b(ActionId::ToggleMute, "m", false), + // The unshifted pair, which is what gpui reports for those two + // keys ("=" and "-", platform.rs:862): the volume keys every + // player has, without asking for shift to make the "+". + b(ActionId::VolumeUp, "=", false), + b(ActionId::VolumeDown, "-", false), b(ActionId::CancelExport, "escape", false), ], } @@ -425,7 +443,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 11); + assert_eq!(k.entries().len(), 14); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); assert_eq!(k.lookup("e", false), Some(ActionId::Export)); assert_eq!(k.lookup("s", true), Some(ActionId::Save)); @@ -436,6 +454,12 @@ mod tests { assert_eq!(k.lookup("delete", false), Some(ActionId::Delete)); assert_eq!(k.lookup("z", false), Some(ActionId::Undo)); assert_eq!(k.lookup("z", true), Some(ActionId::Undo)); + assert_eq!(k.lookup("m", false), Some(ActionId::ToggleMute)); + // The volume pair is the unshifted one, so neither needs a modifier + // and neither is the "+" gpui reports for shift+=. + assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp)); + assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown)); + assert_eq!(k.lookup("+", false), None); assert_eq!(k.lookup("escape", false), Some(ActionId::CancelExport)); // The modifier is half the chord: ctrl+e is not e. assert_eq!(k.lookup("e", true), None); @@ -564,7 +588,7 @@ mod tests { ); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 9); + assert_eq!(ActionId::ALL.len(), 12); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 7038c8e..55cde5e 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -60,6 +60,10 @@ const TIME_W: f32 = 200.; /// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too. const KEYS_W: f32 = 320.; const KEYS_ROW_H: f32 = HIT_MIN; +/// How much of the row list is on screen at once; past this it scrolls. What +/// keeps the card inside the smallest window no matter how many actions the +/// editor grows -- ten rows fit here, and the eleventh is a scroll away. +const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; /// The one key name this file still spells out, and gpui's spelling of it: it /// 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; /// through the keymap to find it. const ESCAPE: &str = "escape"; +/// What the monitoring output is set to. Two things, not one: the level the +/// user picked, and whether it is being held silent -- so unmuting comes back +/// to the level rather than to a guess. +/// +/// The level counts steps rather than carrying an `f32`, because 5% at a time +/// down and back up again through a float would not land on the number it +/// started from, and the label would eventually read `79%`. +/// +/// Volume and mute stay independent on purpose: turning the level down while +/// muted must not be what makes sound come out. Only the mute key unmutes, and +/// the button says both things at once ("Muted 80%") so neither is a surprise. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +struct Volume { + steps: u8, + muted: bool, +} + +impl Volume { + /// 5% a press: twenty of them across the range. + const MAX_STEPS: u8 = 20; + + /// What the device is set to: mute wins, and the level is what it returns + /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts. + fn gain(self) -> f32 { + if self.muted { + 0. + } else { + f32::from(self.steps) / f32::from(Self::MAX_STEPS) + } + } + + /// One press up or down, clamped at both ends -- saturating, so the count + /// cannot wrap past silence into full volume. + fn step(&mut self, up: bool) { + self.steps = if up { + self.steps.saturating_add(1).min(Self::MAX_STEPS) + } else { + self.steps.saturating_sub(1) + }; + } + + /// What the button reads. The level shows while muted too: it is what the + /// next press of the mute key brings back. + fn label(self) -> String { + let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS); + if self.muted { + format!("Muted {percent}%") + } else { + format!("Vol {percent}%") + } + } +} + +impl Default for Volume { + fn default() -> Self { + Self { + steps: Self::MAX_STEPS, + muted: false, + } + } +} + struct Player { /// The timeline, once there is one. A run with no file opens without it and /// waits: the first media import or project load is what fills it, and @@ -117,6 +183,12 @@ struct Player { /// Which stroke means what, and what every shortcut on screen is called. /// The one place either question is answered. keymap: Keymap, + /// How loud the monitoring is, and whether it is muted. Lives here rather + /// than in the session so it survives closing one file and opening the + /// next -- it is a setting of the player, not of the timeline, which is + /// also why it is not written to the project file and cannot reach an + /// export. [`Player::apply_volume`] is what pushes it at a session. + volume: Volume, /// The keybindings overlay is up. While it is, it owns the keyboard and the /// pointer: a stroke or a click meant for a row must not also cut the /// timeline. @@ -322,6 +394,9 @@ impl Player { Ok(session) => { self.fps = session.meta().frame_rate; self.session = Some(session); + // A fresh session comes up at full volume; the player's own + // setting outlives the file, so it is pushed at every new one. + self.apply_volume(); self.export_path = export_path(path); self.project_path = project_path(path); self.name = file_name(path).into(); @@ -376,6 +451,7 @@ impl Player { // media: that is the only place an export has ever landed. self.export_path = export_path(&session.sources()[0]); self.session = Some(session); + self.apply_volume(); self.project_path = path.to_path_buf(); self.name = file_name(path).into(); // A copied clip names its source by index, which means a @@ -472,6 +548,26 @@ impl Player { /// The play binding and the transport button share it: once the timeline is finished /// the only sensible "play" is from the top. + /// Pushes the current volume at the session, which is the only place it is + /// ever pushed: after a change here, and after a session arrives. A session + /// starts at full volume, so a file opened while muted has to be told -- + /// that is the whole reason this is not just called from the key handler. + /// Silent no-op with no timeline, or with a run that has no audio device. + fn apply_volume(&self) { + if let Some(session) = &self.session { + session.set_gain(self.volume.gain()); + } + } + + /// The mute key and the two volume keys, and the click on the button. The + /// picture is not touched: silencing the output is not pausing it, so the + /// clock -- which the device still drives -- runs straight through. + fn set_volume(&mut self, change: impl FnOnce(&mut Volume), cx: &mut Context) { + change(&mut self.volume); + self.apply_volume(); + cx.notify(); + } + fn toggle_or_restart(&mut self, cx: &mut Context) { if self.exporting().is_some() { return; @@ -729,6 +825,11 @@ impl Render for Player { Some(ActionId::Cut) => this.cut(cx), Some(ActionId::Delete) => this.delete_selected(cx), Some(ActionId::Undo) => this.undo(cx), + Some(ActionId::ToggleMute) => { + this.set_volume(|volume| volume.muted = !volume.muted, cx) + } + Some(ActionId::VolumeUp) => this.set_volume(|volume| volume.step(true), cx), + Some(ActionId::VolumeDown) => this.set_volume(|volume| volume.step(false), cx), // Nothing to cancel while nothing is exporting. Some(ActionId::CancelExport) | None => {} } @@ -931,6 +1032,24 @@ impl Player { live && self.selected.is_some(), cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)), )) + // With the transport, not the edit group: it changes what + // the file sounds like, never what it is. Reads as its own + // state, so muted is legible without a tooltip. + .child(control( + "volume", + None, + self.volume.label(), + format!( + "{} mutes · {} louder · {} quieter", + key(ActionId::ToggleMute), + key(ActionId::VolumeUp), + key(ActionId::VolumeDown) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.set_volume(|volume| volume.muted = !volume.muted, cx) + }), + )) .child(separator()) .child(control( "import", @@ -1164,9 +1283,9 @@ impl Player { // two, and the notice bar it would otherwise appear in is // under the scrim. // - // ponytail: a refusal long enough to wrap to three lines - // pushes the card past a 360 px tall window. The upgrade - // path is a scrolling row list, not a shorter message. + // The row list below is capped and scrolls, so neither a + // wrapped refusal here nor another action added to `ALL` + // can push the card past a 360 px window any more. .child( div() .flex_none() @@ -1179,7 +1298,19 @@ impl Player { .unwrap_or_else(|| "click a row, then press a key".into()), ), ) - .children(rows), + // Capped and scrolling rather than as tall as the action + // list happens to be: the list grows with the editor, + // the smallest window does not. + .child( + div() + .id("keys-rows") + .flex() + .flex_col() + .gap(px(2.)) + .max_h(px(KEYS_ROWS_H)) + .overflow_y_scroll() + .children(rows), + ), ), ) } @@ -1576,11 +1707,13 @@ fn width_frac(len: f64, total: f64) -> f32 { fn control( id: &'static str, glyph: Option, - label: &'static str, + // Not `&'static str`: the volume button's label is its state. + label: impl Into, shortcut: String, enabled: bool, on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, ) -> impl IntoElement { + let label = label.into(); let tip: SharedString = format!("{label} — {shortcut}").into(); div() .id(id) @@ -1762,9 +1895,10 @@ fn timecode(t: f64, fps: f64) -> String { #[cfg(test)] mod tests { use super::{ - CONTROL_H, HIT_MIN, KEYS_ROW_H, KEYS_W, LANE_H, Quality, RULER_HIT_H, SOURCE_TINTS, - SURFACE, cancels_export, export_path, export_settings, frac_along, is_bare_modifier, - is_project, keymap, project_path, push_digit, scrub_due, source_tint, timecode, width_frac, + CONTROL_H, HIT_MIN, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LANE_H, Quality, RULER_HIT_H, + SOURCE_TINTS, SURFACE, Volume, cancels_export, export_path, export_settings, frac_along, + is_bare_modifier, is_project, keymap, project_path, push_digit, scrub_due, source_tint, + timecode, width_frac, }; use gpui::{Bounds, Pixels, point, px, size}; use std::time::Duration; @@ -1908,24 +2042,83 @@ mod tests { #[test] fn the_keybindings_card_fits_the_smallest_window() { - // A row per action -- not per binding, which is why the count is - // `ALL` -- under a title and a status line, inside the 640x360 the rest - // of the layout is already sized for. - let rows = keymap::ActionId::ALL.len() as f32; + // The row list is capped and scrolls, so the card's height no longer + // depends on how many actions there are: a title, a status line and the + // viewport, inside the 640x360 the rest of the layout is sized for. let title = 17.; // 13 px text on its own line let status = 28.; // 11 px text, two lines: a refusal wraps - let gaps = (rows + 1.) * 2.; + let gaps = 3. * 2.; let padding = 24.; assert!( - title + status + rows * KEYS_ROW_H + gaps + padding <= 360., + title + status + KEYS_ROWS_H + gaps + padding <= 360., "card too tall" ); + // The cap is only honest if it is the taller list that scrolls, not the + // card that grows: every action must be reachable by scrolling, and + // enough of them visible that the list reads as a list. + assert!( + KEYS_ROWS_H / KEYS_ROW_H >= 8., + "too few rows visible to scan" + ); assert!(KEYS_W <= 640., "card too wide"); // The rows are clickable, so WCAG 2.5.8 binds them like every other // target in this window. assert!(KEYS_ROW_H >= HIT_MIN); } + /// Mute and level are one control with two states, and the whole point is + /// that mute keeps the level: the user gets back what they had, not 100%. + #[test] + fn muting_keeps_the_level_it_comes_back_to() { + let mut volume = Volume::default(); + assert_eq!(volume.gain(), 1.0); + assert_eq!(volume.label(), "Vol 100%"); + + // Four presses down, then muted: the gain is silence but the level is + // still what it was, and the button keeps saying so. + for _ in 0..4 { + volume.step(false); + } + assert_eq!(volume.gain(), 0.8); + volume.muted = true; + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Muted 80%"); + + // Turning it down while muted stays muted -- the one thing a mute + // button must never do is get louder because you asked for quieter. + volume.step(false); + assert_eq!(volume.gain(), 0.0); + assert!(volume.muted); + + // Unmute returns to the level, including the step taken while silent. + volume.muted = false; + assert_eq!(volume.gain(), 0.75); + } + + /// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`, + /// and a wrapped step count would hand it something else. + #[test] + fn the_volume_stops_at_both_ends() { + let mut volume = Volume::default(); + for _ in 0..40 { + volume.step(true); + } + assert_eq!(volume.gain(), 1.0); + assert_eq!(volume.steps, Volume::MAX_STEPS); + + for _ in 0..40 { + volume.step(false); + } + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Vol 0%"); + + // Silent by the level rather than by the flag is still not muted: the + // button says which, because only one of them survives a step up. + assert!(!volume.muted); + volume.step(true); + assert_eq!(volume.gain(), 0.05); + } + #[test] fn a_quality_row_is_the_bitrate_it_promises() { // Auto is the one row that says nothing: the exporter derives it, and @@ -2106,6 +2299,9 @@ fn main() { // screen. An empty window has none to wait for. pending_seek: session.is_some(), session, + // Full and unmuted, which is what the session it was just + // handed is already set to: nothing to push at startup. + volume: Volume::default(), // Only ever used with a timeline; 30 keeps the empty // timecode reading in frames rather than in NaN. fps: meta.map_or(30., |meta| meta.frame_rate), diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs index 014ef5a..c6f24b2 100644 --- a/crates/engine-audio/src/lib.rs +++ b/crates/engine-audio/src/lib.rs @@ -91,6 +91,27 @@ impl Ring { } } +/// Multiplies the little-endian f32 samples in `dst` by `gain`, in place. +/// +/// This is how the editor's volume and mute are applied, rather than through +/// the stream's PipeWire volume control: the session manager persists every +/// change to a node's Props into its restore state (measured: WirePlumber +/// writes the bucket ~2 s after the change), so a mute keypress here would +/// become "edith is muted" in the system mixer tomorrow, and a quit while +/// muted would come back muted with nothing in the app to explain it. Scaling +/// the samples is invisible to the daemon, costs one multiply each, and -- +/// because the frames are still consumed and still handed over -- leaves the +/// device clock, and so the whole A/V sync, exactly where it was. +fn scale(dst: &mut [u8], gain: f32) { + if gain == 1.0 { + return; + } + for sample in dst.chunks_exact_mut(4) { + let scaled = f32::from_le_bytes(sample.try_into().unwrap_or([0; 4])) * gain; + sample.copy_from_slice(&scaled.to_le_bytes()); + } +} + /// The consumer half of a flush: drops everything queued, then pops as usual. /// Doing it here rather than in `ao_flush` keeps the ring single-consumer -- /// only the RT thread ever moves `read` -- and means a flush asked for while @@ -132,6 +153,9 @@ struct Shared { /// graph clock keeps ticking while the stream is inactive, and that time /// was never played. resumed: AtomicBool, + /// Output gain as f32 bits, 1.0 until the caller says otherwise. Read once + /// per callback on the RT thread, so it is an atomic rather than a lock. + gain: AtomicU32, underruns: AtomicU64, } @@ -228,6 +252,13 @@ fn run( slice[got * 4..want * 4].fill(0); shared.underruns.fetch_add(1, Ordering::Relaxed); } + // After the fill, so the silence stays silent whatever + // the gain is, and the underrun count keeps meaning + // "the decoder was late" rather than "the user muted". + scale( + &mut slice[..want * 4], + f32::from_bits(shared.gain.load(Ordering::Relaxed)), + ); frames } None => 0, @@ -377,6 +408,7 @@ pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { dead: AtomicBool::new(false), flush: AtomicBool::new(false), resumed: AtomicBool::new(false), + gain: AtomicU32::new(1.0f32.to_bits()), underruns: AtomicU64::new(0), }); 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 .unwrap_or(-1) } +/// Sets the output gain: 0.0 is silence, 1.0 is the samples as written. One +/// knob for both the editor's volume and its mute -- mute is a gain of 0.0 +/// pushed down, and which of the two the user is looking at is the caller's +/// business. Takes effect on the next callback (~23 ms), and the position keeps +/// advancing throughout: this silences the output, it does not pause it. +/// 0 on success, negative on failure or a gain that is not in `0.0..=1.0`. +/// +/// # Safety +/// `session` must come from [`ao_open`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 { + catch_unwind(AssertUnwindSafe(|| { + // A NaN would compare false against every bound and then multiply every + // sample into a NaN, which is a loud fault in a speaker: refuse it here, + // at the ABI, rather than let it reach the RT thread. + if session.is_null() || !(0.0..=1.0).contains(&gain) { + return -1; + } + // SAFETY: caller-guaranteed live session. + let session = unsafe { &*(session as *const Session) }; + session.shared.gain.store(gain.to_bits(), Ordering::Relaxed); + 0 + })) + .unwrap_or(-1) +} + /// Drops every queued sample, so playback resumes from whatever is written /// next: what a seek needs. Takes effect on the next process callback (or the /// 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) { #[cfg(test)] mod tests { - use super::{AtomicBool, Ordering, Ring, accept, consume}; + use super::{AtomicBool, Ordering, Ring, accept, consume, scale}; + + /// The gain is applied to the bytes the device is about to play, so silence + /// really is silence and a partial gain really is quieter -- and 1.0 must + /// leave the samples bit-identical, since that is every callback's path. + #[test] + fn gain_scales_the_samples_the_device_sees() { + let sample = + |bytes: &[u8], i: usize| f32::from_le_bytes(bytes[i..i + 4].try_into().unwrap()); + + let mut buf = Vec::new(); + for v in [1.0f32, -0.5, 0.25] { + buf.extend_from_slice(&v.to_le_bytes()); + } + + // Unity is the no-op the common case walks through. + let untouched = buf.clone(); + scale(&mut buf, 1.0); + assert_eq!(buf, untouched); + + // Half volume, sign kept. + scale(&mut buf, 0.5); + assert_eq!(sample(&buf, 0), 0.5); + assert_eq!(sample(&buf, 4), -0.25); + + // Mute is a gain of zero: every sample gone, none left ringing. + scale(&mut buf, 0.0); + assert!(buf.chunks_exact(4).all(|s| sample(s, 0) == 0.0)); + } /// The paused-seek ordering: a flush requested with no RT callbacks running /// must not let the writer queue new audio behind the pending discard. diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs index 056f2c0..00bded0 100644 --- a/crates/engine/src/ao.rs +++ b/crates/engine/src/ao.rs @@ -18,6 +18,7 @@ struct Plugin { write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize, position: unsafe extern "C" fn(*mut c_void) -> i64, set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32, + set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32, flush: unsafe extern "C" fn(*mut c_void) -> i32, close: unsafe extern "C" fn(*mut c_void), // Never dropped (lives in a static), so the fn pointers above stay valid. @@ -56,7 +57,11 @@ fn load() -> Option { position: *lib.get(b"ao_position\0").ok()?, set_active: *lib.get(b"ao_set_active\0").ok()?, // Required, so a plugin predating seek is rejected whole - // and we play muted rather than half-working. + // and we play muted rather than half-working. Volume is + // required on the same terms: the two ship from one build, + // and a mute button that does nothing is worse than a run + // with no sound at all, which at least says so. + set_volume: *lib.get(b"ao_set_volume\0").ok()?, flush: *lib.get(b"ao_flush\0").ok()?, close: *lib.get(b"ao_close\0").ok()?, _lib: lib, @@ -123,6 +128,15 @@ impl AoSession { unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 } } + /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's + /// volume and its mute are the same knob by the time they get here. The + /// clock is unaffected -- a silenced stream still plays, so the picture + /// keeps running against it. `false` for a gain outside the range. + pub fn set_volume(&self, gain: f32) -> bool { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { (self.plugin.set_volume)(self.handle, gain) == 0 } + } + /// Drops everything still queued, so the next samples written play right /// away -- what a seek needs. The played position keeps counting. pub fn flush(&self) -> bool { diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 3a3b652..d0a5aab 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -465,6 +465,25 @@ impl PlaybackSession { } } + /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0: + /// one knob, because muting and turning it down are the same thing to the + /// device, and *which* the user meant is a question only the UI can answer + /// -- it keeps the level to come back to. + /// + /// Deliberately not session state: nothing here remembers it, so a caller + /// pushes it once per session and an export -- which renders the file + /// rather than what the speakers are doing -- can never pick it up. Silent + /// with no audio device, which is also the only honest answer there. + /// + /// Mute is not pause: the samples are still consumed and the device clock + /// still runs, so the picture keeps playing against it. + pub fn set_gain(&self, gain: f32) -> bool { + match &self.audio { + Some(audio) => audio.ao.lock().unwrap().set_volume(gain), + None => false, + } + } + /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode /// workers are replaced rather than steered: a fresh channel cannot hold a /// stale frame, and it works just as well after EOF, where the old workers diff --git a/crates/engine/tests/ao_output.rs b/crates/engine/tests/ao_output.rs index 04b1c4f..8338fac 100644 --- a/crates/engine/tests/ao_output.rs +++ b/crates/engine/tests/ao_output.rs @@ -88,6 +88,51 @@ fn plays_and_tracks_position() { ); } +/// Muting is not pausing: the device keeps consuming and the master clock keeps +/// running, which is the whole reason the picture can play on through a mute. +/// That the samples really go quiet is the plugin's own `scale` unit test -- +/// nothing out here can hear the device. +#[test] +#[ignore = "needs libengine_audio.so and a PipeWire daemon"] +fn muting_silences_without_stopping_the_clock() { + assert!(AoSession::probe(), "plugin not loadable"); + let mut ao = AoSession::open(RATE, CHANNELS).expect("no PipeWire playback available"); + + let samples = tone(); + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); + let first = wait_for_playback(&ao, Duration::from_secs(2)); + + // Mute, then keep it fed: the position must move exactly as it would have. + assert!(ao.set_volume(0.0), "mute rejected"); + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); + std::thread::sleep(Duration::from_millis(300)); + let muted = ao.position().expect("position went unknown"); + let advanced = muted - first; + let expected = RATE as i64 * 300 / 1000; + eprintln!("clock advanced {advanced} samples in 300 ms while muted (expected ~{expected})"); + assert!( + (advanced - expected).abs() < expected / 5, + "the clock stalled while muted: {advanced} samples in 300 ms" + ); + + // Every level in range is taken, and the two ends are in range. + for gain in [0.0, 0.5, 1.0] { + assert!(ao.set_volume(gain), "gain {gain} rejected"); + } + // Out of range is refused at the ABI rather than multiplied into the + // speakers -- a NaN would otherwise reach the RT thread and stay there. + for gain in [-0.1, 1.5, f32::NAN, f32::INFINITY] { + assert!(!ao.set_volume(gain), "gain {gain} accepted"); + } + // ...and a refusal changes nothing: the last accepted gain still stands. + assert_eq!(ao.write(&samples), Some(samples.len()), "short write"); + std::thread::sleep(Duration::from_millis(100)); + assert!( + ao.position().expect("position went unknown") > muted, + "clock stopped after a refused gain" + ); +} + /// No reachable daemon must fail the open cleanly and quickly, never hang. #[test] #[ignore = "needs libengine_audio.so and a PipeWire daemon"]