From 429bf040acb35ce4bf9f7471f4a9332ae41cd6a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 10 Sep 2026 03:05:12 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20fix(engine):=20tests=20never=20o?= =?UTF-8?q?pen=20a=20playback=20device?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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.rs | 32 ++++- crates/engine-audio/src/lib.rs | 3 + crates/engine/src/ao.rs | 236 +++++++++++++++++++++++++++---- crates/engine/tests/ao_output.rs | 9 ++ 4 files changed, 252 insertions(+), 28 deletions(-) diff --git a/crates/app/src/tests/mod.rs b/crates/app/src/tests/mod.rs index 669eea7..098c271 100644 --- a/crates/app/src/tests/mod.rs +++ b/crates/app/src/tests/mod.rs @@ -65,7 +65,7 @@ use std::path::{Path, PathBuf}; use std::time::{Duration, Instant}; -use std::sync::{LazyLock, Mutex, MutexGuard}; +use std::sync::{LazyLock, Mutex, MutexGuard, Once}; static CONFIG_ENV_LOCK: LazyLock> = LazyLock::new(|| Mutex::new(())); @@ -75,6 +75,19 @@ fn config_env_lock() -> MutexGuard<'static, ()> { .expect("config environment lock poisoned") } +/// Tests never open PipeWire. The output seam also refuses a cargo-test +/// binary under `target/*/deps/`; this pin is the documented door and the +/// source-scan guard below. +fn pin_silent_output() { + static PIN: Once = Once::new(); + PIN.call_once(|| { + // SAFETY: this process is the test binary; no other thread has + // opened a device yet because `asset()` (every session fixture) + // calls this first. + unsafe { std::env::set_var("VE_NO_AO", "1") }; + }); +} + /// Every line of the window's source there is, as one string. The regions have /// moved house twice -- one `main.rs`, then `ui/`, then the tests out of it -- /// and a scan that names its files passes a rule by simply not looking where @@ -157,6 +170,7 @@ fn source_files() -> Vec { } fn asset(name: &str) -> PathBuf { + pin_silent_output(); Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../assets") .join(name) @@ -247,3 +261,19 @@ fn sub(path: &str, track: Option, label: &str) -> engine::subtitle::Subtitl refused: None, } } + +#[test] +fn the_suite_pins_a_silent_output() { + pin_silent_output(); + assert!( + src_text("tests/mod.rs").contains("VE_NO_AO"), + "the fixture no longer pins silent output" + ); + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + let _ = session.set_gain(0.0); + assert_eq!( + engine::ao::AoSession::devices_opened(), + 0, + "a test opened the speakers" + ); +} diff --git a/crates/engine-audio/src/lib.rs b/crates/engine-audio/src/lib.rs index fd2e066..c492f54 100644 --- a/crates/engine-audio/src/lib.rs +++ b/crates/engine-audio/src/lib.rs @@ -426,6 +426,9 @@ impl Drop for Session { #[unsafe(no_mangle)] pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void { catch_unwind(AssertUnwindSafe(|| { + if std::env::var_os("VE_NO_AO").is_some_and(|v| v == "1") { + return std::ptr::null_mut(); + } if !(8_000..=768_000).contains(&sample_rate) || channels == 0 || channels as usize > spa::param::audio::MAX_CHANNELS diff --git a/crates/engine/src/ao.rs b/crates/engine/src/ao.rs index 31e7645..eb7ba7a 100644 --- a/crates/engine/src/ao.rs +++ b/crates/engine/src/ao.rs @@ -4,14 +4,43 @@ //! only coupling is this C ABI plus a `dlopen`. Anything that goes wrong -- //! plugin missing, no PipeWire daemon, an unusable format -- leaves us with //! `None` and the caller plays silently. +//! +//! `VE_NO_AO=1` (and cargo-test binaries under `target/*/deps/`) open a silent +//! sink instead: the session, the clock and the feeder stay, PipeWire is never +//! touched. `VE_AO=1` forces the real device, which is what the ignored +//! `ao_output` suite needs. use std::ffi::c_void; use std::path::Path; -use std::sync::OnceLock; +use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; +use std::sync::{LazyLock, OnceLock}; +use std::time::Instant; use libloading::Library; const LIB_NAME: &str = "libengine_audio.so"; +static DEVICES_OPENED: AtomicU64 = AtomicU64::new(0); + +fn env_is(name: &str, value: &str) -> bool { + std::env::var_os(name).is_some_and(|v| v == value) +} + +/// A cargo-test binary lives in `target//deps/-`. The +/// editor itself is `target//edith`, which is what the harness +/// launches, so this never mutes a real session. +fn cargo_test_binary() -> bool { + std::env::current_exe() + .ok() + .and_then(|p| p.parent().map(|d| d.ends_with("deps"))) + .unwrap_or(false) +} + +fn silent_output() -> bool { + if env_is("VE_AO", "1") { + return false; + } + env_is("VE_NO_AO", "1") || cargo_test_binary() +} struct Plugin { open: unsafe extern "C" fn(u32, u32) -> *mut c_void, @@ -88,21 +117,114 @@ fn load() -> Option { /// An open playback stream. Dropping it stops playback and closes the session. pub struct AoSession { - plugin: &'static Plugin, - handle: *mut c_void, + backend: Backend, +} + +enum Backend { + Plugin { + plugin: &'static Plugin, + handle: *mut c_void, + }, + /// Wall-clock paced, samples discarded. Same contract as the plugin + /// (paused until `set_active`, position is samples per channel) without + /// a sink-input on the user's speakers. + Silent(Silent), +} + +struct Silent { + rate: f64, + /// Samples already accounted for; `-1` until the stream has run. + base: AtomicI64, + /// 0 = paused; otherwise milliseconds from [`epoch`] at the last resume. + origin_ms: AtomicU64, +} + +fn epoch() -> Instant { + static EPOCH: LazyLock = LazyLock::new(Instant::now); + *EPOCH +} + +fn now_ms() -> u64 { + epoch().elapsed().as_millis() as u64 +} + +impl Silent { + fn new(sample_rate: u32) -> Self { + Self { + rate: f64::from(sample_rate), + base: AtomicI64::new(-1), + origin_ms: AtomicU64::new(0), + } + } + + fn extra(&self) -> i64 { + match self.origin_ms.load(Ordering::Relaxed) { + 0 => 0, + origin => { + let ms = now_ms().saturating_sub(origin) as f64; + (ms / 1000.0 * self.rate).round() as i64 + } + } + } + + fn position(&self) -> Option { + let base = self.base.load(Ordering::Relaxed); + let extra = self.extra(); + if base < 0 && self.origin_ms.load(Ordering::Relaxed) == 0 { + None + } else { + Some(base.max(0) + extra.max(0)) + } + } + + fn set_active(&self, active: bool) { + if active { + if self.origin_ms.load(Ordering::Relaxed) == 0 { + self.base + .compare_exchange(-1, 0, Ordering::Relaxed, Ordering::Relaxed) + .ok(); + self.origin_ms.store(now_ms().max(1), Ordering::Relaxed); + } + } else { + let origin = self.origin_ms.swap(0, Ordering::Relaxed); + if origin != 0 { + let ms = now_ms().saturating_sub(origin) as f64; + let extra = (ms / 1000.0 * self.rate).round() as i64; + self.base + .compare_exchange(-1, 0, Ordering::Relaxed, Ordering::Relaxed) + .ok(); + self.base.fetch_add(extra.max(0), Ordering::Relaxed); + } + } + } } impl AoSession { /// Connects a playback stream for interleaved f32 at `sample_rate`. /// `None` covers everything: no plugin, no daemon, unusable format. + /// A silent pin still returns `Some`: the timeline keeps an audio clock. pub fn open(sample_rate: u32, channels: u32) -> Option { + if silent_output() { + return Some(Self { + backend: Backend::Silent(Silent::new(sample_rate)), + }); + } let plugin = plugin()?; // SAFETY: plain scalars in, a session pointer or null out. let handle = unsafe { (plugin.open)(sample_rate, channels) }; if handle.is_null() { return None; } - Some(Self { plugin, handle }) + DEVICES_OPENED.fetch_add(1, Ordering::Relaxed); + Some(Self { + backend: Backend::Plugin { plugin, handle }, + }) + } + + /// How many times this process has opened a real PipeWire stream. The + /// silent sink does not count: that is the whole point of the pin. + pub fn devices_opened() -> u64 { + DEVICES_OPENED.load(Ordering::Relaxed) } /// Whether the plugin itself is loadable. Says nothing about the daemon -- @@ -116,20 +238,30 @@ impl AoSession { /// count means the ring is full and the caller should come back later. /// `None` once the output has died (daemon gone). pub fn write(&mut self, samples: &[f32]) -> Option { - // SAFETY: `handle` is live and `samples` is a valid slice for the call. - match unsafe { (self.plugin.write)(self.handle, samples.as_ptr(), samples.len()) } { - n if n < 0 => None, - n => Some(n as usize), + match &mut self.backend { + Backend::Silent(_) => Some(samples.len()), + Backend::Plugin { plugin, handle } => { + // SAFETY: `handle` is live and `samples` is a valid slice for the call. + match unsafe { (plugin.write)(*handle, samples.as_ptr(), samples.len()) } { + n if n < 0 => None, + n => Some(n as usize), + } + } } } /// Samples per channel actually played at the device -- the master clock. /// `None` until the stream has run its first cycle. pub fn position(&self) -> Option { - // SAFETY: `handle` came from `ao_open` and is still open. - match unsafe { (self.plugin.position)(self.handle) } { - n if n < 0 => None, - n => Some(n), + match &self.backend { + Backend::Silent(s) => s.position(), + Backend::Plugin { plugin, handle } => { + // SAFETY: `handle` came from `ao_open` and is still open. + match unsafe { (plugin.position)(*handle) } { + n if n < 0 => None, + n => Some(n), + } + } } } @@ -137,16 +269,26 @@ impl AoSession { /// as it is, and the silence after it is not counted against a decoder that /// has already finished. Nothing at all on a plugin without the symbol. pub fn stream_ended(&self) { - if let Some(ended) = self.plugin.stream_ended { - // SAFETY: `handle` came from `ao_open` and is still open. - unsafe { ended(self.handle) }; + if let Backend::Plugin { plugin, handle } = &self.backend { + if let Some(ended) = plugin.stream_ended { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { ended(*handle) }; + } } } /// Pauses or resumes playback; while paused the position stays put. pub fn set_active(&self, active: bool) -> bool { - // SAFETY: `handle` came from `ao_open` and is still open. - unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 } + match &self.backend { + Backend::Silent(s) => { + s.set_active(active); + true + } + Backend::Plugin { plugin, handle } => { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { (plugin.set_active)(*handle, active as u32) == 0 } + } + } } /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's @@ -154,15 +296,28 @@ impl AoSession { /// 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 } + if !(0.0..=1.0).contains(&gain) { + return false; + } + match &self.backend { + Backend::Silent(_) => true, + Backend::Plugin { plugin, handle } => { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { (plugin.set_volume)(*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 { - // SAFETY: `handle` came from `ao_open` and is still open. - unsafe { (self.plugin.flush)(self.handle) == 0 } + match &self.backend { + Backend::Silent(_) => true, + Backend::Plugin { plugin, handle } => { + // SAFETY: `handle` came from `ao_open` and is still open. + unsafe { (plugin.flush)(*handle) == 0 } + } + } } /// Starved callbacks so far, and the device position (samples per channel) @@ -170,20 +325,47 @@ impl AoSession { /// dry. Two atomic loads inside the plugin, so it is cheap enough to poll /// and it never touches the RT thread's path. pub fn underruns(&self) -> (u64, Option) { - let mut last = -1i64; - // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours. - let count = unsafe { (self.plugin.underruns)(self.handle, &raw mut last) }; - (count.max(0) as u64, (last >= 0).then_some(last)) + match &self.backend { + Backend::Silent(_) => (0, None), + Backend::Plugin { plugin, handle } => { + let mut last = -1i64; + // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours. + let count = unsafe { (plugin.underruns)(*handle, &raw mut last) }; + (count.max(0) as u64, (last >= 0).then_some(last)) + } + } } } impl Drop for AoSession { fn drop(&mut self) { - // SAFETY: `handle` came from `ao_open` and is closed exactly once. - unsafe { (self.plugin.close)(self.handle) } + if let Backend::Plugin { plugin, handle } = &self.backend { + // SAFETY: `handle` came from `ao_open` and is closed exactly once. + unsafe { (plugin.close)(*handle) } + } } } // The session is used from one thread at a time (the audio feeder) and never // shared; the PipeWire state behind it is not `Sync`. unsafe impl Send for AoSession {} + +#[cfg(test)] +mod tests { + use super::AoSession; + + #[test] + fn a_silent_pin_never_opens_a_device() { + // SAFETY: this is the engine's own unit-test process. + unsafe { std::env::set_var("VE_NO_AO", "1") }; + let mut ao = AoSession::open(48_000, 2).expect("silent opens"); + assert_eq!(AoSession::devices_opened(), 0); + assert!(ao.set_volume(0.0)); + assert!(!ao.set_volume(1.5)); + assert!(ao.set_active(true)); + assert_eq!(ao.write(&[0.0; 64]), Some(64)); + assert!(ao.flush()); + ao.stream_ended(); + assert_eq!(ao.underruns(), (0, None)); + } +} diff --git a/crates/engine/tests/ao_output.rs b/crates/engine/tests/ao_output.rs index 42cb4f7..c97932c 100644 --- a/crates/engine/tests/ao_output.rs +++ b/crates/engine/tests/ao_output.rs @@ -40,11 +40,18 @@ fn tone() -> Vec { /// bytes alone) and a person with the app open. The upgrade path is recording /// a null sink and asserting on the samples that come back. fn open_silent() -> AoSession { + want_real_device(); let ao = AoSession::open(RATE, CHANNELS).expect("no PipeWire playback available"); assert!(ao.set_volume(0.0), "mute rejected"); ao } +fn want_real_device() { + // SAFETY: this ignored suite is --test-threads=1 and is the one + // process that is allowed a real sink. + unsafe { std::env::set_var("VE_AO", "1") }; +} + /// Waits up to `limit` for the clock to report a played position past zero. fn wait_for_playback(ao: &AoSession, limit: Duration) -> i64 { let start = Instant::now(); @@ -160,11 +167,13 @@ fn muting_silences_without_stopping_the_clock() { #[test] #[ignore = "needs libengine_audio.so and a PipeWire daemon"] fn no_daemon_opens_nothing() { + want_real_device(); assert!(AoSession::probe(), "plugin not loadable"); // SAFETY: the suite is documented to run with --test-threads=1. unsafe { std::env::set_var("PIPEWIRE_REMOTE", "/nonexistent") }; let start = Instant::now(); let session = AoSession::open(RATE, CHANNELS); + let elapsed = start.elapsed(); unsafe { std::env::remove_var("PIPEWIRE_REMOTE") };