forge
Explore
Log in

Don't you dare go Hollow

Tests never open a playback device

Browse files at this commit

429bf040acb35ce4bf9f7471f4a9332ae41cd6a8Ahmet Kaan GümüşParent: 0775641
  • fix
    • tests never open a playback device
Show full message
🐛 fix(engine): tests never open a playback device

PlaybackSession::open connected a real PipeWire stream for every
fixture — the 1 Hz pulse was the bip-bop on the speakers. VE_NO_AO=1
and cargo-test binaries under target/*/deps/ get a wall-clock silent
sink instead; VE_AO=1 still forces the ignored ao_output suite onto
the device.
crates/app/src/tests/mod.rsmodified+31 -1
@@ -65,7 +65,7 @@ use std::path::{Path, PathBuf};
6565
6666 use std::time::{Duration, Instant};
6767
68-use std::sync::{LazyLock, Mutex, MutexGuard};
68+use std::sync::{LazyLock, Mutex, MutexGuard, Once};
6969
7070 static CONFIG_ENV_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
7171
@@ -75,6 +75,19 @@ fn config_env_lock() -> MutexGuard<'static, ()> {
7575 .expect("config environment lock poisoned")
7676 }
7777
78+/// Tests never open PipeWire. The output seam also refuses a cargo-test
79+/// binary under `target/*/deps/`; this pin is the documented door and the
80+/// source-scan guard below.
81+fn pin_silent_output() {
82+ static PIN: Once = Once::new();
83+ PIN.call_once(|| {
84+ // SAFETY: this process is the test binary; no other thread has
85+ // opened a device yet because `asset()` (every session fixture)
86+ // calls this first.
87+ unsafe { std::env::set_var("VE_NO_AO", "1") };
88+ });
89+}
90+
7891 /// Every line of the window's source there is, as one string. The regions have
7992 /// moved house twice -- one `main.rs`, then `ui/`, then the tests out of it --
8093 /// and a scan that names its files passes a rule by simply not looking where
@@ -157,6 +170,7 @@ fn source_files() -> Vec<PathBuf> {
157170 }
158171
159172 fn asset(name: &str) -> PathBuf {
173+ pin_silent_output();
160174 Path::new(env!("CARGO_MANIFEST_DIR"))
161175 .join("../../assets")
162176 .join(name)
@@ -247,3 +261,19 @@ fn sub(path: &str, track: Option<u64>, label: &str) -> engine::subtitle::Subtitl
247261 refused: None,
248262 }
249263 }
264+
265+#[test]
266+fn the_suite_pins_a_silent_output() {
267+ pin_silent_output();
268+ assert!(
269+ src_text("tests/mod.rs").contains("VE_NO_AO"),
270+ "the fixture no longer pins silent output"
271+ );
272+ let session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
273+ let _ = session.set_gain(0.0);
274+ assert_eq!(
275+ engine::ao::AoSession::devices_opened(),
276+ 0,
277+ "a test opened the speakers"
278+ );
279+}
crates/engine-audio/src/lib.rsmodified+3 -0
@@ -426,6 +426,9 @@ impl Drop for Session {
426426 #[unsafe(no_mangle)]
427427 pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void {
428428 catch_unwind(AssertUnwindSafe(|| {
429+ if std::env::var_os("VE_NO_AO").is_some_and(|v| v == "1") {
430+ return std::ptr::null_mut();
431+ }
429432 if !(8_000..=768_000).contains(&sample_rate)
430433 || channels == 0
431434 || channels as usize > spa::param::audio::MAX_CHANNELS
crates/engine/src/ao.rsmodified+209 -27
@@ -4,14 +4,43 @@
44 //! only coupling is this C ABI plus a `dlopen`. Anything that goes wrong --
55 //! plugin missing, no PipeWire daemon, an unusable format -- leaves us with
66 //! `None` and the caller plays silently.
7+//!
8+//! `VE_NO_AO=1` (and cargo-test binaries under `target/*/deps/`) open a silent
9+//! sink instead: the session, the clock and the feeder stay, PipeWire is never
10+//! touched. `VE_AO=1` forces the real device, which is what the ignored
11+//! `ao_output` suite needs.
712
813 use std::ffi::c_void;
914 use std::path::Path;
10-use std::sync::OnceLock;
15+use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
16+use std::sync::{LazyLock, OnceLock};
17+use std::time::Instant;
1118
1219 use libloading::Library;
1320
1421 const LIB_NAME: &str = "libengine_audio.so";
22+static DEVICES_OPENED: AtomicU64 = AtomicU64::new(0);
23+
24+fn env_is(name: &str, value: &str) -> bool {
25+ std::env::var_os(name).is_some_and(|v| v == value)
26+}
27+
28+/// A cargo-test binary lives in `target/<profile>/deps/<name>-<hash>`. The
29+/// editor itself is `target/<profile>/edith`, which is what the harness
30+/// launches, so this never mutes a real session.
31+fn cargo_test_binary() -> bool {
32+ std::env::current_exe()
33+ .ok()
34+ .and_then(|p| p.parent().map(|d| d.ends_with("deps")))
35+ .unwrap_or(false)
36+}
37+
38+fn silent_output() -> bool {
39+ if env_is("VE_AO", "1") {
40+ return false;
41+ }
42+ env_is("VE_NO_AO", "1") || cargo_test_binary()
43+}
1544
1645 struct Plugin {
1746 open: unsafe extern "C" fn(u32, u32) -> *mut c_void,
@@ -88,21 +117,114 @@ fn load() -> Option<Plugin> {
88117
89118 /// An open playback stream. Dropping it stops playback and closes the session.
90119 pub struct AoSession {
91- plugin: &'static Plugin,
92- handle: *mut c_void,
120+ backend: Backend,
121+}
122+
123+enum Backend {
124+ Plugin {
125+ plugin: &'static Plugin,
126+ handle: *mut c_void,
127+ },
128+ /// Wall-clock paced, samples discarded. Same contract as the plugin
129+ /// (paused until `set_active`, position is samples per channel) without
130+ /// a sink-input on the user's speakers.
131+ Silent(Silent),
132+}
133+
134+struct Silent {
135+ rate: f64,
136+ /// Samples already accounted for; `-1` until the stream has run.
137+ base: AtomicI64,
138+ /// 0 = paused; otherwise milliseconds from [`epoch`] at the last resume.
139+ origin_ms: AtomicU64,
140+}
141+
142+fn epoch() -> Instant {
143+ static EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
144+ *EPOCH
145+}
146+
147+fn now_ms() -> u64 {
148+ epoch().elapsed().as_millis() as u64
149+}
150+
151+impl Silent {
152+ fn new(sample_rate: u32) -> Self {
153+ Self {
154+ rate: f64::from(sample_rate),
155+ base: AtomicI64::new(-1),
156+ origin_ms: AtomicU64::new(0),
157+ }
158+ }
159+
160+ fn extra(&self) -> i64 {
161+ match self.origin_ms.load(Ordering::Relaxed) {
162+ 0 => 0,
163+ origin => {
164+ let ms = now_ms().saturating_sub(origin) as f64;
165+ (ms / 1000.0 * self.rate).round() as i64
166+ }
167+ }
168+ }
169+
170+ fn position(&self) -> Option<i64> {
171+ let base = self.base.load(Ordering::Relaxed);
172+ let extra = self.extra();
173+ if base < 0 && self.origin_ms.load(Ordering::Relaxed) == 0 {
174+ None
175+ } else {
176+ Some(base.max(0) + extra.max(0))
177+ }
178+ }
179+
180+ fn set_active(&self, active: bool) {
181+ if active {
182+ if self.origin_ms.load(Ordering::Relaxed) == 0 {
183+ self.base
184+ .compare_exchange(-1, 0, Ordering::Relaxed, Ordering::Relaxed)
185+ .ok();
186+ self.origin_ms.store(now_ms().max(1), Ordering::Relaxed);
187+ }
188+ } else {
189+ let origin = self.origin_ms.swap(0, Ordering::Relaxed);
190+ if origin != 0 {
191+ let ms = now_ms().saturating_sub(origin) as f64;
192+ let extra = (ms / 1000.0 * self.rate).round() as i64;
193+ self.base
194+ .compare_exchange(-1, 0, Ordering::Relaxed, Ordering::Relaxed)
195+ .ok();
196+ self.base.fetch_add(extra.max(0), Ordering::Relaxed);
197+ }
198+ }
199+ }
93200 }
94201
95202 impl AoSession {
96203 /// Connects a playback stream for interleaved f32 at `sample_rate`.
97204 /// `None` covers everything: no plugin, no daemon, unusable format.
205+ /// A silent pin still returns `Some`: the timeline keeps an audio clock.
98206 pub fn open(sample_rate: u32, channels: u32) -> Option<Self> {
207+ if silent_output() {
208+ return Some(Self {
209+ backend: Backend::Silent(Silent::new(sample_rate)),
210+ });
211+ }
99212 let plugin = plugin()?;
100213 // SAFETY: plain scalars in, a session pointer or null out.
101214 let handle = unsafe { (plugin.open)(sample_rate, channels) };
102215 if handle.is_null() {
103216 return None;
104217 }
105- Some(Self { plugin, handle })
218+ DEVICES_OPENED.fetch_add(1, Ordering::Relaxed);
219+ Some(Self {
220+ backend: Backend::Plugin { plugin, handle },
221+ })
222+ }
223+
224+ /// How many times this process has opened a real PipeWire stream. The
225+ /// silent sink does not count: that is the whole point of the pin.
226+ pub fn devices_opened() -> u64 {
227+ DEVICES_OPENED.load(Ordering::Relaxed)
106228 }
107229
108230 /// Whether the plugin itself is loadable. Says nothing about the daemon --
@@ -116,20 +238,30 @@ impl AoSession {
116238 /// count means the ring is full and the caller should come back later.
117239 /// `None` once the output has died (daemon gone).
118240 pub fn write(&mut self, samples: &[f32]) -> Option<usize> {
119- // SAFETY: `handle` is live and `samples` is a valid slice for the call.
120- match unsafe { (self.plugin.write)(self.handle, samples.as_ptr(), samples.len()) } {
121- n if n < 0 => None,
122- n => Some(n as usize),
241+ match &mut self.backend {
242+ Backend::Silent(_) => Some(samples.len()),
243+ Backend::Plugin { plugin, handle } => {
244+ // SAFETY: `handle` is live and `samples` is a valid slice for the call.
245+ match unsafe { (plugin.write)(*handle, samples.as_ptr(), samples.len()) } {
246+ n if n < 0 => None,
247+ n => Some(n as usize),
248+ }
249+ }
123250 }
124251 }
125252
126253 /// Samples per channel actually played at the device -- the master clock.
127254 /// `None` until the stream has run its first cycle.
128255 pub fn position(&self) -> Option<i64> {
129- // SAFETY: `handle` came from `ao_open` and is still open.
130- match unsafe { (self.plugin.position)(self.handle) } {
131- n if n < 0 => None,
132- n => Some(n),
256+ match &self.backend {
257+ Backend::Silent(s) => s.position(),
258+ Backend::Plugin { plugin, handle } => {
259+ // SAFETY: `handle` came from `ao_open` and is still open.
260+ match unsafe { (plugin.position)(*handle) } {
261+ n if n < 0 => None,
262+ n => Some(n),
263+ }
264+ }
133265 }
134266 }
135267
@@ -137,16 +269,26 @@ impl AoSession {
137269 /// as it is, and the silence after it is not counted against a decoder that
138270 /// has already finished. Nothing at all on a plugin without the symbol.
139271 pub fn stream_ended(&self) {
140- if let Some(ended) = self.plugin.stream_ended {
141- // SAFETY: `handle` came from `ao_open` and is still open.
142- unsafe { ended(self.handle) };
272+ if let Backend::Plugin { plugin, handle } = &self.backend {
273+ if let Some(ended) = plugin.stream_ended {
274+ // SAFETY: `handle` came from `ao_open` and is still open.
275+ unsafe { ended(*handle) };
276+ }
143277 }
144278 }
145279
146280 /// Pauses or resumes playback; while paused the position stays put.
147281 pub fn set_active(&self, active: bool) -> bool {
148- // SAFETY: `handle` came from `ao_open` and is still open.
149- unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 }
282+ match &self.backend {
283+ Backend::Silent(s) => {
284+ s.set_active(active);
285+ true
286+ }
287+ Backend::Plugin { plugin, handle } => {
288+ // SAFETY: `handle` came from `ao_open` and is still open.
289+ unsafe { (plugin.set_active)(*handle, active as u32) == 0 }
290+ }
291+ }
150292 }
151293
152294 /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's
@@ -154,15 +296,28 @@ impl AoSession {
154296 /// clock is unaffected -- a silenced stream still plays, so the picture
155297 /// keeps running against it. `false` for a gain outside the range.
156298 pub fn set_volume(&self, gain: f32) -> bool {
157- // SAFETY: `handle` came from `ao_open` and is still open.
158- unsafe { (self.plugin.set_volume)(self.handle, gain) == 0 }
299+ if !(0.0..=1.0).contains(&gain) {
300+ return false;
301+ }
302+ match &self.backend {
303+ Backend::Silent(_) => true,
304+ Backend::Plugin { plugin, handle } => {
305+ // SAFETY: `handle` came from `ao_open` and is still open.
306+ unsafe { (plugin.set_volume)(*handle, gain) == 0 }
307+ }
308+ }
159309 }
160310
161311 /// Drops everything still queued, so the next samples written play right
162312 /// away -- what a seek needs. The played position keeps counting.
163313 pub fn flush(&self) -> bool {
164- // SAFETY: `handle` came from `ao_open` and is still open.
165- unsafe { (self.plugin.flush)(self.handle) == 0 }
314+ match &self.backend {
315+ Backend::Silent(_) => true,
316+ Backend::Plugin { plugin, handle } => {
317+ // SAFETY: `handle` came from `ao_open` and is still open.
318+ unsafe { (plugin.flush)(*handle) == 0 }
319+ }
320+ }
166321 }
167322
168323 /// Starved callbacks so far, and the device position (samples per channel)
@@ -170,20 +325,47 @@ impl AoSession {
170325 /// dry. Two atomic loads inside the plugin, so it is cheap enough to poll
171326 /// and it never touches the RT thread's path.
172327 pub fn underruns(&self) -> (u64, Option<i64>) {
173- let mut last = -1i64;
174- // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours.
175- let count = unsafe { (self.plugin.underruns)(self.handle, &raw mut last) };
176- (count.max(0) as u64, (last >= 0).then_some(last))
328+ match &self.backend {
329+ Backend::Silent(_) => (0, None),
330+ Backend::Plugin { plugin, handle } => {
331+ let mut last = -1i64;
332+ // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours.
333+ let count = unsafe { (plugin.underruns)(*handle, &raw mut last) };
334+ (count.max(0) as u64, (last >= 0).then_some(last))
335+ }
336+ }
177337 }
178338 }
179339
180340 impl Drop for AoSession {
181341 fn drop(&mut self) {
182- // SAFETY: `handle` came from `ao_open` and is closed exactly once.
183- unsafe { (self.plugin.close)(self.handle) }
342+ if let Backend::Plugin { plugin, handle } = &self.backend {
343+ // SAFETY: `handle` came from `ao_open` and is closed exactly once.
344+ unsafe { (plugin.close)(*handle) }
345+ }
184346 }
185347 }
186348
187349 // The session is used from one thread at a time (the audio feeder) and never
188350 // shared; the PipeWire state behind it is not `Sync`.
189351 unsafe impl Send for AoSession {}
352+
353+#[cfg(test)]
354+mod tests {
355+ use super::AoSession;
356+
357+ #[test]
358+ fn a_silent_pin_never_opens_a_device() {
359+ // SAFETY: this is the engine's own unit-test process.
360+ unsafe { std::env::set_var("VE_NO_AO", "1") };
361+ let mut ao = AoSession::open(48_000, 2).expect("silent opens");
362+ assert_eq!(AoSession::devices_opened(), 0);
363+ assert!(ao.set_volume(0.0));
364+ assert!(!ao.set_volume(1.5));
365+ assert!(ao.set_active(true));
366+ assert_eq!(ao.write(&[0.0; 64]), Some(64));
367+ assert!(ao.flush());
368+ ao.stream_ended();
369+ assert_eq!(ao.underruns(), (0, None));
370+ }
371+}
crates/engine/tests/ao_output.rsmodified+9 -0
@@ -40,11 +40,18 @@ fn tone() -> Vec<f32> {
4040 /// bytes alone) and a person with the app open. The upgrade path is recording
4141 /// a null sink and asserting on the samples that come back.
4242 fn open_silent() -> AoSession {
43+ want_real_device();
4344 let ao = AoSession::open(RATE, CHANNELS).expect("no PipeWire playback available");
4445 assert!(ao.set_volume(0.0), "mute rejected");
4546 ao
4647 }
4748
49+fn want_real_device() {
50+ // SAFETY: this ignored suite is --test-threads=1 and is the one
51+ // process that is allowed a real sink.
52+ unsafe { std::env::set_var("VE_AO", "1") };
53+}
54+
4855 /// Waits up to `limit` for the clock to report a played position past zero.
4956 fn wait_for_playback(ao: &AoSession, limit: Duration) -> i64 {
5057 let start = Instant::now();
@@ -160,11 +167,13 @@ fn muting_silences_without_stopping_the_clock() {
160167 #[test]
161168 #[ignore = "needs libengine_audio.so and a PipeWire daemon"]
162169 fn no_daemon_opens_nothing() {
170+ want_real_device();
163171 assert!(AoSession::probe(), "plugin not loadable");
164172 // SAFETY: the suite is documented to run with --test-threads=1.
165173 unsafe { std::env::set_var("PIPEWIRE_REMOTE", "/nonexistent") };
166174 let start = Instant::now();
167175 let session = AoSession::open(RATE, CHANNELS);
176+
168177 let elapsed = start.elapsed();
169178 unsafe { std::env::remove_var("PIPEWIRE_REMOTE") };
170179