forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

ao.rs189 lines, 7.9 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 underruns: unsafe extern "C" fn(*mut c_void, *mut i64) -> i64,
24 /// Optional, unlike its neighbours: without it a plugin plays exactly as it
25 /// did and only counts the tail of a played-out stream as lateness, which
26 /// is a worse diagnostic rather than a worse session.
27 stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>,
28 close: unsafe extern "C" fn(*mut c_void),
29 // Never dropped (lives in a static), so the fn pointers above stay valid.
30 _lib: Library,
31}
32
33fn plugin() -> Option<&'static Plugin> {
34 static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new();
35 PLUGIN.get_or_init(load).as_ref()
36}
37
38fn load() -> Option<Plugin> {
39 // Next to the executable first (cargo puts both in target/<profile>), then
40 // whatever the dynamic linker's search path turns up.
41 let beside_exe = std::env::current_exe()
42 .ok()
43 .and_then(|exe| exe.parent().map(|dir| dir.join(LIB_NAME)));
44 let candidates = beside_exe
45 .as_deref()
46 .into_iter()
47 .chain(std::iter::once(Path::new(LIB_NAME)));
48
49 for candidate in candidates {
50 // SAFETY: loading a shared object runs its initialisers; we only ever
51 // name our own plugin, and every symbol below is type-checked against
52 // the signatures this crate shares with it.
53 let lib = match unsafe { Library::new(candidate) } {
54 Ok(lib) => lib,
55 Err(_) => continue,
56 };
57 let plugin = unsafe {
58 (|| {
59 Some(Plugin {
60 open: *lib.get(b"ao_open\0").ok()?,
61 write: *lib.get(b"ao_write\0").ok()?,
62 position: *lib.get(b"ao_position\0").ok()?,
63 set_active: *lib.get(b"ao_set_active\0").ok()?,
64 // Required, so a plugin predating seek is rejected whole
65 // and we play muted rather than half-working. Volume is
66 // required on the same terms: the two ship from one build,
67 // and a mute button that does nothing is worse than a run
68 // with no sound at all, which at least says so.
69 set_volume: *lib.get(b"ao_set_volume\0").ok()?,
70 flush: *lib.get(b"ao_flush\0").ok()?,
71 // Required on the same terms as the two above: the plugin
72 // ships from this build, and a measurement that silently
73 // reads zero underruns is worse than a run that says the
74 // plugin is the wrong one.
75 underruns: *lib.get(b"ao_underruns\0").ok()?,
76 stream_ended: lib.get(b"ao_stream_ended\0").ok().map(|f| *f),
77 close: *lib.get(b"ao_close\0").ok()?,
78 _lib: lib,
79 })
80 })()
81 };
82 if plugin.is_some() {
83 return plugin;
84 }
85 }
86 None
87}
88
89/// An open playback stream. Dropping it stops playback and closes the session.
90pub struct AoSession {
91 plugin: &'static Plugin,
92 handle: *mut c_void,
93}
94
95impl AoSession {
96 /// Connects a playback stream for interleaved f32 at `sample_rate`.
97 /// `None` covers everything: no plugin, no daemon, unusable format.
98 pub fn open(sample_rate: u32, channels: u32) -> Option<Self> {
99 let plugin = plugin()?;
100 // SAFETY: plain scalars in, a session pointer or null out.
101 let handle = unsafe { (plugin.open)(sample_rate, channels) };
102 if handle.is_null() {
103 return None;
104 }
105 Some(Self { plugin, handle })
106 }
107
108 /// Whether the plugin itself is loadable. Says nothing about the daemon --
109 /// only [`AoSession::open`] answers that, and it is cheap enough to be the
110 /// real probe.
111 pub fn probe() -> bool {
112 plugin().is_some()
113 }
114
115 /// Queues interleaved samples, returning how many were accepted; a short
116 /// count means the ring is full and the caller should come back later.
117 /// `None` once the output has died (daemon gone).
118 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),
123 }
124 }
125
126 /// Samples per channel actually played at the device -- the master clock.
127 /// `None` until the stream has run its first cycle.
128 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),
133 }
134 }
135
136 /// Says the last sample of this stream has been queued: the ring plays out
137 /// as it is, and the silence after it is not counted against a decoder that
138 /// has already finished. Nothing at all on a plugin without the symbol.
139 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) };
143 }
144 }
145
146 /// Pauses or resumes playback; while paused the position stays put.
147 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 }
150 }
151
152 /// Sets the output gain, 0.0 (silent) to 1.0 (as written): the editor's
153 /// volume and its mute are the same knob by the time they get here. The
154 /// clock is unaffected -- a silenced stream still plays, so the picture
155 /// keeps running against it. `false` for a gain outside the range.
156 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 }
159 }
160
161 /// Drops everything still queued, so the next samples written play right
162 /// away -- what a seek needs. The played position keeps counting.
163 pub fn flush(&self) -> bool {
164 // SAFETY: `handle` came from `ao_open` and is still open.
165 unsafe { (self.plugin.flush)(self.handle) == 0 }
166 }
167
168 /// Starved callbacks so far, and the device position (samples per channel)
169 /// the last of them was seen at -- `None` for a stream that has never run
170 /// dry. Two atomic loads inside the plugin, so it is cheap enough to poll
171 /// and it never touches the RT thread's path.
172 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))
177 }
178}
179
180impl Drop for AoSession {
181 fn drop(&mut self) {
182 // SAFETY: `handle` came from `ao_open` and is closed exactly once.
183 unsafe { (self.plugin.close)(self.handle) }
184 }
185}
186
187// The session is used from one thread at a time (the audio feeder) and never
188// shared; the PipeWire state behind it is not `Sync`.
189unsafe impl Send for AoSession {}