Skip to main content

moq_audio/playback/
sink.rs

1//! [`Sink`]: one stream of PCM on its way to the speaker.
2
3use std::pin::Pin;
4use std::sync::atomic::{AtomicU8, Ordering};
5use std::sync::mpsc::{SyncSender, TrySendError};
6use std::sync::{Arc, Mutex};
7use std::task::{Context, Poll};
8use std::time::Duration;
9
10use kio::clock::Instant;
11
12use super::driver::Shared;
13use super::mixer::{self, Gain};
14use crate::resample::Remix;
15use crate::ring::{self, Push};
16use crate::{Error, Format, Layout};
17
18/// Default for [`Input::latency`]: audio buffered between [`Sink::write`] and
19/// the speaker.
20///
21/// This is the price of surviving jitter: the device pulls on a fixed clock, so
22/// a late write is a dropout. 50 ms rides out a stalled network read without
23/// being audible as delay.
24const LATENCY: Duration = Duration::from_millis(50);
25
26/// Headroom above [`Input::latency`]. A writer that runs ahead (a decoder
27/// catching up after a pause) parks samples here instead of losing them.
28const HEADROOM: Duration = Duration::from_secs(3);
29
30/// The PCM layout a [`Sink`] accepts.
31///
32/// The playback counterpart to [`encode::Input`](crate::encode::Input): it
33/// describes the buffers you hand in, not the device, which is free to run at
34/// its own rate and layout.
35///
36/// `#[non_exhaustive]`: construct via [`Input::default`] and set fields, so new
37/// options can be added without breaking callers.
38#[derive(Clone, Debug)]
39#[non_exhaustive]
40pub struct Input {
41	/// How samples are packed in each buffer.
42	pub format: Format,
43	/// Samples per second per channel. Resampled to the device rate if they
44	/// differ.
45	pub sample_rate: u32,
46	/// Speaker meaning and channel order. Remixed to the device's layout, so it
47	/// must name speaker positions rather than be [`Layout::Discrete`].
48	pub layout: Layout,
49
50	/// How much audio to hold between [`Sink::write`] and the speaker (default:
51	/// 50 ms).
52	///
53	/// The device pulls on its own clock, so this is the jitter a late write may
54	/// absorb without a dropout, and it is also delay: the sample handed over now
55	/// sounds this much later. A player that presents video against a playout
56	/// delay sets this to match, so the sink is where that delay lives rather
57	/// than something the picture has to be held back for separately. Once a
58	/// clock is [`due`](Sink::due), the device's own delay counts toward it and
59	/// the sink holds the rest. Must be non-zero: a ring with no depth can never
60	/// be read from.
61	pub latency: Duration,
62}
63
64impl Default for Input {
65	fn default() -> Self {
66		Self {
67			format: Format::F32,
68			sample_rate: 48_000,
69			layout: Layout::Stereo,
70			latency: LATENCY,
71		}
72	}
73}
74
75impl Input {
76	fn validate(&self) -> Result<(), Error> {
77		if self.sample_rate == 0 {
78			return Err(Error::Unsupported("sample rate must be > 0".into()));
79		}
80		if self.layout.speakers().is_none() {
81			return Err(Error::Unsupported(format!(
82				"playback needs speaker positions to remix (got {:?})",
83				self.layout
84			)));
85		}
86		if self.latency.is_zero() || self.latency > moq_mux::container::DELAY_MAX {
87			return Err(Error::Unsupported(format!(
88				"playback latency must be non-zero and at most {:?} (got {:?})",
89				moq_mux::container::DELAY_MAX,
90				self.latency
91			)));
92		}
93		Ok(())
94	}
95}
96
97/// The sample frames accepted and dropped by one [`Sink::write`].
98///
99/// A sample frame is one instant across all input channels, so one stereo
100/// frame counts once rather than twice.
101#[must_use = "inspect dropped_sample_frames; retrying dropped live audio adds latency"]
102#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
103#[non_exhaustive]
104pub struct Write {
105	/// Input sample frames accepted for playback.
106	pub accepted_sample_frames: usize,
107	/// Input sample frames dropped to keep playback live.
108	pub dropped_sample_frames: usize,
109}
110
111impl Write {
112	fn from_accepted(requested_sample_frames: usize, accepted_sample_frames: usize) -> Self {
113		Self {
114			accepted_sample_frames,
115			dropped_sample_frames: requested_sample_frames - accepted_sample_frames,
116		}
117	}
118}
119
120/// One stream of PCM being played, mixed with every other sink on the device.
121///
122/// Write decoded samples with [`write`](Self::write), then [`finish`](Self::finish)
123/// to play the tail or drop the sink to stop immediately.
124/// Writes are cheap and never block on the device: they remix to the device's
125/// layout and hand samples to a ring buffer that the audio thread drains on its
126/// own clock, resampling to the device rate on the way.
127pub struct Sink {
128	completion: Arc<Completion>,
129	drained: tokio::sync::oneshot::Receiver<()>,
130	id: u64,
131	input: Input,
132	channel: Arc<Mutex<Channel>>,
133	control: Control,
134	/// Whether the last write overflowed, so a writer that stays ahead of the
135	/// device logs once rather than on every write.
136	overflowing: bool,
137	shared: Arc<Shared>,
138	/// Keeps the driver thread running while this sink is alive, so dropping the
139	/// [`Engine`](super::Engine) that made it doesn't cut playback short.
140	engine: Arc<super::Handle>,
141}
142
143impl Sink {
144	/// Play every queued sample before leaving the mix.
145	///
146	/// Await the returned handle to wait for the device; dropping it stops
147	/// immediately. A device that is unavailable keeps the drain pending.
148	/// The wait includes staged stretch output and up to one resampler block
149	/// of trailing silence. A finished sink bypasses emergency refilling.
150	pub fn finish(self) -> Drain {
151		// Nothing follows the last write, so push the resampler's tail through
152		// and let the mixer play the silence behind it.
153		if !self.channel.lock().unwrap().prod.flush() {
154			tracing::warn!("audio playback overflow, cutting the final samples short");
155		}
156		self.completion.state.store(1, Ordering::Release);
157		Drain { sink: Some(self) }
158	}
159
160	/// Play `samples`, in the layout this sink was built with.
161	///
162	/// Samples play back to back in write order. Nothing is scheduled against a
163	/// clock here, so pace writes with [`buffered`](Self::buffered): it reports
164	/// how far ahead of the speaker you are, which is the anchor an A/V sync
165	/// clock steers video by.
166	///
167	/// Received audio is time-stretched toward the current latency, or toward
168	/// the clock [`due`](Self::due) anchors it to. A writer that outruns that
169	/// correction eventually overflows and drops the excess; one that leaves no
170	/// received audio underruns and plays silence. Both are logged and neither
171	/// is an error, since the next write can recover.
172	/// The returned [`Write`] counts input sample frames accepted and dropped;
173	/// dropped live audio should be observed for telemetry, not retried.
174	pub fn write(&mut self, samples: &[u8]) -> Result<Write, Error> {
175		let channels = self.input.layout.channels();
176		let pcm = self.input.format.as_interleaved_f32(samples, channels)?;
177		let requested_sample_frames = pcm.len() / channels as usize;
178
179		let mut channel = self.channel.lock().unwrap();
180		let mixed;
181		let pcm = match &channel.remix {
182			Some(remix) => {
183				mixed = remix.process(&pcm);
184				&mixed
185			}
186			None => pcm.as_ref(),
187		};
188
189		let accepted_sample_frames = match channel.prod.push(pcm) {
190			// NotReady means the device has not read yet, so these samples are
191			// dropped rather than queued to play late.
192			Push::Ok => {
193				self.overflowing = false;
194				requested_sample_frames
195			}
196			Push::NotReady => {
197				self.overflowing = false;
198				0
199			}
200			Push::Overflow { accepted } => {
201				// Once per spell, not once per write: a writer that stays ahead
202				// of the device would otherwise warn every frame for as long as
203				// it lasts.
204				if !self.overflowing {
205					tracing::warn!(accepted, "audio playback overflow, dropping samples");
206					self.overflowing = true;
207				}
208				accepted
209			}
210			Push::Padded { frames } => {
211				self.overflowing = false;
212				tracing::debug!(frames, "audio playback underflow, padded with silence");
213				requested_sample_frames
214			}
215		};
216
217		Ok(Write::from_accepted(requested_sample_frames, accepted_sample_frames))
218	}
219
220	/// Declare that the audio written so far is followed by a silence its
221	/// publisher announced, such as a push-to-talk mute.
222	///
223	/// Once that audio has played, the sink plays comfort noise at the level of
224	/// the quietest 20 ms it played, at most -60 dBFS, rather than running dry,
225	/// and the [`Observer`](super::Observer) counts no gap. That lasts until the
226	/// utterance [`resume`](Self::resume) starts plays. Writes before then, such
227	/// as a codec's final frames, continue the audio before the silence.
228	///
229	/// A player calls it at the decoder's [`Read::End`](crate::decode::Read::End),
230	/// the marker a publisher's [`discontinuity`](crate::encode::Producer::discontinuity)
231	/// sends. The sink plays on; [`finish`](Self::finish) is what ends it.
232	pub fn silence(&mut self) {
233		self.channel.lock().unwrap().prod.silence();
234	}
235
236	/// Start the next utterance after a declared silence with the next
237	/// [`write`](Self::write).
238	///
239	/// It plays one [`latency`](Input::latency) after that write, behind
240	/// whatever is still queued, with comfort noise filling the wait, the way a
241	/// new sink's first write plays behind its opening silence.
242	pub fn resume(&mut self) {
243		self.channel.lock().unwrap().prod.resume();
244	}
245
246	/// How much audio is queued between the last [`write`](Self::write) and the
247	/// speaker, the device's own delay included.
248	///
249	/// The pacing signal for A/V sync: the sample sounding right now was written
250	/// at roughly `last_timestamp - buffered()`, so a video clock can steer
251	/// against it. It settles near [`Input::latency`] once playback is running,
252	/// climbs when the writer runs ahead, and falls toward the device's delay
253	/// when it falls behind.
254	pub fn buffered(&self) -> Duration {
255		self.channel.lock().unwrap().prod.heard_in(crate::ring::host())
256	}
257
258	/// How long the device takes to sound what it reads: the delay its host
259	/// reports plus one device period. `None` until the device has called back.
260	///
261	/// A player holding a playout delay counts this in it, since the sink places
262	/// audio on [`due`](Self::due)'s clock where it is heard.
263	pub fn output_latency(&self) -> Option<Duration> {
264		self.shared.observe.output()
265	}
266
267	/// Set the playout target, converging by stretching received PCM.
268	///
269	/// This is the buffer the sink keeps against jitter, counting the device's
270	/// own delay: it slows down while what it holds runs short of it, and speeds up past it only to catch up
271	/// with the clock [`due`](Self::due) anchors it to.
272	///
273	/// Must be non-zero, at most [`moq_mux::container::DELAY_MAX`], and fit in the current
274	/// ring. Each device open or rebuild allocates the then-current target plus
275	/// three seconds, less a 30 ms processing window reserved as headroom.
276	/// Does not resize or reset the device.
277	pub fn set_latency(&mut self, latency: Duration) -> Result<(), Error> {
278		let mut input = self.input.clone();
279		input.latency = latency;
280		input.validate()?;
281		let mut channel = self.channel.lock().unwrap();
282		if !channel.prod.set_latency(latency) {
283			return Err(Error::Unsupported(
284				"playback latency exceeds the current ring capacity".into(),
285			));
286		}
287		self.input = input;
288		Ok(())
289	}
290
291	/// Anchor the audio written so far to the caller's clock: its end is due to
292	/// sound at `at`, as heard after the device's own delay.
293	///
294	/// The sink then plays onto that clock rather than at its latency alone:
295	/// behind it, it speeds up, and ahead of it, it slows down, at a rate
296	/// proportional to how far it is off, up to 10%. Audio about to run out
297	/// slows down too, falling behind the clock by at most `stretch`. Audio
298	/// trailing the clock by more than `stretch` skips onto it, and audio
299	/// leading it by as much waits in silence for it, however the clock moved.
300	/// A zero `stretch` turns the time stretch off: written audio plays
301	/// unaltered, and a sink more than a window off the clock skips onto it or
302	/// pads silence until the clock reaches it. Call it after each write and
303	/// whenever the clock moves; until the first call, or after the device
304	/// changes, the latency alone is the clock.
305	pub fn due(&mut self, at: Instant, stretch: Duration) {
306		// The device thread reads std's clock, so carry the distance from now
307		// over to it rather than the instant.
308		let (now, host) = (Instant::now(), crate::ring::host());
309		let at = match at.checked_duration_since(now) {
310			Some(ahead) => host + ahead,
311			None => host.checked_sub(now.duration_since(at)).unwrap_or(host),
312		};
313		self.channel.lock().unwrap().prod.due(at, stretch);
314	}
315
316	/// The PCM layout this sink was built with.
317	pub fn input(&self) -> &Input {
318		&self.input
319	}
320
321	/// This sink's volume and level, as a handle a UI thread can hold while a
322	/// decode task does the writing.
323	pub fn control(&self) -> Control {
324		self.control.clone()
325	}
326}
327
328impl Drop for Sink {
329	fn drop(&mut self) {
330		self.shared.remove(self.id);
331		// The mixer hands the retired sink back rather than dropping it on the
332		// audio thread, so somebody has to come collect it.
333		self.engine.wake();
334	}
335}
336
337/// A finished sink that stays in the mix until its queued samples have played.
338///
339/// Await it to release the sink after playback; dropping it stops immediately.
340#[must_use = "await the drain to play the sink's final samples"]
341pub struct Drain {
342	sink: Option<Sink>,
343}
344
345impl Future for Drain {
346	type Output = ();
347
348	fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<()> {
349		let Some(sink) = self.sink.as_mut() else {
350			return Poll::Ready(());
351		};
352		if Pin::new(&mut sink.drained).poll(cx).is_pending() {
353			return Poll::Pending;
354		}
355		self.sink.take();
356		Poll::Ready(())
357	}
358}
359
360/// Callback state is atomic; the driver delivers the async wake off the audio thread.
361pub(super) struct Completion {
362	// 0: writing, 1: finished, 2: played by the device.
363	state: AtomicU8,
364	commands: super::driver::Commands,
365}
366
367impl Completion {
368	pub(super) fn new(commands: super::driver::Commands) -> Self {
369		Self {
370			state: AtomicU8::new(0),
371			commands,
372		}
373	}
374
375	/// Whether the caller is still writing, rather than having finished.
376	pub(super) fn writing(&self) -> bool {
377		self.state.load(Ordering::Acquire) == 0
378	}
379
380	pub(super) fn played(&self, cons: &ring::Consumer) {
381		if self.state.load(Ordering::Acquire) == 1 && cons.available() == 0 {
382			self.state.store(2, Ordering::Release);
383			self.commands.sync();
384		}
385	}
386}
387
388/// A cheap, clonable handle to one [`Sink`]'s volume and level.
389///
390/// Everything here is a lone atomic, so it is safe to poll from a UI frame loop
391/// while the audio thread is mixing.
392#[derive(Clone, Debug)]
393pub struct Control {
394	gain: Arc<Gain>,
395}
396
397impl Control {
398	/// Set the playback volume, `0.0` (silent) to `1.0` (unchanged), clamped. A
399	/// non-finite volume is ignored rather than clamped, since NaN would ride
400	/// the ramp into every sample this sink contributes.
401	///
402	/// The change ramps in over a few milliseconds rather than landing on one
403	/// sample, so muting mid-stream does not click. A muted sink keeps
404	/// consuming its input: this is live audio, so it stays on the timeline
405	/// instead of queueing up and jumping ahead when it unmutes.
406	pub fn set_volume(&self, volume: f32) {
407		self.gain.set_volume(volume);
408	}
409
410	/// The volume last set. Defaults to `1.0`.
411	pub fn volume(&self) -> f32 {
412		self.gain.volume()
413	}
414
415	/// The loudest sample this sink contributed since the previous call, `0.0`
416	/// to `1.0`, after volume.
417	///
418	/// Reading resets it, so poll on the interval you want to display and do any
419	/// smoothing or dB conversion yourself.
420	pub fn peak(&self) -> f32 {
421		self.gain.peak()
422	}
423}
424
425/// The ring into the mixer and the remix that fills it, swapped together when
426/// the device changes rate or layout.
427struct Channel {
428	prod: ring::Producer,
429	/// Converts the sink's layout to the device's, when they differ.
430	remix: Option<Remix>,
431}
432
433/// A sink as the driver sees it: enough to rebuild its channel when the device
434/// changes underneath it.
435pub(super) struct Registration {
436	completion: Arc<Completion>,
437	drained: Option<tokio::sync::oneshot::Sender<()>>,
438	pub(super) id: u64,
439	/// The caller's rate, layout, and latency: the input side of the channel.
440	input: Input,
441	channel: Arc<Mutex<Channel>>,
442	gain: Arc<Gain>,
443	/// The consumer waiting to be handed to a mixer. Taken once it is attached,
444	/// and refilled by [`rebuild`](Self::rebuild). Boxed, since it moves
445	/// through the mixer's command channel by value.
446	pending: Option<Box<ring::Consumer>>,
447}
448
449impl Registration {
450	pub(super) fn complete(&mut self) {
451		if self.completion.state.load(Ordering::Acquire) == 2
452			&& let Some(reply) = self.drained.take()
453		{
454			let _ = reply.send(());
455		}
456	}
457
458	/// Whether the mixer has taken this sink's consumer.
459	pub(super) fn attached(&self) -> bool {
460		self.pending.is_none()
461	}
462
463	/// Hand the consumer to a running mixer, if it hasn't been already.
464	pub(super) fn attach(&mut self, mixer: &SyncSender<mixer::Command>) {
465		let Some(cons) = self.pending.take() else { return };
466
467		let command = mixer::Command::Add {
468			id: self.id,
469			cons,
470			gain: self.gain.clone(),
471			completion: self.completion.clone(),
472		};
473
474		if let Err(err) = mixer.try_send(command) {
475			// The mixer is backed up or gone. Keep the consumer so the next
476			// attach retries rather than leaving a silent sink forever.
477			let (TrySendError::Full(rejected) | TrySendError::Disconnected(rejected)) = err;
478			if let mixer::Command::Add { cons, .. } = rejected {
479				self.pending = Some(cons);
480			}
481		}
482	}
483
484	/// Re-create the channel for a device now running at `rate` in `bus`,
485	/// swapping the producer the caller's [`Sink`] writes into.
486	pub(super) fn rebuild(&mut self, rate: u32, bus: Layout) {
487		let mut current = self.channel.lock().unwrap();
488		let mut input = self.input.clone();
489		input.latency = current.prod.latency();
490		let (mut channel, cons) = channel(&input, rate, bus);
491		channel.prod.carry(&current.prod);
492		*current = channel;
493		self.pending = Some(Box::new(cons));
494	}
495}
496
497/// Build a sink and its registration. The device may not be open yet, in which
498/// case `rate` and `bus` are placeholders the driver replaces on the next
499/// rebuild.
500pub(super) fn new(
501	id: u64,
502	rate: u32,
503	bus: Layout,
504	input: Input,
505	shared: Arc<Shared>,
506	engine: Arc<super::Handle>,
507) -> Result<(Sink, Registration), Error> {
508	input.validate()?;
509
510	let (channel, cons) = self::channel(&input, rate, bus);
511	let channel = Arc::new(Mutex::new(channel));
512	let gain = Arc::new(Gain::new());
513
514	let completion = Arc::new(Completion::new(engine.commands.clone()));
515	let (reply, drained) = tokio::sync::oneshot::channel();
516	let sink = Sink {
517		completion: completion.clone(),
518		drained,
519		id,
520		input,
521		channel: channel.clone(),
522		control: Control { gain: gain.clone() },
523		overflowing: false,
524		shared,
525		engine,
526	};
527
528	let registration = Registration {
529		completion,
530		drained: Some(reply),
531		id,
532		input: sink.input.clone(),
533		channel,
534		gain,
535		pending: Some(Box::new(cons)),
536	};
537
538	Ok((sink, registration))
539}
540
541/// The ring buffer between a writer and the audio thread, remixing the caller's
542/// layout to the device's and resampling its rate to the device's.
543fn channel(input: &Input, rate: u32, bus: Layout) -> (Channel, ring::Consumer) {
544	let remix =
545		(input.layout != bus).then(|| Remix::new(input.layout, bus).expect("sink and bus layouts name their speakers"));
546
547	let (prod, cons) = ring::channel(
548		bus.channels() as usize,
549		input.sample_rate,
550		rate,
551		ring::Config {
552			latency: input.latency,
553			capacity: input.latency + HEADROOM,
554			correction: ring::Correction::Stretch,
555			comfort: true,
556		},
557	);
558	(Channel { prod, remix }, cons)
559}
560
561#[cfg(test)]
562mod tests {
563	use super::*;
564
565	#[test]
566	fn ring_allocation_follows_the_device_rate() {
567		let mut baseline = None;
568		for sample_rate in [44_100, 96_000, 4_000_000_000] {
569			let input = Input {
570				sample_rate,
571				layout: Layout::SevenPointOne,
572				..Default::default()
573			};
574			let (_, stats) = crate::allocation::measure(|| channel(&input, 48_000, Layout::Stereo));
575			let baseline = *baseline.get_or_insert(stats.bytes);
576			assert!(
577				stats.bytes <= baseline,
578				"{sample_rate} Hz allocated {} bytes, baseline {baseline}",
579				stats.bytes
580			);
581		}
582	}
583
584	fn sink(input: Input, output_rate: u32) -> (Sink, ring::Consumer) {
585		sink_into(input, output_rate, Layout::Stereo)
586	}
587
588	fn sink_into(input: Input, output_rate: u32, bus: Layout) -> (Sink, ring::Consumer) {
589		let shared = Arc::new(Shared::default());
590		let engine = Arc::new(super::super::Handle {
591			commands: super::super::driver::Commands::default(),
592		});
593		let (sink, mut registration) = new(0, output_rate, bus, input, shared, engine).unwrap();
594		(sink, *registration.pending.take().unwrap())
595	}
596
597	#[test]
598	fn finish_plays_the_partial_final_period_before_completing() {
599		let shared = Arc::new(Shared::default());
600		let engine = Arc::new(super::super::Handle {
601			commands: super::super::driver::Commands::default(),
602		});
603		let (mut sink, mut registration) = new(0, 48_000, Layout::Stereo, Input::default(), shared, engine).unwrap();
604		let (commands, rx) = std::sync::mpsc::sync_channel(8);
605		let (retired, _rx) = std::sync::mpsc::sync_channel(8);
606		let mut mixer = mixer::Mixer::new(rx, retired, 48_000, Layout::Stereo, Default::default()).unwrap();
607		registration.attach(&commands);
608		let mut out = [0.0f32; 960];
609		mixer.fill(&mut out, Duration::from_millis(100), crate::ring::host());
610		let samples = [0.25f32; 123 * 2];
611		let bytes: Vec<_> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
612		assert_eq!(sink.write(&bytes).unwrap().accepted_sample_frames, 123);
613		let mut drain = sink.finish();
614		let mut cx = Context::from_waker(std::task::Waker::noop());
615		assert!(Pin::new(&mut drain).poll(&mut cx).is_pending());
616		let mut heard = 0;
617		while heard < 123 * 2 {
618			mixer.fill(&mut out, Duration::from_millis(100), crate::ring::host());
619			heard += out.iter().filter(|s| **s == 0.25).count();
620			registration.complete();
621			assert!(Pin::new(&mut drain).poll(&mut cx).is_pending());
622		}
623		assert_eq!(heard, 123 * 2);
624		// Another staging chunk in the same callback does not finish the drain.
625		mixer.fill(&mut out, Duration::from_millis(100), crate::ring::host());
626		registration.complete();
627		assert!(Pin::new(&mut drain).poll(&mut cx).is_pending());
628		// Later callbacks can still run before the device plays its queued tail.
629		mixer.complete(Duration::from_millis(99));
630		registration.complete();
631		assert!(Pin::new(&mut drain).poll(&mut cx).is_pending());
632		mixer.complete(Duration::from_millis(100));
633		registration.complete();
634		assert!(Pin::new(&mut drain).poll(&mut cx).is_ready());
635	}
636
637	#[test]
638	fn a_writing_sink_running_dry_is_a_gap_and_a_finished_tail_plays_out() {
639		let shared = Arc::new(Shared::default());
640		let mut observer = super::super::Observer::new(shared.observe.clone()).unwrap();
641		let engine = Arc::new(super::super::Handle {
642			commands: super::super::driver::Commands::default(),
643		});
644		let input = Input {
645			latency: Duration::from_millis(1),
646			..Default::default()
647		};
648		let (mut sink, mut registration) = new(0, 48_000, Layout::Stereo, input, shared.clone(), engine).unwrap();
649		let (commands, rx) = std::sync::mpsc::sync_channel(8);
650		let (retired, _rx) = std::sync::mpsc::sync_channel(8);
651		let mut mixer = mixer::Mixer::new(rx, retired, 48_000, Layout::Stereo, shared.observe.clone()).unwrap();
652		registration.attach(&commands);
653		let mut out = [0.0; 1024];
654		mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
655		assert!(observer.read().unwrap().stalled, "nothing written yet");
656
657		let tone: Vec<_> = [0.25f32; 2048].iter().flat_map(|s| s.to_le_bytes()).collect();
658		let _ = sink.write(&tone).unwrap();
659		for _ in 0..4 {
660			mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
661		}
662		// Running dry waits for a 30 ms window and the device period to resume.
663		let refill: Vec<_> = [0.25f32; 2 * (1440 + 512)]
664			.iter()
665			.flat_map(|s| s.to_le_bytes())
666			.collect();
667		let _ = sink.write(&refill).unwrap();
668		mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
669		let observation = observer.read().unwrap();
670		assert!(!observation.stalled);
671		assert_eq!(observation.gaps.len(), 1, "the sink ran dry once: {observation:?}");
672
673		// A finished sink still plays its tail: no stall while it lasts.
674		let _drain = sink.finish();
675		mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
676		let observation = observer.read().unwrap();
677		assert!(!observation.stalled && observation.stalls.is_empty(), "{observation:?}");
678		let tail = observation.clock;
679
680		for _ in 0..4 {
681			mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
682		}
683		{
684			let mut cx = Context::from_waker(std::task::Waker::noop());
685			let mut finish = std::pin::pin!(observer.finish());
686			assert!(finish.as_mut().poll(&mut cx).is_pending());
687			mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
688			assert!(finish.as_mut().poll(&mut cx).is_ready());
689		}
690		// Once the tail runs out nothing plays. The gap where it ran out lands in
691		// the buffer before the stall, which the analyzer attributes to the stall.
692		let observation = observer.read().unwrap();
693		assert!(observation.stalled, "{observation:?}");
694		let ([gap], [stall]) = (&observation.gaps[..], &observation.stalls[..]) else {
695			panic!("one gap and one stall: {observation:?}");
696		};
697		let buffer = Duration::from_secs_f64(512.0 / 48_000.0);
698		assert!(stall.at >= tail, "{observation:?}");
699		assert!(gap.at <= stall.at && stall.at - gap.at < buffer, "{observation:?}");
700	}
701
702	/// A declared silence plays comfort noise at the level heard before it, through
703	/// the wait before the next utterance, which then plays one latency after its
704	/// first write. None of it is a gap or a stall.
705	#[test]
706	fn a_declared_silence_plays_comfort_noise_until_the_next_utterance() {
707		let shared = Arc::new(Shared::default());
708		let mut observer = super::super::Observer::new(shared.observe.clone()).unwrap();
709		let engine = Arc::new(super::super::Handle {
710			commands: super::super::driver::Commands::default(),
711		});
712		let latency = Duration::from_millis(40);
713		let input = Input {
714			latency,
715			..Default::default()
716		};
717		let (mut sink, mut registration) = new(0, 48_000, Layout::Stereo, input, shared.clone(), engine).unwrap();
718		let (commands, rx) = std::sync::mpsc::sync_channel(8);
719		let (retired, _rx) = std::sync::mpsc::sync_channel(8);
720		let mut mixer = mixer::Mixer::new(rx, retired, 48_000, Layout::Stereo, shared.observe.clone()).unwrap();
721		registration.attach(&commands);
722		let pcm = |sample: f32, frames: usize| -> Vec<u8> {
723			std::iter::repeat_n(sample.to_le_bytes(), frames * 2)
724				.flatten()
725				.collect()
726		};
727		let rms =
728			|samples: &[f32]| (samples.iter().map(|&s| s as f64 * s as f64).sum::<f64>() / samples.len() as f64).sqrt();
729		let mut out = [0.0f32; 960];
730		mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
731
732		// 100 ms of a quiet background, then a declared end.
733		let quiet = 0.0002;
734		let _ = sink.write(&pcm(quiet, 4_800)).unwrap();
735		sink.silence();
736		let mut heard = Vec::new();
737		for _ in 0..150 {
738			mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
739			heard.extend_from_slice(&out);
740		}
741		// The primed silence, the background, then a second of noise at its level.
742		let noise = &heard[heard.len() - 48_000 * 2..];
743		assert!(noise.iter().all(|s| s.abs() <= quiet * 3f32.sqrt() * 1.0001));
744		assert!((rms(noise) - quiet as f64).abs() < 0.00001, "rms {}", rms(noise));
745
746		// The next utterance plays one latency after its first write, with noise until then.
747		sink.resume();
748		let _ = sink.write(&pcm(0.5, 960)).unwrap();
749		let mut until = 0;
750		loop {
751			mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
752			if let Some(at) = out.iter().position(|s| *s == 0.5) {
753				until += at / 2;
754				break;
755			}
756			assert!(out.iter().all(|s| s.abs() <= quiet * 3f32.sqrt() * 1.0001 && *s != 0.0));
757			until += out.len() / 2;
758		}
759		assert_eq!(until, 48_000 * 40 / 1000);
760		for _ in 0..10 {
761			let _ = sink.write(&pcm(0.5, 480)).unwrap();
762			mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
763		}
764
765		let observation = observer.read().unwrap();
766		assert!(observation.gaps.is_empty(), "{observation:?}");
767		assert!(!observation.stalled && observation.stalls.len() == 1, "{observation:?}");
768
769		// Once the next utterance plays, running dry is a gap again.
770		for _ in 0..20 {
771			mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
772		}
773		let _ = sink.write(&pcm(0.5, 2_400)).unwrap();
774		mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
775		assert_eq!(observer.read().unwrap().gaps.len(), 1);
776	}
777
778	/// The resampler only converts whole blocks and its filter lags the input, so
779	/// a track whose rate differs from the device's must have its tail pushed
780	/// through on finish: both a partial final block and one that ends exactly on
781	/// a block boundary, where only the filter delay is owed.
782	#[test]
783	fn finish_plays_the_resampled_tail_before_completing() {
784		for frames in [1000, 2 * ring::CHUNK] {
785			let want = frames * 48_000 / 44_100;
786			let heard = play_resampled(frames);
787			assert!(heard.abs_diff(want) <= 1, "{frames} frames: heard {heard}, want {want}");
788		}
789	}
790
791	/// Write `frames` of a 44.1 kHz tone into a 48 kHz mixer, finish, and count
792	/// the frames heard before the drain completes.
793	fn play_resampled(frames: usize) -> usize {
794		let shared = Arc::new(Shared::default());
795		let engine = Arc::new(super::super::Handle {
796			commands: super::super::driver::Commands::default(),
797		});
798		let input = Input {
799			sample_rate: 44_100,
800			..Default::default()
801		};
802		let (mut sink, mut registration) = new(0, 48_000, Layout::Stereo, input, shared, engine).unwrap();
803		let (commands, rx) = std::sync::mpsc::sync_channel(8);
804		let (retired, _rx) = std::sync::mpsc::sync_channel(8);
805		let mut mixer = mixer::Mixer::new(rx, retired, 48_000, Layout::Stereo, Default::default()).unwrap();
806		registration.attach(&commands);
807		let mut out = [0.0f32; 960];
808		mixer.fill(&mut out, Duration::ZERO, crate::ring::host());
809
810		let bytes: Vec<_> = [0.25f32]
811			.repeat(frames * 2)
812			.iter()
813			.flat_map(|s| s.to_le_bytes())
814			.collect();
815		assert_eq!(sink.write(&bytes).unwrap().accepted_sample_frames, frames);
816		let mut drain = sink.finish();
817		let mut cx = Context::from_waker(std::task::Waker::noop());
818
819		// Count frames past half amplitude, where the resampled edges cross, so
820		// the count is the tone's duration at the device rate.
821		let mut heard = 0;
822		for period in 1..100 {
823			let now = Duration::from_millis(10 * period);
824			mixer.fill(&mut out, now, crate::ring::host());
825			mixer.complete(now);
826			registration.complete();
827			heard += out.iter().step_by(2).filter(|left| **left > 0.125).count();
828			if Pin::new(&mut drain).poll(&mut cx).is_ready() {
829				return heard;
830			}
831		}
832		panic!("the drain never completed, after {heard} frames");
833	}
834
835	/// Write `frame` repeated as `input` and read back what the bus got.
836	fn mix(input: Layout, bus: Layout, frame: &[f32]) -> Vec<f32> {
837		let input = Input {
838			layout: input,
839			..Default::default()
840		};
841		let (mut sink, mut cons) = sink_into(input, 48_000, bus);
842		let channels = bus.channels() as usize;
843		cons.read(&mut vec![0.0; channels]);
844
845		let pcm: Vec<u8> = frame.repeat(4800).iter().flat_map(|s| s.to_le_bytes()).collect();
846		assert_eq!(sink.write(&pcm).unwrap().dropped_sample_frames, 0);
847
848		let mut out = vec![0.0; 4800 * channels];
849		cons.read(&mut out);
850		out[out.len() - channels..].to_vec()
851	}
852
853	fn close(got: &[f32], want: &[f32]) {
854		assert_eq!(got.len(), want.len(), "{got:?} vs {want:?}");
855		for (g, w) in got.iter().zip(want) {
856			assert!((g - w).abs() < 1e-4, "{got:?} vs {want:?}");
857		}
858	}
859
860	/// A 5.1 track on a stereo device plays its downmix, center and surrounds
861	/// folded into the front pair at -3 dB.
862	#[test]
863	fn a_surround_sink_downmixes_into_a_stereo_bus() {
864		let h = std::f32::consts::FRAC_1_SQRT_2;
865		let got = mix(Layout::FivePointOne, Layout::Stereo, &[0.1, 0.2, 0.3, 0.4, 0.05, 0.06]);
866		close(&got, &[0.1 + h * 0.3 + h * 0.05, 0.2 + h * 0.3 + h * 0.06]);
867	}
868
869	/// A stereo track on a 5.1 device plays from the front pair alone.
870	#[test]
871	fn a_stereo_sink_fills_the_front_of_a_surround_bus() {
872		let got = mix(Layout::Stereo, Layout::FivePointOne, &[0.25, 0.75]);
873		close(&got, &[0.25, 0.75, 0.0, 0.0, 0.0, 0.0]);
874	}
875
876	fn s16(frames: usize, channels: usize) -> Vec<u8> {
877		vec![0; frames * channels * 2]
878	}
879
880	fn ready(cons: &mut ring::Consumer) {
881		cons.read(&mut [0.0; 2]);
882	}
883
884	#[test]
885	fn reports_output_not_ready_as_dropped() {
886		let input = Input {
887			format: Format::S16,
888			..Default::default()
889		};
890		let (mut sink, _cons) = sink(input, 48_000);
891
892		assert_eq!(
893			sink.write(&s16(10, 2)).unwrap(),
894			Write {
895				accepted_sample_frames: 0,
896				dropped_sample_frames: 10,
897			}
898		);
899	}
900
901	#[test]
902	fn reports_input_frame_units_through_conversion_and_resampling() {
903		let input = Input {
904			format: Format::S16,
905			sample_rate: 44_100,
906			layout: Layout::Mono,
907			..Default::default()
908		};
909		let (mut sink, mut cons) = sink(input, 48_000);
910		ready(&mut cons);
911
912		assert_eq!(
913			sink.write(&s16(441, 1)).unwrap(),
914			Write {
915				accepted_sample_frames: 441,
916				dropped_sample_frames: 0,
917			}
918		);
919	}
920
921	#[test]
922	fn reports_partial_acceptance_on_overflow() {
923		let input = Input {
924			format: Format::S16,
925			latency: Duration::from_millis(1),
926			..Default::default()
927		};
928		let (mut sink, mut cons) = sink(input, 48_000);
929		ready(&mut cons);
930		let requested = 4 * 48_000;
931
932		let write = sink.write(&s16(requested, 2)).unwrap();
933		assert!(write.accepted_sample_frames > 0);
934		assert!(write.dropped_sample_frames > 0);
935		assert_eq!(write.accepted_sample_frames + write.dropped_sample_frames, requested);
936	}
937
938	#[test]
939	fn keeps_invalid_input_distinct_from_dropping() {
940		let input = Input {
941			format: Format::S16,
942			..Default::default()
943		};
944		let (mut sink, _cons) = sink(input, 48_000);
945
946		assert!(matches!(sink.write(&[0]), Err(Error::Misaligned { .. })));
947	}
948
949	#[test]
950	fn rejects_layouts_it_cannot_mix() {
951		for layout in [
952			Layout::Discrete(2.try_into().unwrap()),
953			Layout::Discrete(6.try_into().unwrap()),
954		] {
955			let input = Input {
956				layout,
957				..Default::default()
958			};
959			assert!(matches!(input.validate(), Err(Error::Unsupported(_))), "{layout:?}");
960		}
961
962		let input = Input {
963			sample_rate: 0,
964			..Default::default()
965		};
966		assert!(matches!(input.validate(), Err(Error::Unsupported(_))));
967	}
968
969	#[test]
970	fn accepts_named_layouts() {
971		for layout in [
972			Layout::Mono,
973			Layout::Stereo,
974			Layout::FivePointOne,
975			Layout::SevenPointOne,
976		] {
977			let input = Input {
978				layout,
979				..Default::default()
980			};
981			input.validate().unwrap();
982		}
983	}
984
985	/// A ring with no depth can never be read from, and one deeper than the
986	/// device could ever drain is a delay nobody asked for.
987	#[test]
988	fn rejects_a_latency_it_cannot_buffer() {
989		for latency in [Duration::ZERO, moq_mux::container::DELAY_MAX + Duration::from_secs(1)] {
990			let input = Input {
991				latency,
992				..Default::default()
993			};
994			assert!(matches!(input.validate(), Err(Error::Unsupported(_))), "{latency:?}");
995		}
996
997		Input {
998			latency: moq_mux::container::DELAY_MAX,
999			..Default::default()
1000		}
1001		.validate()
1002		.unwrap();
1003	}
1004
1005	#[test]
1006	fn changing_target_is_bounded_and_survives_device_rebuild() {
1007		let shared = Arc::new(Shared::default());
1008		let engine = Arc::new(super::super::Handle {
1009			commands: super::super::driver::Commands::default(),
1010		});
1011		let (mut sink, mut registration) = new(0, 48_000, Layout::Stereo, Input::default(), shared, engine).unwrap();
1012		for latency in [
1013			Duration::ZERO,
1014			Duration::from_secs(4),
1015			moq_mux::container::DELAY_MAX + Duration::from_secs(1),
1016		] {
1017			assert!(sink.set_latency(latency).is_err());
1018			assert_eq!(sink.input().latency, LATENCY);
1019		}
1020		let latency = Duration::from_millis(120);
1021		sink.set_latency(latency).unwrap();
1022		assert_eq!(sink.input().latency, latency);
1023		registration.rebuild(44_100, Layout::Mono);
1024		assert_eq!(sink.channel.lock().unwrap().prod.latency(), latency);
1025		assert!(registration.pending.as_ref().unwrap().available() == 0);
1026	}
1027}