forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

ao.rs402 lines, 15.1 KiBHistoryRawDownload
1//! Runtime-optional audio output plugin (`libengine_audio.so`).
2//!
3//! The plugin links libpipewire; this crate and the app binary must not, so the
4//! only coupling is this C ABI plus a `dlopen`. Anything that goes wrong --
5//! plugin missing, no PipeWire daemon, an unusable format -- leaves us with
6//! `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.
12
13use std::ffi::c_void;
14use std::path::Path;
15use std::sync::atomic::{AtomicI64, AtomicU64, Ordering};
16use std::sync::{LazyLock, OnceLock};
17use std::time::Instant;
18
19use libloading::Library;
20
21const LIB_NAME: &str = "libengine_audio.so";
22static DEVICES_OPENED: AtomicU64 = AtomicU64::new(0);
23
24fn 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.
31fn 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
38fn 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}
44
45struct Plugin {
46 open: unsafe extern "C" fn(u32, u32) -> *mut c_void,
47 write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize,
48 position: unsafe extern "C" fn(*mut c_void) -> i64,
49 set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32,
50 set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32,
51 flush: unsafe extern "C" fn(*mut c_void) -> i32,
52 underruns: unsafe extern "C" fn(*mut c_void, *mut i64) -> i64,
53 /// Optional, unlike its neighbours: without it a plugin plays exactly as it
54 /// did and only counts the tail of a played-out stream as lateness, which
55 /// is a worse diagnostic rather than a worse session.
56 stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>,
57 close: unsafe extern "C" fn(*mut c_void),
58 // Never dropped (lives in a static), so the fn pointers above stay valid.
59 _lib: Library,
60}
61
62fn plugin() -> Option<&'static Plugin> {
63 static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new();
64 PLUGIN.get_or_init(load).as_ref()
65}
66
67fn load() -> Option<Plugin> {
68 // Next to the executable first (cargo puts both in target/<profile>), then
69 // whatever the dynamic linker's search path turns up.
70 let beside_exe = std::env::current_exe()
71 .ok()
72 .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)));
73 let candidates = beside_exe
74 .as_deref()
75 .into_iter()
76 .chain(std::iter::once(Path::new(LIB_NAME)));
77
78 for candidate in candidates {
79 // SAFETY: loading a shared object runs its initialisers; we only ever
80 // name our own plugin, and every symbol below is type-checked against
81 // the signatures this crate shares with it.
82 let lib = match unsafe { Library::new(candidate) } {
83 Ok(lib) => lib,
84 Err(_) => continue,
85 };
86 let plugin = unsafe {
87 (|| {
88 Some(Plugin {
89 open: *lib.get(b"ao_open\0").ok()?,
90 write: *lib.get(b"ao_write\0").ok()?,
91 position: *lib.get(b"ao_position\0").ok()?,
92 set_active: *lib.get(b"ao_set_active\0").ok()?,
93 // Required, so a plugin predating seek is rejected whole
94 // and we play muted rather than half-working. Volume is
95 // required on the same terms: the two ship from one build,
96 // and a mute button that does nothing is worse than a run
97 // with no sound at all, which at least says so.
98 set_volume: *lib.get(b"ao_set_volume\0").ok()?,
99 flush: *lib.get(b"ao_flush\0").ok()?,
100 // Required on the same terms as the two above: the plugin
101 // ships from this build, and a measurement that silently
102 // reads zero underruns is worse than a run that says the
103 // plugin is the wrong one.
104 underruns: *lib.get(b"ao_underruns\0").ok()?,
105 stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f),
106 close: *lib.get(b"ao_close\0").ok()?,
107 _lib: lib,
108 })
109 })()
110 };
111 if plugin.is_some() {
112 return plugin;
113 }
114 }
115 None
116}
117
118/// An open playback stream. Dropping it stops playback and closes the session.
119pub struct AoSession {
120 backend: Backend,
121}
122
123enum 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
134struct 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
142fn epoch() -> Instant {
143 static EPOCH: LazyLock<Instant> = LazyLock::new(Instant::now);
144 *EPOCH
145}
146
147fn now_ms() -> u64 {
148 epoch().elapsed().as_millis() as u64
149}
150
151impl 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 }
200}
201
202impl AoSession {
203 /// Connects a playback stream for interleaved f32 at `sample_rate`.
204 /// `None` covers everything: no plugin, no daemon, unusable format.
205 /// A silent pin still returns `Some`: the timeline keeps an audio clock.
206 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 }
212 let plugin = plugin()?;
213 // SAFETY: plain scalars in, a session pointer or null out.
214 let handle = unsafe { (plugin.open)(sample_rate, channels) };
215 if handle.is_null() {
216 return None;
217 }
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)
228 }
229
230 /// Whether this session is the silent sink rather than a real stream --
231 /// what the `VE_NO_AO` pin buys, and the one form of that claim a caller can
232 /// own: [`AoSession::devices_opened`] is process-wide and moves under any
233 /// other session this process opens.
234 pub fn is_silent(&self) -> bool {
235 matches!(self.backend, Backend::Silent(_))
236 }
237
238 /// Whether the plugin itself is loadable. Says nothing about the daemon --
239 /// only [`AoSession::open`] answers that, and it is cheap enough to be the
240 /// real probe.
241 pub fn probe() -> bool {
242 plugin().is_some()
243 }
244
245 /// Queues interleaved samples, returning how many were accepted; a short
246 /// count means the ring is full and the caller should come back later.
247 /// `None` once the output has died (daemon gone).
248 pub fn write(&mut self, samples: &[f32]) -> Option<usize> {
249 match &mut self.backend {
250 Backend::Silent(_) => Some(samples.len()),
251 Backend::Plugin { plugin, handle } => {
252 // SAFETY: `handle` is live and `samples` is a valid slice for the call.
253 match unsafe { (plugin.write)(*handle, samples.as_ptr(), samples.len()) } {
254 n if n < 0 => None,
255 n => Some(n as usize),
256 }
257 }
258 }
259 }
260
261 /// Samples per channel actually played at the device -- the master clock.
262 /// `None` until the stream has run its first cycle.
263 pub fn position(&self) -> Option<i64> {
264 match &self.backend {
265 Backend::Silent(s) => s.position(),
266 Backend::Plugin { plugin, handle } => {
267 // SAFETY: `handle` came from `ao_open` and is still open.
268 match unsafe { (plugin.position)(*handle) } {
269 n if n < 0 => None,
270 n => Some(n),
271 }
272 }
273 }
274 }
275
276 /// Says the last sample of this stream has been queued: the ring plays out
277 /// as it is, and the silence after it is not counted against a decoder that
278 /// has already finished. Nothing at all on a plugin without the symbol.
279 pub fn stream_ended(&self) {
280 if let Backend::Plugin { plugin, handle } = &self.backend {
281 if let Some(ended) = plugin.stream_ended {
282 // SAFETY: `handle` came from `ao_open` and is still open.
283 unsafe { ended(*handle) };
284 }
285 }
286 }
287
288 /// Pauses or resumes playback; while paused the position stays put.
289 pub fn set_active(&self, active: bool) -> bool {
290 match &self.backend {
291 Backend::Silent(s) => {
292 s.set_active(active);
293 true
294 }
295 Backend::Plugin { plugin, handle } => {
296 // SAFETY: `handle` came from `ao_open` and is still open.
297 unsafe { (plugin.set_active)(*handle, active as u32) == 0 }
298 }
299 }
300 }
301
302 /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's
303 /// volume and its mute are the same knob by the time they get here. The
304 /// clock is unaffected -- a silenced stream still plays, so the picture
305 /// keeps running against it. `false` for a gain outside the range.
306 pub fn set_volume(&self, gain: f32) -> bool {
307 if !(0.0..=1.0).contains(&gain) {
308 return false;
309 }
310 match &self.backend {
311 Backend::Silent(_) => true,
312 Backend::Plugin { plugin, handle } => {
313 // SAFETY: `handle` came from `ao_open` and is still open.
314 unsafe { (plugin.set_volume)(*handle, gain) == 0 }
315 }
316 }
317 }
318
319 /// Drops everything still queued, so the next samples written play right
320 /// away -- what a seek needs. The played position keeps counting.
321 pub fn flush(&self) -> bool {
322 match &self.backend {
323 Backend::Silent(_) => true,
324 Backend::Plugin { plugin, handle } => {
325 // SAFETY: `handle` came from `ao_open` and is still open.
326 unsafe { (plugin.flush)(*handle) == 0 }
327 }
328 }
329 }
330
331 /// Starved callbacks so far, and the device position (samples per channel)
332 /// the last of them was seen at -- `None` for a stream that has never run
333 /// dry. Two atomic loads inside the plugin, so it is cheap enough to poll
334 /// and it never touches the RT thread's path.
335 pub fn underruns(&self) -> (u64, Option<i64>) {
336 match &self.backend {
337 Backend::Silent(_) => (0, None),
338 Backend::Plugin { plugin, handle } => {
339 let mut last = -1i64;
340 // SAFETY: `handle` came from `ao_open`, and `last` is a live i64 of ours.
341 let count = unsafe { (plugin.underruns)(*handle, &raw mut last) };
342 (count.max(0) as u64, (last >= 0).then_some(last))
343 }
344 }
345 }
346}
347
348impl Drop for AoSession {
349 fn drop(&mut self) {
350 if let Backend::Plugin { plugin, handle } = &self.backend {
351 // SAFETY: `handle` came from `ao_open` and is closed exactly once.
352 unsafe { (plugin.close)(*handle) }
353 }
354 }
355}
356
357// The session is used from one thread at a time (the audio feeder) and never
358// shared; the PipeWire state behind it is not `Sync`.
359unsafe impl Send for AoSession {}
360
361#[cfg(test)]
362mod tests {
363 use super::AoSession;
364
365 /// This module's counter assertions, one test at a time: the counters are
366 /// process-wide, so two of these tests measuring at once would see each
367 /// other's opens. Same shape as `waveform::counters_serial`, and for the
368 /// same reason -- the counters stay readable, and one at a time is the
369 /// whole point.
370 fn counters_serial() -> std::sync::MutexGuard<'static, ()> {
371 static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
372 LOCK.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
373 }
374
375 #[test]
376 fn a_silent_pin_never_opens_a_device() {
377 let _serial = counters_serial();
378 // SAFETY: this is the engine's own unit-test process.
379 unsafe { std::env::set_var("VE_NO_AO", "1") };
380 let before = AoSession::devices_opened();
381 let mut ao = AoSession::open(48_000, 2).expect("silent opens");
382 // The pin's effect, on the session this test owns: no other test in
383 // this binary can open one for it, and no absolute claim is made on a
384 // counter *any* session in the process moves.
385 assert!(
386 ao.is_silent(),
387 "the pin must route the open to the silent sink"
388 );
389 assert_eq!(
390 AoSession::devices_opened(),
391 before,
392 "the silent open moved the process's device counter"
393 );
394 assert!(ao.set_volume(0.0));
395 assert!(!ao.set_volume(1.5));
396 assert!(ao.set_active(true));
397 assert_eq!(ao.write(&[0.0; 64]), Some(64));
398 assert!(ao.flush());
399 ao.stream_ended();
400 assert_eq!(ao.underruns(), (0, None));
401 }
402}