1use 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
18const LATENCY: Duration = Duration::from_millis(50);
25
26const HEADROOM: Duration = Duration::from_secs(3);
29
30#[derive(Clone, Debug)]
39#[non_exhaustive]
40pub struct Input {
41 pub format: Format,
43 pub sample_rate: u32,
46 pub layout: Layout,
49
50 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#[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 pub accepted_sample_frames: usize,
107 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
120pub 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 overflowing: bool,
137 shared: Arc<Shared>,
138 engine: Arc<super::Handle>,
141}
142
143impl Sink {
144 pub fn finish(self) -> Drain {
151 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 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 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 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 pub fn silence(&mut self) {
233 self.channel.lock().unwrap().prod.silence();
234 }
235
236 pub fn resume(&mut self) {
243 self.channel.lock().unwrap().prod.resume();
244 }
245
246 pub fn buffered(&self) -> Duration {
255 self.channel.lock().unwrap().prod.heard_in(crate::ring::host())
256 }
257
258 pub fn output_latency(&self) -> Option<Duration> {
264 self.shared.observe.output()
265 }
266
267 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 pub fn due(&mut self, at: Instant, stretch: Duration) {
306 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 pub fn input(&self) -> &Input {
318 &self.input
319 }
320
321 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 self.engine.wake();
334 }
335}
336
337#[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
360pub(super) struct Completion {
362 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 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#[derive(Clone, Debug)]
393pub struct Control {
394 gain: Arc<Gain>,
395}
396
397impl Control {
398 pub fn set_volume(&self, volume: f32) {
407 self.gain.set_volume(volume);
408 }
409
410 pub fn volume(&self) -> f32 {
412 self.gain.volume()
413 }
414
415 pub fn peak(&self) -> f32 {
421 self.gain.peak()
422 }
423}
424
425struct Channel {
428 prod: ring::Producer,
429 remix: Option<Remix>,
431}
432
433pub(super) struct Registration {
436 completion: Arc<Completion>,
437 drained: Option<tokio::sync::oneshot::Sender<()>>,
438 pub(super) id: u64,
439 input: Input,
441 channel: Arc<Mutex<Channel>>,
442 gain: Arc<Gain>,
443 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 pub(super) fn attached(&self) -> bool {
460 self.pending.is_none()
461 }
462
463 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 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 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(¤t.prod);
492 *current = channel;
493 self.pending = Some(Box::new(cons));
494 }
495}
496
497pub(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
541fn 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 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 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 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 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 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 #[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 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 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 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 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 #[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 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 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 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 #[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 #[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 #[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}