forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

lib.rs808 lines, 34.0 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 std::env::var_os("VE_NO_AO").is_some_and(|v| v == "1") {
430 return std::ptr::null_mut();
431 }
432 if !(8_000..=768_000).contains(&sample_rate)
433 || channels == 0
434 || channels as usize > spa::param::audio::MAX_CHANNELS
435 {
436 return std::ptr::null_mut();
437 }
438 pw_init();
439
440 let shared = Arc::new(Shared {
441 // One second of audio: enough that a stalled decoder is audible as
442 // an underrun rather than papered over by a huge buffer.
443 ring: Ring::new(sample_rate as usize * channels as usize),
444 position: AtomicI64::new(-1),
445 ready: AtomicBool::new(false),
446 dead: AtomicBool::new(false),
447 flush: AtomicBool::new(false),
448 resumed: AtomicBool::new(false),
449 gain: AtomicU32::new(1.0f32.to_bits()),
450 // Nothing has been queued yet, so the callbacks between the connect
451 // and the caller's first write have nothing to be late for.
452 primed: AtomicBool::new(false),
453 underruns: AtomicU64::new(0),
454 last_underrun: AtomicI64::new(-1),
455 });
456 let (ready_tx, ready_rx) = mpsc::channel();
457 let (ctl_tx, ctl_rx) = mpsc::channel();
458 let thread = std::thread::spawn({
459 let shared = shared.clone();
460 move || {
461 if let Err(e) = run(sample_rate, channels as usize, shared, ready_tx, ctl_rx) {
462 eprintln!("engine_audio: {e}");
463 }
464 }
465 });
466
467 // A failed setup drops `ready_tx`, so this returns without waiting out
468 // the timeout; the timeout only covers a PipeWire call that blocks
469 // against its contract, and then we leave the thread to its own exit.
470 match ready_rx.recv_timeout(OPEN_TIMEOUT) {
471 Ok(()) => Box::into_raw(Box::new(Session {
472 shared,
473 ctl: ctl_tx,
474 thread: Some(thread),
475 })) as *mut c_void,
476 Err(_) => {
477 let _ = ctl_tx.send(Ctl::Quit);
478 std::ptr::null_mut()
479 }
480 }
481 }))
482 .unwrap_or(std::ptr::null_mut())
483}
484
485/// Queues up to `n` interleaved f32 samples, returning how many were accepted:
486/// short counts mean the ring is full. Never blocks. -1 once the stream is dead.
487///
488/// # Safety
489/// `session` must come from [`ao_open`] and `samples` must point at `n` f32s.
490#[unsafe(no_mangle)]
491pub unsafe extern "C" fn ao_write(session: *mut c_void, samples: *const f32, n: usize) -> isize {
492 catch_unwind(AssertUnwindSafe(|| {
493 if session.is_null() || samples.is_null() {
494 return -1;
495 }
496 // SAFETY: caller-guaranteed live session and `n` readable samples.
497 let session = unsafe { &*(session as *const Session) };
498 if session.shared.dead.load(Ordering::Relaxed) {
499 return -1;
500 }
501 let samples = unsafe { std::slice::from_raw_parts(samples, n) };
502 accept(
503 &session.shared.flush,
504 &session.shared.ring,
505 &session.shared.primed,
506 samples,
507 ) as isize
508 }))
509 .unwrap_or(-1)
510}
511
512/// Samples per channel actually played at the device, or -1 while unknown.
513///
514/// # Safety
515/// `session` must come from [`ao_open`].
516#[unsafe(no_mangle)]
517pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 {
518 catch_unwind(AssertUnwindSafe(|| {
519 if session.is_null() {
520 return -1;
521 }
522 // SAFETY: caller-guaranteed live session.
523 let session = unsafe { &*(session as *const Session) };
524 session.shared.position.load(Ordering::Relaxed)
525 }))
526 .unwrap_or(-1)
527}
528
529/// Says the caller has queued the last sample this stream will ever have.
530/// What is still in the ring plays out untouched -- this is not a flush and not
531/// a pause -- but the silence *after* it stops being counted as a late decoder:
532/// there is no decoder left to be late ([`Shared::primed`]). The next accepted
533/// write is a stream again and counts again. 0 on success.
534///
535/// # Safety
536/// `session` must come from [`ao_open`].
537#[unsafe(no_mangle)]
538pub unsafe extern "C" fn ao_stream_ended(session: *mut c_void) -> i32 {
539 catch_unwind(AssertUnwindSafe(|| {
540 if session.is_null() {
541 return -1;
542 }
543 // SAFETY: caller-guaranteed live session.
544 let session = unsafe { &*(session as *const Session) };
545 session.shared.primed.store(false, Ordering::Release);
546 0
547 }))
548 .unwrap_or(-1)
549}
550
551/// Starved callbacks since the stream opened -- one per quantum the decoder was
552/// late for -- and, through `last_at`, the device position the newest of them
553/// was seen at (`-1` if there has been none). The same number the drop print
554/// reports, asked for while the session is still running: a caller measuring a
555/// seek reads it before and after and the difference is that seek's cost.
556///
557/// Two relaxed atomic loads, nothing else: the RT thread writes both and must
558/// never wait on a reader.
559///
560/// # Safety
561/// `session` must come from [`ao_open`]; `last_at` is either null or writable.
562#[unsafe(no_mangle)]
563pub unsafe extern "C" fn ao_underruns(session: *mut c_void, last_at: *mut i64) -> i64 {
564 catch_unwind(AssertUnwindSafe(|| {
565 if session.is_null() {
566 return -1;
567 }
568 // SAFETY: caller-guaranteed live session.
569 let session = unsafe { &*(session as *const Session) };
570 if !last_at.is_null() {
571 // SAFETY: caller-guaranteed writable, and it is a plain i64.
572 unsafe { *last_at = session.shared.last_underrun.load(Ordering::Relaxed) };
573 }
574 session.shared.underruns.load(Ordering::Relaxed) as i64
575 }))
576 .unwrap_or(-1)
577}
578
579/// Pauses (0) or resumes (non-zero) playback. Paused freezes the position.
580/// 0 on success, negative on failure.
581///
582/// # Safety
583/// `session` must come from [`ao_open`].
584#[unsafe(no_mangle)]
585pub unsafe extern "C" fn ao_set_active(session: *mut c_void, active: u32) -> i32 {
586 catch_unwind(AssertUnwindSafe(|| {
587 if session.is_null() {
588 return -1;
589 }
590 // SAFETY: caller-guaranteed live session.
591 let session = unsafe { &*(session as *const Session) };
592 if active != 0 {
593 session.shared.resumed.store(true, Ordering::Relaxed);
594 }
595 match session.ctl.send(Ctl::Active(active != 0)) {
596 Ok(()) => 0,
597 Err(_) => -1,
598 }
599 }))
600 .unwrap_or(-1)
601}
602
603/// Sets the output gain: 0.0 is silence, 1.0 is the samples as written. One
604/// knob for both the editor's volume and its mute -- mute is a gain of 0.0
605/// pushed down, and which of the two the user is looking at is the caller's
606/// business. Takes effect on the next callback (~23 ms), and the position keeps
607/// advancing throughout: this silences the output, it does not pause it.
608/// 0 on success, negative on failure or a gain that is not in `0.0..=1.0`.
609///
610/// # Safety
611/// `session` must come from [`ao_open`].
612#[unsafe(no_mangle)]
613pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 {
614 catch_unwind(AssertUnwindSafe(|| {
615 // A NaN would compare false against every bound and then multiply every
616 // sample into a NaN, which is a loud fault in a speaker: refuse it here,
617 // at the ABI, rather than let it reach the RT thread.
618 if session.is_null() || !(0.0..=1.0).contains(&gain) {
619 return -1;
620 }
621 // SAFETY: caller-guaranteed live session.
622 let session = unsafe { &*(session as *const Session) };
623 session.shared.gain.store(gain.to_bits(), Ordering::Relaxed);
624 0
625 }))
626 .unwrap_or(-1)
627}
628
629/// Drops every queued sample, so playback resumes from whatever is written
630/// next: what a seek needs. Takes effect on the next process callback (or the
631/// first one after a resume), and leaves the played position alone -- the
632/// device keeps counting, the caller re-bases against it.
633/// 0 on success, negative on failure.
634///
635/// # Safety
636/// `session` must come from [`ao_open`].
637#[unsafe(no_mangle)]
638pub unsafe extern "C" fn ao_flush(session: *mut c_void) -> i32 {
639 catch_unwind(AssertUnwindSafe(|| {
640 if session.is_null() {
641 return -1;
642 }
643 // SAFETY: caller-guaranteed live session.
644 let session = unsafe { &*(session as *const Session) };
645 // Unprimed first, so the callback that consumes the flag below cannot
646 // find an empty ring and count the head of the restart as a late
647 // decoder (`Shared::primed`).
648 session.shared.primed.store(false, Ordering::Release);
649 session.shared.flush.store(true, Ordering::Release);
650 0
651 }))
652 .unwrap_or(-1)
653}
654
655/// Stops playback and releases the session. Safe to call with null.
656///
657/// # Safety
658/// `session` must come from [`ao_open`] and must not be used afterwards.
659#[unsafe(no_mangle)]
660pub unsafe extern "C" fn ao_close(session: *mut c_void) {
661 let _ = catch_unwind(AssertUnwindSafe(|| {
662 if !session.is_null() {
663 // SAFETY: pointer came from `Box::into_raw` in `ao_open`.
664 drop(unsafe { Box::from_raw(session as *mut Session) });
665 }
666 }));
667}
668
669#[cfg(test)]
670mod tests {
671 use super::{AtomicBool, Ordering, Ring, accept, consume, scale};
672
673 /// The gain is applied to the bytes the device is about to play, so silence
674 /// really is silence and a partial gain really is quieter -- and 1.0 must
675 /// leave the samples bit-identical, since that is every callback's path.
676 #[test]
677 fn gain_scales_the_samples_the_device_sees() {
678 let sample =
679 |bytes: &[u8], i: usize| f32::from_le_bytes(bytes[i..i + 4].try_into().unwrap());
680
681 let mut buf = Vec::new();
682 for v in [1.0f32, -0.5, 0.25] {
683 buf.extend_from_slice(&v.to_le_bytes());
684 }
685
686 // Unity is the no-op the common case walks through.
687 let untouched = buf.clone();
688 scale(&mut buf, 1.0);
689 assert_eq!(buf, untouched);
690
691 // Half volume, sign kept.
692 scale(&mut buf, 0.5);
693 assert_eq!(sample(&buf, 0), 0.5);
694 assert_eq!(sample(&buf, 4), -0.25);
695
696 // Mute is a gain of zero: every sample gone, none left ringing.
697 scale(&mut buf, 0.0);
698 assert!(buf.chunks_exact(4).all(|s| sample(s, 0) == 0.0));
699 }
700
701 /// The paused-seek ordering: a flush requested with no RT callbacks running
702 /// must not let the writer queue new audio behind the pending discard.
703 #[test]
704 fn pending_flush_refuses_writes_until_consumed() {
705 let ring = Ring::new(4);
706 let flush = AtomicBool::new(false);
707 let primed = AtomicBool::new(false);
708 let mut out = [0u8; 16];
709
710 // Stale pre-seek audio sits in the ring; a flush is requested while
711 // paused (no callback runs yet).
712 assert_eq!(accept(&flush, &ring, &primed, &[1.0, 2.0]), 2);
713 flush.store(true, Ordering::Release);
714
715 // The new stream's feeder tries to write: refused, ring untouched.
716 assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 0);
717
718 // First post-resume callback consumes the flag and drains the stale
719 // tail -- and ONLY the stale tail, because nothing was queued behind it.
720 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
721
722 // Writer unparks; the new audio flows intact.
723 assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 2);
724 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
725 assert_eq!(&out[..4], &3.0f32.to_le_bytes());
726 }
727
728 /// What the underrun count is allowed to mean: a starved callback is a late
729 /// decoder only while a decoder is actually behind the ring. The head of a
730 /// restart (nothing queued since the flush) and the tail of a stream (the
731 /// decoder is done) are silence nobody is late for, and counting them made
732 /// the number say "a seek happened" instead.
733 #[test]
734 fn only_a_started_stream_can_be_late() {
735 let ring = Ring::new(4);
736 let flush = AtomicBool::new(false);
737 let primed = AtomicBool::new(false);
738
739 // The open: callbacks may run before the first write, and there is
740 // nothing to be late for yet.
741 assert!(!primed.load(Ordering::Acquire), "primed before a sample");
742 assert_eq!(accept(&flush, &ring, &primed, &[1.0, 2.0]), 2);
743 assert!(
744 primed.load(Ordering::Acquire),
745 "a queued sample is a stream that can fall behind"
746 );
747
748 // A seek: `ao_flush` unprimes, and the head of the new stream -- the
749 // decoder open, seconds on a cold film -- is not counted...
750 primed.store(false, Ordering::Release);
751 flush.store(true, Ordering::Release);
752 let mut out = [0u8; 16];
753 assert_eq!(consume(&flush, &ring, &mut out, 2), 0, "the flush landed");
754 assert!(!primed.load(Ordering::Acquire), "the restart counts as late");
755
756 // ...until its own first sample lands, from where it counts again --
757 // which is also what makes the tail work: `ao_stream_ended` unprimes
758 // the same flag when the decoder is done, and only a write can prime it
759 // again.
760 assert_eq!(accept(&flush, &ring, &primed, &[3.0, 4.0]), 2);
761 assert!(primed.load(Ordering::Acquire), "the new stream is running");
762 }
763
764 #[test]
765 fn ring_wraps_fills_and_starves() {
766 let ring = Ring::new(4);
767 let mut out = [0u8; 24];
768
769 // Short write, then read it back as little-endian f32.
770 assert_eq!(ring.push(&[1.0, 2.0]), 2);
771 assert_eq!(ring.pop(&mut out, 2), 2);
772 assert_eq!(&out[..4], &1.0f32.to_le_bytes());
773 assert_eq!(&out[4..8], &2.0f32.to_le_bytes());
774
775 // Full ring accepts only what fits, and the tail wraps the mask.
776 assert_eq!(ring.push(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), 4);
777 assert_eq!(ring.push(&[9.0]), 0);
778 assert_eq!(ring.pop(&mut out, 6), 4);
779 assert_eq!(&out[12..16], &4.0f32.to_le_bytes());
780
781 // Empty ring starves instead of replaying stale samples.
782 assert_eq!(ring.pop(&mut out, 4), 0);
783 }
784
785 #[test]
786 fn flush_drops_queued_samples() {
787 let ring = Ring::new(4);
788 let flush = AtomicBool::new(false);
789 let mut out = [0u8; 16];
790
791 // No flush pending: an ordinary pop.
792 assert_eq!(ring.push(&[1.0, 2.0]), 2);
793 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
794
795 // Flushed: the queued samples are gone, so the callback gets nothing
796 // and fills silence, and the flag is one-shot.
797 assert_eq!(ring.push(&[3.0, 4.0]), 2);
798 flush.store(true, Ordering::Release);
799 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
800 assert!(!flush.load(Ordering::Acquire));
801
802 // Ring is empty, not corrupt: the next write plays as usual.
803 assert_eq!(ring.push(&[5.0, 6.0, 7.0, 8.0]), 4);
804 assert_eq!(consume(&flush, &ring, &mut out, 4), 4);
805 assert_eq!(&out[..4], &5.0f32.to_le_bytes());
806 assert_eq!(&out[12..16], &8.0f32.to_le_bytes());
807 }
808}