| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | use std::ffi::c_void; |
| 14 | use std::path::Path; |
| 15 | use std::sync::atomic::{AtomicI64, AtomicU64, Ordering}; |
| 16 | use std::sync::{LazyLock, OnceLock}; |
| 17 | use std::time::Instant; |
| 18 | |
| 19 | use libloading::Library; |
| 20 | |
| 21 | 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 | |
| 29 | |
| 30 | |
| 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 | } |
| 44 | |
| 45 | struct 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 | |
| 54 | |
| 55 | |
| 56 | stream_ended: Option<unsafe extern "C" fn(*mut c_void) -> i32>, |
| 57 | close: unsafe extern "C" fn(*mut c_void), |
| 58 | |
| 59 | _lib: Library, |
| 60 | } |
| 61 | |
| 62 | fn plugin() -> Option<&'static Plugin> { |
| 63 | static PLUGIN: OnceLock<Option<Plugin>> = OnceLock::new(); |
| 64 | PLUGIN.get_or_init(load).as_ref() |
| 65 | } |
| 66 | |
| 67 | fn load() -> Option<Plugin> { |
| 68 | |
| 69 | |
| 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 | |
| 80 | |
| 81 | |
| 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 | |
| 94 | |
| 95 | |
| 96 | |
| 97 | |
| 98 | set_volume: *lib.get(b"ao_set_volume\0").ok()?, |
| 99 | flush: *lib.get(b"ao_flush\0").ok()?, |
| 100 | |
| 101 | |
| 102 | |
| 103 | |
| 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 | |
| 119 | pub struct AoSession { |
| 120 | backend: Backend, |
| 121 | } |
| 122 | |
| 123 | enum Backend { |
| 124 | Plugin { |
| 125 | plugin: &'static Plugin, |
| 126 | handle: *mut c_void, |
| 127 | }, |
| 128 | |
| 129 | |
| 130 | |
| 131 | Silent(Silent), |
| 132 | } |
| 133 | |
| 134 | struct Silent { |
| 135 | rate: f64, |
| 136 | |
| 137 | base: AtomicI64, |
| 138 | |
| 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 | } |
| 200 | } |
| 201 | |
| 202 | impl AoSession { |
| 203 | |
| 204 | |
| 205 | |
| 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 | |
| 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 | |
| 225 | |
| 226 | pub fn devices_opened() -> u64 { |
| 227 | DEVICES_OPENED.load(Ordering::Relaxed) |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | |
| 233 | |
| 234 | pub fn is_silent(&self) -> bool { |
| 235 | matches!(self.backend, Backend::Silent(_)) |
| 236 | } |
| 237 | |
| 238 | |
| 239 | |
| 240 | |
| 241 | pub fn probe() -> bool { |
| 242 | plugin().is_some() |
| 243 | } |
| 244 | |
| 245 | |
| 246 | |
| 247 | |
| 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 | |
| 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 | |
| 262 | |
| 263 | pub fn position(&self) -> Option<i64> { |
| 264 | match &self.backend { |
| 265 | Backend::Silent(s) => s.position(), |
| 266 | Backend::Plugin { plugin, handle } => { |
| 267 | |
| 268 | match unsafe { (plugin.position)(*handle) } { |
| 269 | n if n < 0 => None, |
| 270 | n => Some(n), |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | |
| 277 | |
| 278 | |
| 279 | pub fn stream_ended(&self) { |
| 280 | if let Backend::Plugin { plugin, handle } = &self.backend { |
| 281 | if let Some(ended) = plugin.stream_ended { |
| 282 | |
| 283 | unsafe { ended(*handle) }; |
| 284 | } |
| 285 | } |
| 286 | } |
| 287 | |
| 288 | |
| 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 | |
| 297 | unsafe { (plugin.set_active)(*handle, active as u32) == 0 } |
| 298 | } |
| 299 | } |
| 300 | } |
| 301 | |
| 302 | |
| 303 | |
| 304 | |
| 305 | |
| 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 | |
| 314 | unsafe { (plugin.set_volume)(*handle, gain) == 0 } |
| 315 | } |
| 316 | } |
| 317 | } |
| 318 | |
| 319 | |
| 320 | |
| 321 | pub fn flush(&self) -> bool { |
| 322 | match &self.backend { |
| 323 | Backend::Silent(_) => true, |
| 324 | Backend::Plugin { plugin, handle } => { |
| 325 | |
| 326 | unsafe { (plugin.flush)(*handle) == 0 } |
| 327 | } |
| 328 | } |
| 329 | } |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 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 | |
| 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 | |
| 348 | impl Drop for AoSession { |
| 349 | fn drop(&mut self) { |
| 350 | if let Backend::Plugin { plugin, handle } = &self.backend { |
| 351 | |
| 352 | unsafe { (plugin.close)(*handle) } |
| 353 | } |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | |
| 358 | |
| 359 | unsafe impl Send for AoSession {} |
| 360 | |
| 361 | #[cfg(test)] |
| 362 | mod tests { |
| 363 | use super::AoSession; |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 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 | |
| 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 | |
| 383 | |
| 384 | |
| 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 | } |