forge
Explore
Log in

Don't you dare go Hollow

A gain that survives the device being replaced

Browse files at this commit

2734028c895b539733cde3e0026d91b26808ffa4Ahmet Kaan GümüşParent: 0c9d76c
  • fix
    • a gain that survives the device being replaced
Show full message
fix(audio): a gain that survives the device being replaced

The monitoring gain was written straight at the device and remembered
nowhere, so every replacement of that device came up at 1.0 -- and a
session playing muted whose output died (a PipeWire restart, a sink
unplugged) came back at full volume with the toolbar still reading
"muted". Compare `content_at`, which is reset at the same door with a
comment about the stream that died: the clock anchor has an owner, the
level did not.

* `ao_gain` (engine-audio): the symmetric read-back of `ao_set_volume`,
  off the same `Shared::gain` the RT callback multiplies by, so a caller
  can ask the device rather than remember what it asked for.
* `AoSession::gain`: that read-back, and the Silent sink now keeps the
  gain it was given (`ao.rs`'s pin answered `true` to every gain, which
  made the sink unable to witness any of this). The plugin symbol is
  optional, like `ao_stream_ended`: an older plugin still plays, it just
  cannot be asked.
* `Audio::gain`: the session's own copy, written only by `set_gain` and
  only after the device has taken the number, so it cannot drift.
* `rearm_audio` and `arm_audio` put it back onto the fresh stream.

Witness: `a_rearmed_output_comes_back_at_the_level_the_session_was_running`
reads the level back out of the device before and after a re-arm driven
the way the sibling re-arm test drives it (dead flag, cooldown spent,
play + seek), with the death flag clearing as the control that a new
device really was installed. Reverting the one `ao.set_volume` line in
`rearm_audio` fails it: `left: Some(1.0), right: Some(0.0)`.

