forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBf2bee6bTahinli2 months ago781 commits

lib.rs805 lines, 33.9 KiBHistoryRawDownload
1//! PipeWire playback, shipped as a `dlopen`-able plugin so the main binary
2//! never gets a DT_NEEDED on libpipewire. Every entry point is `extern "C"`,
3//! catches unwinds and reports failure as a null pointer or a negative code:
4//! the caller's contract is "any failure means the app runs muted".
5//!
6//! corner-cut: that guarantee rests on `panic = "unwind"`. Building this crate with
7//! `panic = "abort"` would turn a PipeWire bug into a killed app; the upgrade
8//! path is running the output in a child process instead of in-process.
9
10use std::ffi::c_void;
11use std::panic::{AssertUnwindSafe, catch_unwind};
12use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering};
13use std::sync::{Arc, OnceLock, mpsc};
14use std::thread::JoinHandle;
15use std::time::{Duration, Instant};
16
17use pipewire as pw;
18use pw::{properties::properties, spa};
19use spa::pod::Pod;
20
21/// How long the loop thread waits for the daemon to accept the stream before
22/// the open counts as failed. Negotiation is a couple of graph cycles when it
23/// works at all, so this only ever fires on a broken setup.
24const READY_TIMEOUT: Duration = Duration::from_secs(1);
25/// Belt and braces around the whole open: no PipeWire call on this path is
26/// supposed to block, but `ao_open` must never hang the caller.
27const OPEN_TIMEOUT: Duration = Duration::from_secs(2);
28/// Loop iteration timeout on the audio thread; also the worst-case latency of
29/// an `ao_set_active` taking effect.
30const POLL: Duration = Duration::from_millis(10);
31/// Frames we hand over per callback, and the latency we ask the graph for.
32/// Left to itself PipeWire gives us a buffer the size of the sink's (measured:
33/// 12288 frames, 256 ms) and calls us once per buffer, so the position clock --
34/// which only moves in the callback -- would step 256 ms at a time and land
35/// that coarseness straight in the A/V sync. 1024 frames is ~23 ms, comfortably
36/// inside a video frame; measured granularity is then one graph quantum.
37///
38/// corner-cut: a graph running a quantum longer than this would consume more per
39/// cycle than we deliver and starve. The fix is the crate's `v0_3_49` feature,
40/// whose `pw_buffer.requested` says exactly how many frames the graph wants --
41/// a Cargo.toml change, so not this slice.
42const QUANTUM: u32 = 1024;
43
44/// Lock-free SPSC ring of f32 samples (interleaved, one producer: `ao_write`,
45/// one consumer: the RT process callback). Samples live in atomics rather than
46/// behind a lock so the RT thread never waits on the decoder thread.
47struct Ring {
48 /// Power-of-two length, so the monotonic counters below can be masked and
49 /// still index correctly across a `usize` wrap.
50 slots: Box<[AtomicU32]>,
51 write: AtomicUsize,
52 read: AtomicUsize,
53}
54
55impl Ring {
56 fn new(capacity: usize) -> Self {
57 let len = capacity.next_power_of_two();
58 Self {
59 slots: (0..len).map(|_| AtomicU32::new(0)).collect(),
60 write: AtomicUsize::new(0),
61 read: AtomicUsize::new(0),
62 }
63 }
64
65 /// Appends as much of `src` as fits, returning how many samples were taken.
66 fn push(&self, src: &[f32]) -> usize {
67 let write = self.write.load(Ordering::Relaxed);
68 let used = write.wrapping_sub(self.read.load(Ordering::Acquire));
69 let n = src.len().min(self.slots.len() - used);
70 let mask = self.slots.len() - 1;
71 for (i, sample) in src[..n].iter().enumerate() {
72 self.slots[write.wrapping_add(i) & mask].store(sample.to_bits(), Ordering::Relaxed);
73 }
74 self.write.store(write.wrapping_add(n), Ordering::Release);
75 n
76 }
77
78 /// Pops up to `want` samples as little-endian f32 into `dst`, returning how
79 /// many were available. `dst` must hold `want * 4` bytes.
80 fn pop(&self, dst: &mut [u8], want: usize) -> usize {
81 let read = self.read.load(Ordering::Relaxed);
82 let avail = self.write.load(Ordering::Acquire).wrapping_sub(read);
83 let n = want.min(avail);
84 let mask = self.slots.len() - 1;
85 for i in 0..n {
86 let bits = self.slots[read.wrapping_add(i) & mask].load(Ordering::Relaxed);
87 dst[i * 4..i * 4 + 4].copy_from_slice(&bits.to_le_bytes());
88 }
89 self.read.store(read.wrapping_add(n), Ordering::Release);
90 n
91 }
92}
93
94/// Multiplies the little-endian f32 samples in `dst` by `gain`, in place.
95///
96/// This is how the editor's volume and mute are applied, rather than through
97/// the stream's PipeWire volume control: the session manager persists every
98/// change to a node's Props into its restore state (measured: WirePlumber
99/// writes the bucket ~2 s after the change), so a mute keypress here would
100/// become "edith is muted" in the system mixer tomorrow, and a quit while
101/// muted would come back muted with nothing in the app to explain it. Scaling
102/// the samples is invisible to the daemon, costs one multiply each, and --
103/// because the frames are still consumed and still handed over -- leaves the
104/// device clock, and so the whole A/V sync, exactly where it was.
105fn scale(dst: &mut [u8], gain: f32) {
106 if gain == 1.0 {
107 return;
108 }
109 for sample in dst.chunks_exact_mut(4) {
110 let scaled = f32::from_le_bytes(sample.try_into().unwrap_or([0; 4])) * gain;
111 sample.copy_from_slice(&scaled.to_le_bytes());
112 }
113}
114
115/// The consumer half of a flush: drops everything queued, then pops as usual.
116/// Doing it here rather than in `ao_flush` keeps the ring single-consumer --
117/// only the RT thread ever moves `read` -- and means a flush asked for while
118/// paused (no callbacks running) still lands before the next pop, so the stale
119/// samples can never be heard.
120/// The producer half of a flush: while the flag is pending, the ring still
121/// holds pre-flush audio waiting to be discarded, and anything accepted now
122/// would queue BEHIND that discard -- with no RT callbacks running (paused
123/// seek) the next callback would then drain the new stream's head along with
124/// the stale tail. Refuse instead; the writer's retry loop parks until the
125/// RT thread consumes the flag.
126fn accept(flush: &AtomicBool, ring: &Ring, primed: &AtomicBool, samples: &[f32]) -> usize {
127 if flush.load(Ordering::Acquire) {
128 return 0;
129 }
130 let pushed = ring.push(samples);
131 if pushed > 0 {
132 // There is something to play from here on, so a starved callback means
133 // what it says again (`Shared::primed`).
134 primed.store(true, Ordering::Release);
135 }
136 pushed
137}
138
139fn consume(flush: &AtomicBool, ring: &Ring, dst: &mut [u8], want: usize) -> usize {
140 if flush.swap(false, Ordering::Acquire) {
141 ring.read
142 .store(ring.write.load(Ordering::Acquire), Ordering::Release);
143 }
144 ring.pop(dst, want)
145}
146
147/// Everything the RT thread and the caller's thread both touch.
148struct Shared {
149 ring: Ring,
150 /// Samples per channel played at the device, -1 until the first callback.
151 position: AtomicI64,
152 /// Set once the daemon has accepted the stream.
153 ready: AtomicBool,
154 /// Stream died (daemon gone, node removed); every later write fails.
155 dead: AtomicBool,
156 /// Asked for by `ao_flush`, honoured by the next process callback.
157 flush: AtomicBool,
158 /// Set by `ao_set_active(true)`, cleared by the next process callback: the
159 /// graph clock keeps ticking while the stream is inactive, and that time
160 /// was never played.
161 resumed: AtomicBool,
162 /// Output gain as f32 bits, 1.0 until the caller says otherwise. Read once
163 /// per callback on the RT thread, so it is an atomic rather than a lock.
164 gain: AtomicU32,
165 /// Whether the ring has been given a sample to play since it was last
166 /// emptied *on purpose*: `false` from the open and from every `ao_flush`
167 /// until the next accepted write.
168 ///
169 /// A callback that finds nothing to play while this is false is the silence
170 /// of a stream that has not started yet -- the head of a seek, whose decoder
171 /// is still being opened -- and not a decoder that fell behind. Counting it
172 /// made the number below say "a seek happened" (1721 of them over a scripted
173 /// cold play-seek-scrub, against 5 warm) instead of the one thing it is for.
174 /// The wait itself is not hidden by this: it is the clock's business, and
175 /// the clock holds still through it (`Audio::content_at`).
176 primed: AtomicBool,
177 underruns: AtomicU64,
178 /// Device position (samples per channel) read at the most recent underrun,
179 /// `-1` until one happens: what says whether the count in hand is old news
180 /// or is still growing. Written on the RT thread, and only on the starved
181 /// path, so the ordinary callback pays nothing for it.
182 last_underrun: AtomicI64,
183}
184
185enum Ctl {
186 Active(bool),
187 Quit,
188}
189
190fn pw_init() {
191 // Refcounted inside libpipewire, but a plugin has no safe point to call
192 // `pw::deinit`, so we init exactly once and never tear down.
193 static INIT: OnceLock<()> = OnceLock::new();
194 INIT.get_or_init(pw::init);
195}
196
197/// Builds the stream, reports readiness through `ready`, then owns the PipeWire
198/// loop until told to quit. Everything PipeWire lives in this one frame: the
199/// smart pointers are `Rc`-flavoured and the borrow chain (listener -> stream ->
200/// core -> context -> loop) is what enforces the destruction order.
201fn run(
202 rate: u32,
203 channels: usize,
204 shared: Arc<Shared>,
205 ready: mpsc::Sender<()>,
206 ctl: mpsc::Receiver<Ctl>,
207) -> Result<(), pw::Error> {
208 pw_init();
209 let mainloop = pw::main_loop::MainLoopRc::new(None)?;
210 let context = pw::context::ContextRc::new(&mainloop, None)?;
211 // Fails synchronously when there is no daemon to talk to: the clean probe.
212 let core = context.connect_rc(None)?;
213
214 let stream = pw::stream::StreamBox::new(
215 &core,
216 "video-editor",
217 properties! {
218 *pw::keys::MEDIA_TYPE => "Audio",
219 *pw::keys::MEDIA_CATEGORY => "Playback",
220 // Deliberately no MEDIA_ROLE: the session manager keys saved stream
221 // volume/mute by media.role before anything else, so declaring
222 // "Movie" put us in one bucket with every other video player on the
223 // box -- a mute somebody set on one of them last month came back as
224 // "edith has no sound", with nothing in the app to undo it. Without
225 // a role we get our own bucket, keyed by name, and start audible.
226 // Restoring stays ON: it is also what initialises the channel
227 // volumes, and a stream that opts out of it comes up at -inf dB.
228 *pw::keys::AUDIO_CHANNELS => channels.to_string(),
229 // Asks the graph to schedule us at our own quantum, which is what
230 // keeps the fill below from under-delivering on a lazy sink.
231 *pw::keys::NODE_LATENCY => format!("{QUANTUM}/{rate}"),
232 },
233 )?;
234
235 let _listener = stream
236 .add_local_listener_with_user_data(())
237 .state_changed({
238 let shared = shared.clone();
239 move |_, (), _old, new| match new {
240 pw::stream::StreamState::Paused | pw::stream::StreamState::Streaming => {
241 shared.ready.store(true, Ordering::Relaxed)
242 }
243 pw::stream::StreamState::Error(_) | pw::stream::StreamState::Unconnected => {
244 shared.dead.store(true, Ordering::Relaxed)
245 }
246 pw::stream::StreamState::Connecting => {}
247 }
248 })
249 .process({
250 let shared = shared.clone();
251 let stride = 4 * channels;
252 // Graph ticks that elapsed while the stream was inactive, and the
253 // last raw reading they are measured against.
254 let (mut skew, mut last_raw) = (0i64, 0i64);
255 move |stream, ()| {
256 let Some(mut buffer) = stream.dequeue_buffer() else {
257 return;
258 };
259 let datas = buffer.datas_mut();
260 let Some(data) = datas.first_mut() else {
261 return;
262 };
263 let n_frames = match data.data() {
264 Some(slice) => {
265 // Only a quantum per callback, however big the buffer
266 // is: everything we queue here is latency the clock,
267 // the pause and a future seek all have to wait out.
268 let frames = (slice.len() / stride).min(QUANTUM as usize);
269 let want = frames * channels;
270 let got = consume(&shared.flush, &shared.ring, slice, want);
271 if got < want {
272 // Underrun: silence rather than stale samples, and
273 // the clock below keeps running -- the device plays
274 // that silence, so it really is elapsed time.
275 slice[got * 4..want * 4].fill(0);
276 // ...but only a *started* stream can be late; see
277 // `Shared::primed`. One relaxed load on the RT
278 // thread, which is what this branch can afford.
279 if shared.primed.load(Ordering::Relaxed) {
280 shared.underruns.fetch_add(1, Ordering::Relaxed);
281 // The position this callback is about to compute
282 // is not known yet; the previous one is a quantum
283 // (~23 ms) behind and needs no clock call here.
284 shared.last_underrun.store(
285 shared.position.load(Ordering::Relaxed),
286 Ordering::Relaxed,
287 );
288 }
289 }
290 // After the fill, so the silence stays silent whatever
291 // the gain is, and the underrun count keeps meaning
292 // "the decoder was late" rather than "the user muted".
293 scale(
294 &mut slice[..want * 4],
295 f32::from_bits(shared.gain.load(Ordering::Relaxed)),
296 );
297 frames
298 }
299 None => 0,
300 };
301 let chunk = data.chunk_mut();
302 *chunk.offset_mut() = 0;
303 *chunk.stride_mut() = stride as _;
304 *chunk.size_mut() = (stride * n_frames) as _;
305
306 // The A/V master clock: what the device has actually played,
307 // which is the stream position minus everything still in flight.
308 if let Ok(time) = stream.time() {
309 let ticks = time.ticks() as i64 - time.delay();
310 let (num, denom) = (time.rate().num as i128, time.rate().denom as i128);
311 // `ticks` counts in the stream's own rate; convert to ours.
312 let played = if denom > 0 {
313 (ticks as i128 * num * rate as i128 / denom) as i64
314 } else {
315 ticks
316 };
317 // The graph clock runs whether or not this stream does, so a
318 // pause shows up here as a step. Nothing was played during
319 // it: fold it into the skew instead of the position, or the
320 // pause leaks into the caller's timeline.
321 if shared.resumed.swap(false, Ordering::Relaxed) {
322 skew += played - last_raw;
323 }
324 last_raw = played;
325 shared
326 .position
327 .store((played - skew).max(0), Ordering::Relaxed);
328 }
329 }
330 })
331 .register()?;
332
333 let mut audio_info = spa::param::audio::AudioInfoRaw::new();
334 audio_info.set_format(spa::param::audio::AudioFormat::F32LE);
335 audio_info.set_rate(rate);
336 audio_info.set_channels(channels as u32);
337 let mut position = [0; spa::param::audio::MAX_CHANNELS];
338 match channels {
339 1 => position[0] = libspa_sys::SPA_AUDIO_CHANNEL_MONO,
340 2 => {
341 position[0] = libspa_sys::SPA_AUDIO_CHANNEL_FL;
342 position[1] = libspa_sys::SPA_AUDIO_CHANNEL_FR;
343 }
344 // Anything else keeps UNKNOWN positions and lets the daemon map them.
345 _ => {}
346 }
347 audio_info.set_position(position);
348
349 let values: Vec<u8> = pw::spa::pod::serialize::PodSerializer::serialize(
350 std::io::Cursor::new(Vec::new()),
351 &pw::spa::pod::Value::Object(pw::spa::pod::Object {
352 type_: libspa_sys::SPA_TYPE_OBJECT_Format,
353 id: libspa_sys::SPA_PARAM_EnumFormat,
354 properties: audio_info.into(),
355 }),
356 )
357 .map_err(|_| pw::Error::CreationFailed)?
358 .0
359 .into_inner();
360 let mut params = [Pod::from_bytes(&values).ok_or(pw::Error::CreationFailed)?];
361
362 stream.connect(
363 spa::utils::Direction::Output,
364 None,
365 pw::stream::StreamFlags::AUTOCONNECT
366 | pw::stream::StreamFlags::MAP_BUFFERS
367 | pw::stream::StreamFlags::RT_PROCESS,
368 &mut params,
369 )?;
370
371 // `connect` only starts negotiation, so a bad format or a daemon that
372 // refuses us still shows up here rather than as silent nothing later.
373 let deadline = Instant::now() + READY_TIMEOUT;
374 while !shared.ready.load(Ordering::Relaxed) {
375 if shared.dead.load(Ordering::Relaxed) || Instant::now() >= deadline {
376 return Err(pw::Error::CreationFailed);
377 }
378 mainloop.loop_().iterate(pw::loop_::Timeout::Finite(POLL));
379 }
380 let _ = ready.send(());
381
382 // Driving the loop by hand instead of `mainloop.run()` + a PipeWire channel:
383 // loop callbacks must be `'static` and the stream borrows the core, so a
384 // callback cannot touch the stream. Iterating lets us call `set_active` from
385 // this very frame. With RT_PROCESS the audio callback runs on the RT thread
386 // regardless, so this loop only handles negotiation and control.
387 'run: loop {
388 mainloop.loop_().iterate(pw::loop_::Timeout::Finite(POLL));
389 loop {
390 match ctl.try_recv() {
391 Ok(Ctl::Active(active)) => {
392 let _ = stream.set_active(active);
393 }
394 // Disconnected means the session was dropped without a Quit.
395 Ok(Ctl::Quit) | Err(mpsc::TryRecvError::Disconnected) => break 'run,
396 Err(mpsc::TryRecvError::Empty) => break,
397 }
398 }
399 }
400 let _ = stream.disconnect();
401 Ok(())
402}
403
404struct Session {
405 shared: Arc<Shared>,
406 ctl: mpsc::Sender<Ctl>,
407 thread: Option<JoinHandle<()>>,
408}
409
410impl Drop for Session {
411 fn drop(&mut self) {
412 let _ = self.ctl.send(Ctl::Quit);
413 if let Some(thread) = self.thread.take() {
414 let _ = thread.join();
415 }
416 let underruns = self.shared.underruns.load(Ordering::Relaxed);
417 if underruns > 0 {
418 eprintln!("engine_audio: {underruns} underruns");
419 }
420 }
421}
422
423/// Opens a playback stream for `sample_rate` Hz, `channels` channels of
424/// interleaved f32. Returns null on any failure at all: no libpipewire, no
425/// daemon, an unusable format.
426#[unsafe(no_mangle)]
427pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void {
428 catch_unwind(AssertUnwindSafe(|| {
429 if !(8_000..=768_000).contains(&sample_rate)
430 || channels == 0
431 || channels as usize > spa::param::audio::MAX_CHANNELS
432 {
433 return std::ptr::null_mut();
434 }
435 pw_init();
436
437 let shared = Arc::new(Shared {
438 // One second of audio: enough that a stalled decoder is audible as
439 // an underrun rather than papered over by a huge buffer.
440 ring: Ring::new(sample_rate as usize * channels as usize),
441 position: AtomicI64::new(-1),
442 ready: AtomicBool::new(false),
443 dead: AtomicBool::new(false),
444 flush: AtomicBool::new(false),
445 resumed: AtomicBool::new(false),
446 gain: AtomicU32::new(1.0f32.to_bits()),
447 // Nothing has been queued yet, so the callbacks between the connect
448 // and the caller's first write have nothing to be late for.
449 primed: AtomicBool::new(false),
450 underruns: AtomicU64::new(0),
451 last_underrun: AtomicI64::new(-1),
452 });
453 let (ready_tx, ready_rx) = mpsc::channel();
454 let (ctl_tx, ctl_rx) = mpsc::channel();
455 let thread = std::thread::spawn({
456 let shared = shared.clone();
457 move || {
458 if let Err(e) = run(sample_rate, channels as usize, shared, ready_tx, ctl_rx) {
459 eprintln!("engine_audio: {e}");
460 }
461 }
462 });
463
464 // A failed setup drops `ready_tx`, so this returns without waiting out
465 // the timeout; the timeout only covers a PipeWire call that blocks
466 // against its contract, and then we leave the thread to its own exit.
467 match ready_rx.recv_timeout(OPEN_TIMEOUT) {
468 Ok(()) => Box::into_raw(Box::new(Session {
469 shared,
470 ctl: ctl_tx,
471 thread: Some(thread),
472 })) as *mut c_void,
473 Err(_) => {
474 let _ = ctl_tx.send(Ctl::Quit);
475 std::ptr::null_mut()
476 }
477 }
478 }))
479 .unwrap_or(std::ptr::null_mut())
480}
481
482/// Queues up to `n` interleaved f32 samples, returning how many were accepted:
483/// short counts mean the ring is full. Never blocks. -1 once the stream is dead.
484///
485/// # Safety
486/// `session` must come from [`ao_open`] and `samples` must point at `n` f32s.
487#[unsafe(no_mangle)]
488pub unsafe extern "C" fn ao_write(session: *mut c_void, samples: *const f32, n: usize) -> isize {
489 catch_unwind(AssertUnwindSafe(|| {
490 if session.is_null() || samples.is_null() {
491 return -1;
492 }
493 // SAFETY: caller-guaranteed live session and `n` readable samples.
494 let session = unsafe { &*(session as *const Session) };
495 if session.shared.dead.load(Ordering::Relaxed) {
496 return -1;
497 }
498 let samples = unsafe { std::slice::from_raw_parts(samples, n) };
499 accept(
500 &session.shared.flush,
501 &session.shared.ring,
502 &session.shared.primed,
503 samples,
504 ) as isize
505 }))
506 .unwrap_or(-1)
507}
508
509/// Samples per channel actually played at the device, or -1 while unknown.
510///
511/// # Safety
512/// `session` must come from [`ao_open`].
513#[unsafe(no_mangle)]
514pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 {
515 catch_unwind(AssertUnwindSafe(|| {
516 if session.is_null() {
517 return -1;
518 }
519 // SAFETY: caller-guaranteed live session.
520 let session = unsafe { &*(session as *const Session) };
521 session.shared.position.load(Ordering::Relaxed)
522 }))
523 .unwrap_or(-1)
524}
525
526/// Says the caller has queued the last sample this stream will ever have.
527/// What is still in the ring plays out untouched -- this is not a flush and not
528/// a pause -- but the silence *after* it stops being counted as a late decoder:
529/// there is no decoder left to be late ([`Shared::primed`]). The next accepted
530/// write is a stream again and counts again. 0 on success.
531///
532/// # Safety
533/// `session` must come from [`ao_open`].
534#[unsafe(no_mangle)]
535pub unsafe extern "C" fn ao_stream_ended(session: *mut c_void) -> i32 {
536 catch_unwind(AssertUnwindSafe(|| {
537 if session.is_null() {
538 return -1;
539 }
540 // SAFETY: caller-guaranteed live session.
541 let session = unsafe { &*(session as *const Session) };
542 session.shared.primed.store(false, Ordering::Release);
543 0
544 }))
545 .unwrap_or(-1)
546}
547
548/// Starved callbacks since the stream opened -- one per quantum the decoder was
549/// late for -- and, through `last_at`, the device position the newest of them
550/// was seen at (`-1` if there has been none). The same number the drop print
551/// reports, asked for while the session is still running: a caller measuring a
552/// seek reads it before and after and the difference is that seek's cost.
553///
554/// Two relaxed atomic loads, nothing else: the RT thread writes both and must
555/// never wait on a reader.
556///
557/// # Safety
558/// `session` must come from [`ao_open`]; `last_at` is either null or writable.
559#[unsafe(no_mangle)]
560pub unsafe extern "C" fn ao_underruns(session: *mut c_void, last_at: *mut i64) -> i64 {
561 catch_unwind(AssertUnwindSafe(|| {
562 if session.is_null() {
563 return -1;
564 }
565 // SAFETY: caller-guaranteed live session.
566 let session = unsafe { &*(session as *const Session) };
567 if !last_at.is_null() {
568 // SAFETY: caller-guaranteed writable, and it is a plain i64.
569 unsafe { *last_at = session.shared.last_underrun.load(Ordering::Relaxed) };
570 }
571 session.shared.underruns.load(Ordering::Relaxed) as i64
572 }))
573 .unwrap_or(-1)
574}
575
576/// Pauses (0) or resumes (non-zero) playback. Paused freezes the position.
577/// 0 on success, negative on failure.
578///
579/// # Safety
580/// `session` must come from [`ao_open`].
581#[unsafe(no_mangle)]
582pub unsafe extern "C" fn ao_set_active(session: *mut c_void, active: u32) -> i32 {
583 catch_unwind(AssertUnwindSafe(|| {
584 if session.is_null() {
585 return -1;
586 }
587 // SAFETY: caller-guaranteed live session.
588 let session = unsafe { &*(session as *const Session) };
589 if active != 0 {
590 session.shared.resumed.store(true, Ordering::Relaxed);
591 }
592 match session.ctl.send(Ctl::Active(active != 0)) {
593 Ok(()) => 0,
594 Err(_) => -1,
595 }
596 }))
597 .unwrap_or(-1)
598}
599
600/// Sets the output gain: 0.0 is silence, 1.0 is the samples as written. One
601/// knob for both the editor's volume and its mute -- mute is a gain of 0.0
602/// pushed down, and which of the two the user is looking at is the caller's
603/// business. Takes effect on the next callback (~23 ms), and the position keeps
604/// advancing throughout: this silences the output, it does not pause it.
605/// 0 on success, negative on failure or a gain that is not in `0.0..=1.0`.
606///
607/// # Safety
608/// `session` must come from [`ao_open`].
609#[unsafe(no_mangle)]
610pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 {
611 catch_unwind(AssertUnwindSafe(|| {
612 // A NaN would compare false against every bound and then multiply every
613 // sample into a NaN, which is a loud fault in a speaker: refuse it here,
614 // at the ABI, rather than let it reach the RT thread.
615 if session.is_null() || !(0.0..=1.0).contains(&gain) {
616 return -1;
617 }
618 // SAFETY: caller-guaranteed live session.
619 let session = unsafe { &*(session as *const Session) };
620 session.shared.gain.store(gain.to_bits(), Ordering::Relaxed);
621 0
622 }))
623 .unwrap_or(-1)
624}
625
626/// Drops every queued sample, so playback resumes from whatever is written
627/// next: what a seek needs. Takes effect on the next process callback (or the
628/// first one after a resume), and leaves the played position alone -- the
629/// device keeps counting, the caller re-bases against it.
630/// 0 on success, negative on failure.
631///
632/// # Safety
633/// `session` must come from [`ao_open`].
634#[unsafe(no_mangle)]
635pub unsafe extern "C" fn ao_flush(session: *mut c_void) -> i32 {
636 catch_unwind(AssertUnwindSafe(|| {
637 if session.is_null() {
638 return -1;
639 }
640 // SAFETY: caller-guaranteed live session.
641 let session = unsafe { &*(session as *const Session) };
642 // Unprimed first, so the callback that consumes the flag below cannot
643 // find an empty ring and count the head of the restart as a late
644 // decoder (`Shared::primed`).
645 session.shared.primed.store(false, Ordering::Release);
646 session.shared.flush.store(true, Ordering::Release);
647 0
648 }))
649 .unwrap_or(-1)
650}
651
652/// Stops playback and releases the session. Safe to call with null.
653///
654/// # Safety
655/// `session` must come from [`ao_open`] and must not be used afterwards.
656#[unsafe(no_mangle)]
657pub unsafe extern "C" fn ao_close(session: *mut c_void) {
658 let _ = catch_unwind(AssertUnwindSafe(|| {
659 if !session.is_null() {
660 // SAFETY: pointer came from `Box::into_raw` in `ao_open`.
661 drop(unsafe { Box::from_raw(session as *mut Session) });
662 }
663 }));
664}
665
666#[cfg(test)]
667mod tests {
668 use super::{AtomicBool, Ordering, Ring, accept, consume, scale};
669
670 /// The gain is applied to the bytes the device is about to play, so silence
671 /// really is silence and a partial gain really is quieter -- and 1.0 must
672 /// leave the samples bit-identical, since that is every callback's path.
673 #[test]
674 fn gain_scales_the_samples_the_device_sees() {
675 let sample =
676 |bytes: &[u8], i: usize| f32::from_le_bytes(bytes[i..i + 4].try_into().unwrap());
677
678 let mut buf = Vec::new();
679 for v in [1.0f32, -0.5, 0.25] {
680 buf.extend_from_slice(&v.to_le_bytes());
681 }
682
683 // Unity is the no-op the common case walks through.
684 let untouched = buf.clone();
685 scale(&mut buf, 1.0);
686 assert_eq!(buf, untouched);
687
688 // Half volume, sign kept.
689 scale(&mut buf, 0.5);
690 assert_eq!(sample(&buf, 0), 0.5);
691 assert_eq!(sample(&buf, 4), -0.25);
692
693 // Mute is a gain of zero: every sample gone, none left ringing.
694 scale(&mut buf, 0.0);
695 assert!(buf.chunks_exact(4).all(|s| sample(s, 0) == 0.0));
696 }
697
698 /// The paused-seek ordering: a flush requested with no RT callbacks running
699 /// must not let the writer queue new audio behind the pending discard.
700 #[test]
701 fn pending_flush_refuses_writes_until_consumed() {
702 let ring = Ring::new(4);
703 let flush = AtomicBool::new(false);
704 let primed = AtomicBool::new(false);
705 let mut out = [0u8; 16];
706
707 // Stale pre-seek audio sits in the ring; a flush is requested while
708 // paused (no callback runs yet).
709 assert_eq!(accept(&flush, &ring, &primed, &[1.0, 2.0]), 2);
710 flush.store(true, Ordering::Release);
711
712 // The new stream's feeder tries to write: refused, ring untouched.
713 assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 0);
714
715 // First post-resume callback consumes the flag and drains the stale
716 // tail -- and ONLY the stale tail, because nothing was queued behind it.
717 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
718
719 // Writer unparks; the new audio flows intact.
720 assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 2);
721 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
722 assert_eq!(&out[..4], &3.0f32.to_le_bytes());
723 }
724
725 /// What the underrun count is allowed to mean: a starved callback is a late
726 /// decoder only while a decoder is actually behind the ring. The head of a
727 /// restart (nothing queued since the flush) and the tail of a stream (the
728 /// decoder is done) are silence nobody is late for, and counting them made
729 /// the number say "a seek happened" instead.
730 #[test]
731 fn only_a_started_stream_can_be_late() {
732 let ring = Ring::new(4);
733 let flush = AtomicBool::new(false);
734 let primed = AtomicBool::new(false);
735
736 // The open: callbacks may run before the first write, and there is
737 // nothing to be late for yet.
738 assert!(!primed.load(Ordering::Acquire), "primed before a sample");
739 assert_eq!(accept(&flush, &ring, &primed, &[1.0, 2.0]), 2);
740 assert!(
741 primed.load(Ordering::Acquire),
742 "a queued sample is a stream that can fall behind"
743 );
744
745 // A seek: `ao_flush` unprimes, and the head of the new stream -- the
746 // decoder open, seconds on a cold film -- is not counted...
747 primed.store(false, Ordering::Release);
748 flush.store(true, Ordering::Release);
749 let mut out = [0u8; 16];
750 assert_eq!(consume(&flush, &ring, &mut out, 2), 0, "the flush landed");
751 assert!(!primed.load(Ordering::Acquire), "the restart counts as late");
752
753 // ...until its own first sample lands, from where it counts again --
754 // which is also what makes the tail work: `ao_stream_ended` unprimes
755 // the same flag when the decoder is done, and only a write can prime it
756 // again.
757 assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 2);
758 assert!(primed.load(Ordering::Acquire), "the new stream is running");
759 }
760
761 #[test]
762 fn ring_wraps_fills_and_starves() {
763 let ring = Ring::new(4);
764 let mut out = [0u8; 24];
765
766 // Short write, then read it back as little-endian f32.
767 assert_eq!(ring.push(&[1.0, 2.0]), 2);
768 assert_eq!(ring.pop(&mut out, 2), 2);
769 assert_eq!(&out[..4], &1.0f32.to_le_bytes());
770 assert_eq!(&out[4..8], &2.0f32.to_le_bytes());
771
772 // Full ring accepts only what fits, and the tail wraps the mask.
773 assert_eq!(ring.push(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), 4);
774 assert_eq!(ring.push(&[9.0]), 0);
775 assert_eq!(ring.pop(&mut out, 6), 4);
776 assert_eq!(&out[12..16], &4.0f32.to_le_bytes());
777
778 // Empty ring starves instead of replaying stale samples.
779 assert_eq!(ring.pop(&mut out, 4), 0);
780 }
781
782 #[test]
783 fn flush_drops_queued_samples() {
784 let ring = Ring::new(4);
785 let flush = AtomicBool::new(false);
786 let mut out = [0u8; 16];
787
788 // No flush pending: an ordinary pop.
789 assert_eq!(ring.push(&[1.0, 2.0]), 2);
790 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
791
792 // Flushed: the queued samples are gone, so the callback gets nothing
793 // and fills silence, and the flag is one-shot.
794 assert_eq!(ring.push(&[3.0, 4.0]), 2);
795 flush.store(true, Ordering::Release);
796 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
797 assert!(!flush.load(Ordering::Acquire));
798
799 // Ring is empty, not corrupt: the next write plays as usual.
800 assert_eq!(ring.push(&[5.0, 6.0, 7.0, 8.0]), 4);
801 assert_eq!(consume(&flush, &ring, &mut out, 4), 4);
802 assert_eq!(&out[..4], &5.0f32.to_le_bytes());
803 assert_eq!(&out[12..16], &8.0f32.to_le_bytes());
804 }
805}