forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

ao.rs157 lines, 6.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
8use std::ffi::c_void;
9use std::path::Path;
10use std::sync::OnceLock;
11
12use libloading::Library;
13
14const LIB_NAME: &str = "libengine_audio.so";
15
16struct Plugin {
17 open: unsafe extern "C" fn(u32, u32) -> *mut c_void,
18 write: unsafe extern "C" fn(*mut c_void, *const f32, usize) -> isize,
19 position: unsafe extern "C" fn(*mut c_void) -> i64,
20 set_active: unsafe extern "C" fn(*mut c_void, u32) -> i32,
21 set_volume: unsafe extern "C" fn(*mut c_void, f32) -> i32,
22 flush: unsafe extern "C" fn(*mut c_void) -> i32,
23 close: unsafe extern "C" fn(*mut c_void),
24 // Never dropped (lives in a static), so the fn pointers above stay valid.
25 _lib: Library,
26}
27
28fn plugin() -> Option<&'static Plugin> {
29 static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new();
30 PLUGIN.get_or_init(load).as_ref()
31}
32
33fn load() -> Option<Plugin> {
34 // Next to the executable first (cargo puts both in target/<profile>), then
35 // whatever the dynamic linker's search path turns up.
36 let beside_exe = std::env::current_exe()
37 .ok()
38 .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)));
39 let candidates = beside_exe
40 .as_deref()
41 .into_iter()
42 .chain(std::iter::once(Path::new(LIB_NAME)));
43
44 for candidate in candidates {
45 // SAFETY: loading a shared object runs its initialisers; we only ever
46 // name our own plugin, and every symbol below is type-checked against
47 // the signatures this crate shares with it.
48 let lib = match unsafe { Library::new(candidate) } {
49 Ok(lib) => lib,
50 Err(_) => continue,
51 };
52 let plugin = unsafe {
53 (|| {
54 Some(Plugin {
55 open: *lib.get(b"ao_open\0").ok()?,
56 write: *lib.get(b"ao_write\0").ok()?,
57 position: *lib.get(b"ao_position\0").ok()?,
58 set_active: *lib.get(b"ao_set_active\0").ok()?,
59 // Required, so a plugin predating seek is rejected whole
60 // and we play muted rather than half-working. Volume is
61 // required on the same terms: the two ship from one build,
62 // and a mute button that does nothing is worse than a run
63 // with no sound at all, which at least says so.
64 set_volume: *lib.get(b"ao_set_volume\0").ok()?,
65 flush: *lib.get(b"ao_flush\0").ok()?,
66 close: *lib.get(b"ao_close\0").ok()?,
67 _lib: lib,
68 })
69 })()
70 };
71 if plugin.is_some() {
72 return plugin;
73 }
74 }
75 None
76}
77
78/// An open playback stream. Dropping it stops playback and closes the session.
79pub struct AoSession {
80 plugin: &'static Plugin,
81 handle: *mut c_void,
82}
83
84impl AoSession {
85 /// Connects a playback stream for interleaved f32 at `sample_rate`.
86 /// `None` covers everything: no plugin, no daemon, unusable format.
87 pub fn open(sample_rate: u32, channels: u32) -> Option<Self> {
88 let plugin = plugin()?;
89 // SAFETY: plain scalars in, a session pointer or null out.
90 let handle = unsafe { (plugin.open)(sample_rate, channels) };
91 if handle.is_null() {
92 return None;
93 }
94 Some(Self { plugin, handle })
95 }
96
97 /// Whether the plugin itself is loadable. Says nothing about the daemon --
98 /// only [`AoSession::open`] answers that, and it is cheap enough to be the
99 /// real probe.
100 pub fn probe() -> bool {
101 plugin().is_some()
102 }
103
104 /// Queues interleaved samples, returning how many were accepted; a short
105 /// count means the ring is full and the caller should come back later.
106 /// `None` once the output has died (daemon gone).
107 pub fn write(&mut self, samples: &[f32]) -> Option<usize> {
108 // SAFETY: `handle` is live and `samples` is a valid slice for the call.
109 match unsafe { (self.plugin.write)(self.handle, samples.as_ptr(), samples.len()) } {
110 n if n < 0 => None,
111 n => Some(n as usize),
112 }
113 }
114
115 /// Samples per channel actually played at the device -- the master clock.
116 /// `None` until the stream has run its first cycle.
117 pub fn position(&self) -> Option<i64> {
118 // SAFETY: `handle` came from `ao_open` and is still open.
119 match unsafe { (self.plugin.position)(self.handle) } {
120 n if n < 0 => None,
121 n => Some(n),
122 }
123 }
124
125 /// Pauses or resumes playback; while paused the position stays put.
126 pub fn set_active(&self, active: bool) -> bool {
127 // SAFETY: `handle` came from `ao_open` and is still open.
128 unsafe { (self.plugin.set_active)(self.handle, active as u32) == 0 }
129 }
130
131 /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's
132 /// volume and its mute are the same knob by the time they get here. The
133 /// clock is unaffected -- a silenced stream still plays, so the picture
134 /// keeps running against it. `false` for a gain outside the range.
135 pub fn set_volume(&self, gain: f32) -> bool {
136 // SAFETY: `handle` came from `ao_open` and is still open.
137 unsafe { (self.plugin.set_volume)(self.handle, gain) == 0 }
138 }
139
140 /// Drops everything still queued, so the next samples written play right
141 /// away -- what a seek needs. The played position keeps counting.
142 pub fn flush(&self) -> bool {
143 // SAFETY: `handle` came from `ao_open` and is still open.
144 unsafe { (self.plugin.flush)(self.handle) == 0 }
145 }
146}
147
148impl Drop for AoSession {
149 fn drop(&mut self) {
150 // SAFETY: `handle` came from `ao_open` and is closed exactly once.
151 unsafe { (self.plugin.close)(self.handle) }
152 }
153}
154
155// The session is used from one thread at a time (the audio feeder) and never
156// shared; the PipeWire state behind it is not `Sync`.
157unsafe impl Send for AoSession {}