forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

lib.rs670 lines, 27.4 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//! ponytail: 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/// ponytail: 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, samples: &[f32]) -> usize {
127 if flush.load(Ordering::Acquire) {
128 return 0;
129 }
130 ring.push(samples)
131}
132
133fn consume(flush: &AtomicBool, ring: &Ring, dst: &mut [u8], want: usize) -> usize {
134 if flush.swap(false, Ordering::Acquire) {
135 ring.read
136 .store(ring.write.load(Ordering::Acquire), Ordering::Release);
137 }
138 ring.pop(dst, want)
139}
140
141/// Everything the RT thread and the caller's thread both touch.
142struct Shared {
143 ring: Ring,
144 /// Samples per channel played at the device, -1 until the first callback.
145 position: AtomicI64,
146 /// Set once the daemon has accepted the stream.
147 ready: AtomicBool,
148 /// Stream died (daemon gone, node removed); every later write fails.
149 dead: AtomicBool,
150 /// Asked for by `ao_flush`, honoured by the next process callback.
151 flush: AtomicBool,
152 /// Set by `ao_set_active(true)`, cleared by the next process callback: the
153 /// graph clock keeps ticking while the stream is inactive, and that time
154 /// was never played.
155 resumed: AtomicBool,
156 /// Output gain as f32 bits, 1.0 until the caller says otherwise. Read once
157 /// per callback on the RT thread, so it is an atomic rather than a lock.
158 gain: AtomicU32,
159 underruns: AtomicU64,
160}
161
162enum Ctl {
163 Active(bool),
164 Quit,
165}
166
167fn pw_init() {
168 // Refcounted inside libpipewire, but a plugin has no safe point to call
169 // `pw::deinit`, so we init exactly once and never tear down.
170 static INIT: OnceLock<()> = OnceLock::new();
171 INIT.get_or_init(pw::init);
172}
173
174/// Builds the stream, reports readiness through `ready`, then owns the PipeWire
175/// loop until told to quit. Everything PipeWire lives in this one frame: the
176/// smart pointers are `Rc`-flavoured and the borrow chain (listener -> stream ->
177/// core -> context -> loop) is what enforces the destruction order.
178fn run(
179 rate: u32,
180 channels: usize,
181 shared: Arc<Shared>,
182 ready: mpsc::Sender<()>,
183 ctl: mpsc::Receiver<Ctl>,
184) -> Result<(), pw::Error> {
185 pw_init();
186 let mainloop = pw::main_loop::MainLoopRc::new(None)?;
187 let context = pw::context::ContextRc::new(&mainloop, None)?;
188 // Fails synchronously when there is no daemon to talk to: the clean probe.
189 let core = context.connect_rc(None)?;
190
191 let stream = pw::stream::StreamBox::new(
192 &core,
193 "video-editor",
194 properties! {
195 *pw::keys::MEDIA_TYPE => "Audio",
196 *pw::keys::MEDIA_CATEGORY => "Playback",
197 // Deliberately no MEDIA_ROLE: the session manager keys saved stream
198 // volume/mute by media.role before anything else, so declaring
199 // "Movie" put us in one bucket with every other video player on the
200 // box -- a mute somebody set on one of them last month came back as
201 // "edith has no sound", with nothing in the app to undo it. Without
202 // a role we get our own bucket, keyed by name, and start audible.
203 // Restoring stays ON: it is also what initialises the channel
204 // volumes, and a stream that opts out of it comes up at -inf dB.
205 *pw::keys::AUDIO_CHANNELS => channels.to_string(),
206 // Asks the graph to schedule us at our own quantum, which is what
207 // keeps the fill below from under-delivering on a lazy sink.
208 *pw::keys::NODE_LATENCY => format!("{QUANTUM}/{rate}"),
209 },
210 )?;
211
212 let _listener = stream
213 .add_local_listener_with_user_data(())
214 .state_changed({
215 let shared = shared.clone();
216 move |_, (), _old, new| match new {
217 pw::stream::StreamState::Paused | pw::stream::StreamState::Streaming => {
218 shared.ready.store(true, Ordering::Relaxed)
219 }
220 pw::stream::StreamState::Error(_) | pw::stream::StreamState::Unconnected => {
221 shared.dead.store(true, Ordering::Relaxed)
222 }
223 pw::stream::StreamState::Connecting => {}
224 }
225 })
226 .process({
227 let shared = shared.clone();
228 let stride = 4 * channels;
229 // Graph ticks that elapsed while the stream was inactive, and the
230 // last raw reading they are measured against.
231 let (mut skew, mut last_raw) = (0i64, 0i64);
232 move |stream, ()| {
233 let Some(mut buffer) = stream.dequeue_buffer() else {
234 return;
235 };
236 let datas = buffer.datas_mut();
237 let Some(data) = datas.first_mut() else {
238 return;
239 };
240 let n_frames = match data.data() {
241 Some(slice) => {
242 // Only a quantum per callback, however big the buffer
243 // is: everything we queue here is latency the clock,
244 // the pause and a future seek all have to wait out.
245 let frames = (slice.len() / stride).min(QUANTUM as usize);
246 let want = frames * channels;
247 let got = consume(&shared.flush, &shared.ring, slice, want);
248 if got < want {
249 // Underrun: silence rather than stale samples, and
250 // the clock below keeps running -- the device plays
251 // that silence, so it really is elapsed time.
252 slice[got * 4..want * 4].fill(0);
253 shared.underruns.fetch_add(1, Ordering::Relaxed);
254 }
255 // After the fill, so the silence stays silent whatever
256 // the gain is, and the underrun count keeps meaning
257 // "the decoder was late" rather than "the user muted".
258 scale(
259 &mut slice[..want * 4],
260 f32::from_bits(shared.gain.load(Ordering::Relaxed)),
261 );
262 frames
263 }
264 None => 0,
265 };
266 let chunk = data.chunk_mut();
267 *chunk.offset_mut() = 0;
268 *chunk.stride_mut() = stride as _;
269 *chunk.size_mut() = (stride * n_frames) as _;
270
271 // The A/V master clock: what the device has actually played,
272 // which is the stream position minus everything still in flight.
273 if let Ok(time) = stream.time() {
274 let ticks = time.ticks() as i64 - time.delay();
275 let (num, denom) = (time.rate().num as i128, time.rate().denom as i128);
276 // `ticks` counts in the stream's own rate; convert to ours.
277 let played = if denom > 0 {
278 (ticks as i128 * num * rate as i128 / denom) as i64
279 } else {
280 ticks
281 };
282 // The graph clock runs whether or not this stream does, so a
283 // pause shows up here as a step. Nothing was played during
284 // it: fold it into the skew instead of the position, or the
285 // pause leaks into the caller's timeline.
286 if shared.resumed.swap(false, Ordering::Relaxed) {
287 skew += played - last_raw;
288 }
289 last_raw = played;
290 shared
291 .position
292 .store((played - skew).max(0), Ordering::Relaxed);
293 }
294 }
295 })
296 .register()?;
297
298 let mut audio_info = spa::param::audio::AudioInfoRaw::new();
299 audio_info.set_format(spa::param::audio::AudioFormat::F32LE);
300 audio_info.set_rate(rate);
301 audio_info.set_channels(channels as u32);
302 let mut position = [0; spa::param::audio::MAX_CHANNELS];
303 match channels {
304 1 => position[0] = libspa_sys::SPA_AUDIO_CHANNEL_MONO,
305 2 => {
306 position[0] = libspa_sys::SPA_AUDIO_CHANNEL_FL;
307 position[1] = libspa_sys::SPA_AUDIO_CHANNEL_FR;
308 }
309 // Anything else keeps UNKNOWN positions and lets the daemon map them.
310 _ => {}
311 }
312 audio_info.set_position(position);
313
314 let values: Vec<u8> = pw::spa::pod::serialize::PodSerializer::serialize(
315 std::io::Cursor::new(Vec::new()),
316 &pw::spa::pod::Value::Object(pw::spa::pod::Object {
317 type_: libspa_sys::SPA_TYPE_OBJECT_Format,
318 id: libspa_sys::SPA_PARAM_EnumFormat,
319 properties: audio_info.into(),
320 }),
321 )
322 .map_err(|_| pw::Error::CreationFailed)?
323 .0
324 .into_inner();
325 let mut params = [Pod::from_bytes(&values).ok_or(pw::Error::CreationFailed)?];
326
327 stream.connect(
328 spa::utils::Direction::Output,
329 None,
330 pw::stream::StreamFlags::AUTOCONNECT
331 | pw::stream::StreamFlags::MAP_BUFFERS
332 | pw::stream::StreamFlags::RT_PROCESS,
333 &mut params,
334 )?;
335
336 // `connect` only starts negotiation, so a bad format or a daemon that
337 // refuses us still shows up here rather than as silent nothing later.
338 let deadline = Instant::now() + READY_TIMEOUT;
339 while !shared.ready.load(Ordering::Relaxed) {
340 if shared.dead.load(Ordering::Relaxed) || Instant::now() >= deadline {
341 return Err(pw::Error::CreationFailed);
342 }
343 mainloop.loop_().iterate(pw::loop_::Timeout::Finite(POLL));
344 }
345 let _ = ready.send(());
346
347 // Driving the loop by hand instead of `mainloop.run()` + a PipeWire channel:
348 // loop callbacks must be `'static` and the stream borrows the core, so a
349 // callback cannot touch the stream. Iterating lets us call `set_active` from
350 // this very frame. With RT_PROCESS the audio callback runs on the RT thread
351 // regardless, so this loop only handles negotiation and control.
352 'run: loop {
353 mainloop.loop_().iterate(pw::loop_::Timeout::Finite(POLL));
354 loop {
355 match ctl.try_recv() {
356 Ok(Ctl::Active(active)) => {
357 let _ = stream.set_active(active);
358 }
359 // Disconnected means the session was dropped without a Quit.
360 Ok(Ctl::Quit) | Err(mpsc::TryRecvError::Disconnected) => break 'run,
361 Err(mpsc::TryRecvError::Empty) => break,
362 }
363 }
364 }
365 let _ = stream.disconnect();
366 Ok(())
367}
368
369struct Session {
370 shared: Arc<Shared>,
371 ctl: mpsc::Sender<Ctl>,
372 thread: Option<JoinHandle<()>>,
373}
374
375impl Drop for Session {
376 fn drop(&mut self) {
377 let _ = self.ctl.send(Ctl::Quit);
378 if let Some(thread) = self.thread.take() {
379 let _ = thread.join();
380 }
381 let underruns = self.shared.underruns.load(Ordering::Relaxed);
382 if underruns > 0 {
383 eprintln!("engine_audio: {underruns} underruns");
384 }
385 }
386}
387
388/// Opens a playback stream for `sample_rate` Hz, `channels` channels of
389/// interleaved f32. Returns null on any failure at all: no libpipewire, no
390/// daemon, an unusable format.
391#[unsafe(no_mangle)]
392pub extern "C" fn ao_open(sample_rate: u32, channels: u32) -> *mut c_void {
393 catch_unwind(AssertUnwindSafe(|| {
394 if !(8_000..=768_000).contains(&sample_rate)
395 || channels == 0
396 || channels as usize > spa::param::audio::MAX_CHANNELS
397 {
398 return std::ptr::null_mut();
399 }
400 pw_init();
401
402 let shared = Arc::new(Shared {
403 // One second of audio: enough that a stalled decoder is audible as
404 // an underrun rather than papered over by a huge buffer.
405 ring: Ring::new(sample_rate as usize * channels as usize),
406 position: AtomicI64::new(-1),
407 ready: AtomicBool::new(false),
408 dead: AtomicBool::new(false),
409 flush: AtomicBool::new(false),
410 resumed: AtomicBool::new(false),
411 gain: AtomicU32::new(1.0f32.to_bits()),
412 underruns: AtomicU64::new(0),
413 });
414 let (ready_tx, ready_rx) = mpsc::channel();
415 let (ctl_tx, ctl_rx) = mpsc::channel();
416 let thread = std::thread::spawn({
417 let shared = shared.clone();
418 move || {
419 if let Err(e) = run(sample_rate, channels as usize, shared, ready_tx, ctl_rx) {
420 eprintln!("engine_audio: {e}");
421 }
422 }
423 });
424
425 // A failed setup drops `ready_tx`, so this returns without waiting out
426 // the timeout; the timeout only covers a PipeWire call that blocks
427 // against its contract, and then we leave the thread to its own exit.
428 match ready_rx.recv_timeout(OPEN_TIMEOUT) {
429 Ok(()) => Box::into_raw(Box::new(Session {
430 shared,
431 ctl: ctl_tx,
432 thread: Some(thread),
433 })) as *mut c_void,
434 Err(_) => {
435 let _ = ctl_tx.send(Ctl::Quit);
436 std::ptr::null_mut()
437 }
438 }
439 }))
440 .unwrap_or(std::ptr::null_mut())
441}
442
443/// Queues up to `n` interleaved f32 samples, returning how many were accepted:
444/// short counts mean the ring is full. Never blocks. -1 once the stream is dead.
445///
446/// # Safety
447/// `session` must come from [`ao_open`] and `samples` must point at `n` f32s.
448#[unsafe(no_mangle)]
449pub unsafe extern "C" fn ao_write(session: *mut c_void, samples: *const f32, n: usize) -> isize {
450 catch_unwind(AssertUnwindSafe(|| {
451 if session.is_null() || samples.is_null() {
452 return -1;
453 }
454 // SAFETY: caller-guaranteed live session and `n` readable samples.
455 let session = unsafe { &*(session as *const Session) };
456 if session.shared.dead.load(Ordering::Relaxed) {
457 return -1;
458 }
459 let samples = unsafe { std::slice::from_raw_parts(samples, n) };
460 accept(&session.shared.flush, &session.shared.ring, samples) as isize
461 }))
462 .unwrap_or(-1)
463}
464
465/// Samples per channel actually played at the device, or -1 while unknown.
466///
467/// # Safety
468/// `session` must come from [`ao_open`].
469#[unsafe(no_mangle)]
470pub unsafe extern "C" fn ao_position(session: *mut c_void) -> i64 {
471 catch_unwind(AssertUnwindSafe(|| {
472 if session.is_null() {
473 return -1;
474 }
475 // SAFETY: caller-guaranteed live session.
476 let session = unsafe { &*(session as *const Session) };
477 session.shared.position.load(Ordering::Relaxed)
478 }))
479 .unwrap_or(-1)
480}
481
482/// Pauses (0) or resumes (non-zero) playback. Paused freezes the position.
483/// 0 on success, negative on failure.
484///
485/// # Safety
486/// `session` must come from [`ao_open`].
487#[unsafe(no_mangle)]
488pub unsafe extern "C" fn ao_set_active(session: *mut c_void, active: u32) -> i32 {
489 catch_unwind(AssertUnwindSafe(|| {
490 if session.is_null() {
491 return -1;
492 }
493 // SAFETY: caller-guaranteed live session.
494 let session = unsafe { &*(session as *const Session) };
495 if active != 0 {
496 session.shared.resumed.store(true, Ordering::Relaxed);
497 }
498 match session.ctl.send(Ctl::Active(active != 0)) {
499 Ok(()) => 0,
500 Err(_) => -1,
501 }
502 }))
503 .unwrap_or(-1)
504}
505
506/// Sets the output gain: 0.0 is silence, 1.0 is the samples as written. One
507/// knob for both the editor's volume and its mute -- mute is a gain of 0.0
508/// pushed down, and which of the two the user is looking at is the caller's
509/// business. Takes effect on the next callback (~23 ms), and the position keeps
510/// advancing throughout: this silences the output, it does not pause it.
511/// 0 on success, negative on failure or a gain that is not in `0.0..=1.0`.
512///
513/// # Safety
514/// `session` must come from [`ao_open`].
515#[unsafe(no_mangle)]
516pub unsafe extern "C" fn ao_set_volume(session: *mut c_void, gain: f32) -> i32 {
517 catch_unwind(AssertUnwindSafe(|| {
518 // A NaN would compare false against every bound and then multiply every
519 // sample into a NaN, which is a loud fault in a speaker: refuse it here,
520 // at the ABI, rather than let it reach the RT thread.
521 if session.is_null() || !(0.0..=1.0).contains(&gain) {
522 return -1;
523 }
524 // SAFETY: caller-guaranteed live session.
525 let session = unsafe { &*(session as *const Session) };
526 session.shared.gain.store(gain.to_bits(), Ordering::Relaxed);
527 0
528 }))
529 .unwrap_or(-1)
530}
531
532/// Drops every queued sample, so playback resumes from whatever is written
533/// next: what a seek needs. Takes effect on the next process callback (or the
534/// first one after a resume), and leaves the played position alone -- the
535/// device keeps counting, the caller re-bases against it.
536/// 0 on success, negative on failure.
537///
538/// # Safety
539/// `session` must come from [`ao_open`].
540#[unsafe(no_mangle)]
541pub unsafe extern "C" fn ao_flush(session: *mut c_void) -> i32 {
542 catch_unwind(AssertUnwindSafe(|| {
543 if session.is_null() {
544 return -1;
545 }
546 // SAFETY: caller-guaranteed live session.
547 let session = unsafe { &*(session as *const Session) };
548 session.shared.flush.store(true, Ordering::Release);
549 0
550 }))
551 .unwrap_or(-1)
552}
553
554/// Stops playback and releases the session. Safe to call with null.
555///
556/// # Safety
557/// `session` must come from [`ao_open`] and must not be used afterwards.
558#[unsafe(no_mangle)]
559pub unsafe extern "C" fn ao_close(session: *mut c_void) {
560 let _ = catch_unwind(AssertUnwindSafe(|| {
561 if !session.is_null() {
562 // SAFETY: pointer came from `Box::into_raw` in `ao_open`.
563 drop(unsafe { Box::from_raw(session as *mut Session) });
564 }
565 }));
566}
567
568#[cfg(test)]
569mod tests {
570 use super::{AtomicBool, Ordering, Ring, accept, consume, scale};
571
572 /// The gain is applied to the bytes the device is about to play, so silence
573 /// really is silence and a partial gain really is quieter -- and 1.0 must
574 /// leave the samples bit-identical, since that is every callback's path.
575 #[test]
576 fn gain_scales_the_samples_the_device_sees() {
577 let sample =
578 |bytes: &[u8], i: usize| f32::from_le_bytes(bytes[i..i + 4].try_into().unwrap());
579
580 let mut buf = Vec::new();
581 for v in [1.0f32, -0.5, 0.25] {
582 buf.extend_from_slice(&v.to_le_bytes());
583 }
584
585 // Unity is the no-op the common case walks through.
586 let untouched = buf.clone();
587 scale(&mut buf, 1.0);
588 assert_eq!(buf, untouched);
589
590 // Half volume, sign kept.
591 scale(&mut buf, 0.5);
592 assert_eq!(sample(&buf, 0), 0.5);
593 assert_eq!(sample(&buf, 4), -0.25);
594
595 // Mute is a gain of zero: every sample gone, none left ringing.
596 scale(&mut buf, 0.0);
597 assert!(buf.chunks_exact(4).all(|s| sample(s, 0) == 0.0));
598 }
599
600 /// The paused-seek ordering: a flush requested with no RT callbacks running
601 /// must not let the writer queue new audio behind the pending discard.
602 #[test]
603 fn pending_flush_refuses_writes_until_consumed() {
604 let ring = Ring::new(4);
605 let flush = AtomicBool::new(false);
606 let mut out = [0u8; 16];
607
608 // Stale pre-seek audio sits in the ring; a flush is requested while
609 // paused (no callback runs yet).
610 assert_eq!(accept(&flush, &ring, &[1.0, 2.0]), 2);
611 flush.store(true, Ordering::Release);
612
613 // The new stream's feeder tries to write: refused, ring untouched.
614 assert_eq!(accept(&flush, &ring, &[3.0, 4.0]), 0);
615
616 // First post-resume callback consumes the flag and drains the stale
617 // tail -- and ONLY the stale tail, because nothing was queued behind it.
618 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
619
620 // Writer unparks; the new audio flows intact.
621 assert_eq!(accept(&flush, &ring, &[3.0, 4.0]), 2);
622 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
623 assert_eq!(&out[..4], &3.0f32.to_le_bytes());
624 }
625
626 #[test]
627 fn ring_wraps_fills_and_starves() {
628 let ring = Ring::new(4);
629 let mut out = [0u8; 24];
630
631 // Short write, then read it back as little-endian f32.
632 assert_eq!(ring.push(&[1.0, 2.0]), 2);
633 assert_eq!(ring.pop(&mut out, 2), 2);
634 assert_eq!(&out[..4], &1.0f32.to_le_bytes());
635 assert_eq!(&out[4..8], &2.0f32.to_le_bytes());
636
637 // Full ring accepts only what fits, and the tail wraps the mask.
638 assert_eq!(ring.push(&[1.0, 2.0, 3.0, 4.0, 5.0, 6.0]), 4);
639 assert_eq!(ring.push(&[9.0]), 0);
640 assert_eq!(ring.pop(&mut out, 6), 4);
641 assert_eq!(&out[12..16], &4.0f32.to_le_bytes());
642
643 // Empty ring starves instead of replaying stale samples.
644 assert_eq!(ring.pop(&mut out, 4), 0);
645 }
646
647 #[test]
648 fn flush_drops_queued_samples() {
649 let ring = Ring::new(4);
650 let flush = AtomicBool::new(false);
651 let mut out = [0u8; 16];
652
653 // No flush pending: an ordinary pop.
654 assert_eq!(ring.push(&[1.0, 2.0]), 2);
655 assert_eq!(consume(&flush, &ring, &mut out, 2), 2);
656
657 // Flushed: the queued samples are gone, so the callback gets nothing
658 // and fills silence, and the flag is one-shot.
659 assert_eq!(ring.push(&[3.0, 4.0]), 2);
660 flush.store(true, Ordering::Release);
661 assert_eq!(consume(&flush, &ring, &mut out, 2), 0);
662 assert!(!flush.load(Ordering::Acquire));
663
664 // Ring is empty, not corrupt: the next write plays as usual.
665 assert_eq!(ring.push(&[5.0, 6.0, 7.0, 8.0]), 4);
666 assert_eq!(consume(&flush, &ring, &mut out, 4), 4);
667 assert_eq!(&out[..4], &5.0f32.to_le_bytes());
668 assert_eq!(&out[12..16], &8.0f32.to_le_bytes());
669 }
670}