No audibility is claimed anywhere in this change: what is witnessed is
state, read back out of the device.
crates/engine-audio/src/lib.rsmodified+25 -1
@@ -626,6 +626,27 @@ pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 {
626626 .unwrap_or(-1)
627627 }
628628
629+/// Reads back the gain [`ao_set_volume`] last set: what the stream is actually
630+/// multiplying by, which is not the same question as what a caller last asked
631+/// for once the device has been replaced (a re-armed stream comes up at 1.0).
632+/// -1.0 for a session that cannot answer -- never a real gain, which is 0.0 to
633+/// 1.0.
634+///
635+/// # Safety
636+/// `session` must come from [`ao_open`].
637+#[unsafe(no_mangle)]
638+pub unsafe extern "C" fn ao_gain(session: *mut c_void) -> f32 {
639+ catch_unwind(AssertUnwindSafe(|| {
640+ if session.is_null() {
641+ return -1.0;
642+ }
643+ // SAFETY: caller-guaranteed live session.
644+ let session = unsafe { &*(session as *const Session) };
645+ f32::from_bits(session.shared.gain.load(Ordering::Relaxed))
646+ }))
647+ .unwrap_or(-1.0)
648+}
649+
629650 /// Drops every queued sample, so playback resumes from whatever is written
630651 /// next: what a seek needs. Takes effect on the next process callback (or the
631652 /// first one after a resume), and leaves the played position alone -- the
@@ -751,7 +772,10 @@ mod tests {
751772 flush.store(true, Ordering::Release);
752773 let mut out = [0u8; 16];
753774 assert_eq!(consume(&flush, &ring, &mut out, 2), 0, "the flush landed");
754- assert!(!primed.load(Ordering::Acquire), "the restart counts as late");
775+ assert!(
776+ !primed.load(Ordering::Acquire),
777+ "the restart counts as late"
778+ );
755779
756780 // ...until its own first sample lands, from where it counts again --
757781 // which is also what makes the tail work: `ao_stream_ended` unprimes
crates/engine/src/ao.rsmodified+44 -2
@@ -12,7 +12,7 @@
1212
1313 use std::ffi::c_void;
1414 use std::path::Path;
15-use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
15+use std::sync::atomic::{AtomicI64, AtomicU32, AtomicU64, Ordering};
1616 use std::sync::{LazyLock, OnceLock};
1717 use std::time::Instant;
1818
@@ -54,6 +54,11 @@ struct Plugin {
5454 /// did and only counts the tail of a played-out stream as lateness, which
5555 /// is a worse diagnostic rather than a worse session.
5656 stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>,
57+ /// Optional, unlike its neighbours: without it a session plays and is
58+ /// silenced exactly as before, it just cannot be *asked* what gain it is
59+ /// running -- and asking is the only way to see that a device replaced
60+ /// under it came back at the wrong level.
61+ gain: Option<unsafe extern "C" fn(*mut c_void) -> f32>,
5762 close: unsafe extern "C" fn(*mut c_void),
5863 // Never dropped (lives in a static), so the fn pointers above stay valid.
5964 _lib: Library,
@@ -102,6 +107,7 @@ fn load() -> Option<Plugin> {
102107 // reads zero underruns is worse than a run that says the
103108 // plugin is the wrong one.
104109 underruns: *lib.get(b"ao_underruns\0").ok()?,
110+ gain: lib.get(b"ao_gain\0").ok().map(|f| *f),
105111 stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f),
106112 close: *lib.get(b"ao_close\0").ok()?,
107113 _lib: lib,
@@ -137,6 +143,11 @@ struct Silent {
137143 base: AtomicI64,
138144 /// 0 = paused; otherwise milliseconds from [`epoch`] at the last resume.
139145 origin_ms: AtomicU64,
146+ /// The gain last pushed, so the silent sink answers the same question the
147+ /// plugin does: what is this stream actually multiplying by. Without it
148+ /// every gain read back as a shrug, and a device that had been re-armed at
149+ /// full volume looked exactly like one that had kept its level.
150+ gain: AtomicU32,
140151 }
141152
142153 fn epoch() -> Instant {
@@ -154,9 +165,18 @@ impl Silent {
154165 rate: f64::from(sample_rate),
155166 base: AtomicI64::new(-1),
156167 origin_ms: AtomicU64::new(0),
168+ gain: AtomicU32::new(1.0f32.to_bits()),
157169 }
158170 }
159171
172+ fn gain(&self) -> f32 {
173+ f32::from_bits(self.gain.load(Ordering::Relaxed))
174+ }
175+
176+ fn set_gain(&self, gain: f32) {
177+ self.gain.store(gain.to_bits(), Ordering::Relaxed);
178+ }
179+
160180 fn extra(&self) -> i64 {
161181 match self.origin_ms.load(Ordering::Relaxed) {
162182 0 => 0,
@@ -308,7 +328,10 @@ impl AoSession {
308328 return false;
309329 }
310330 match &self.backend {
311- Backend::Silent(_) => true,
331+ Backend::Silent(s) => {
332+ s.set_gain(gain);
333+ true
334+ }
312335 Backend::Plugin { plugin, handle } => {
313336 // SAFETY: `handle` came from `ao_open` and is still open.
314337 unsafe { (plugin.set_volume)(*handle, gain) == 0 }
@@ -316,6 +339,25 @@ impl AoSession {
316339 }
317340 }
318341
342+ /// The gain this stream is actually running at, read back from the device
343+ /// rather than remembered by the caller: the two come apart the moment the
344+ /// device object is replaced (a fresh stream comes up at 1.0), and a
345+ /// remembered answer would report the level that was asked for rather than
346+ /// the one in force. `None` with no device, or a plugin too old to answer.
347+ pub fn gain(&self) -> Option<f32> {
348+ match &self.backend {
349+ Backend::Silent(s) => Some(s.gain()),
350+ Backend::Plugin { plugin, handle } => {
351+ let read = plugin.gain?;
352+ // SAFETY: `handle` came from `ao_open` and is still open.
353+ match unsafe { read(*handle) } {
354+ gain if gain < 0.0 => None,
355+ gain => Some(gain),
356+ }
357+ }
358+ }
359+ }
360+
319361 /// Drops everything still queued, so the next samples written play right
320362 /// away -- what a seek needs. The played position keeps counting.
321363 pub fn flush(&self) -> bool {