moq_audio/playback.rs
1//! Play decoded PCM out a speaker, via [`cpal`] (CoreAudio / WASAPI / ALSA).
2//!
3//! The playback counterpart to `capture`, and where a
4// `capture` is deliberately not a doc link: the module is behind its own
5// feature, so a link to it fails the `-D warnings` rustdoc build of a
6// playback-only build (what `moq-cli`'s `play` enables).
7//! [`decode::Consumer`](crate::decode::Consumer) ends up:
8//!
9//! ```no_run
10//! # async fn example(mut audio: moq_audio::decode::Consumer) -> Result<(), moq_audio::Error> {
11//! use moq_audio::playback;
12//!
13//! let engine = playback::Engine::open(playback::Config::default()).await?;
14//! let mut input = playback::Input::default();
15//! input.sample_rate = audio.sample_rate();
16//! input.layout = audio.layout();
17//!
18//! let mut sink = engine.sink(input)?;
19//!
20//! while let Some(event) = audio.read().await? {
21//! let moq_audio::decode::Read::Frame(frame) = event else { continue };
22//! let write = sink.write(&frame.data)?;
23//! if write.dropped_sample_frames > 0 {
24//! eprintln!("dropped {} live audio frames", write.dropped_sample_frames);
25//! }
26//! }
27//! sink.finish().await;
28//! # Ok(())
29//! # }
30//! ```
31//!
32//! [`Engine`] owns the output device and [`Sink`] is one stream playing through
33//! it. That split is deliberate: a call with several participants mixes into one
34//! device stream rather than opening one per speaker, which is what the device
35//! wants and what echo cancellation will need a single mixed reference from.
36//!
37//! The device is not the caller's problem. Opening it, renegotiating its format,
38//! resampling to its rate, and reopening it after it disappears all happen on a
39//! driver thread behind [`Engine`]; a [`Sink`] keeps taking writes throughout,
40//! and its samples land wherever the device currently is.
41
42mod device;
43mod driver;
44mod mixer;
45mod observe;
46mod sink;
47
48use std::sync::Arc;
49
50pub use device::{Device, devices};
51pub use observe::{Gap, Observation, Observer, Stall};
52pub use sink::{Control, Drain, Input, Sink, Write};
53
54#[cfg(all(feature = "capture", feature = "playback"))]
55pub(crate) use driver::Shared;
56#[cfg(all(feature = "capture", feature = "playback"))]
57pub(crate) use mixer::REFERENCE_CHANNELS;
58
59use crate::Error;
60
61/// Playback configuration.
62///
63/// `#[non_exhaustive]`: construct via [`Config::default`] and set fields, so new
64/// options can be added without breaking callers.
65#[derive(Clone, Debug, Default)]
66#[non_exhaustive]
67pub struct Config {
68 /// Output device, by the id [`devices`] reports. `None` opens the system
69 /// default.
70 pub device: Option<String>,
71}
72
73/// An open output device, mixing up to 64 [`Sink`]s into it.
74///
75/// Cheap to clone; every clone drives the same device. The device closes once
76/// the last clone and the last [`Sink`] are dropped.
77#[derive(Clone)]
78pub struct Engine {
79 shared: Arc<driver::Shared>,
80 handle: Arc<Handle>,
81}
82
83/// The driver thread's lifeline, shared by every [`Engine`] clone and every
84/// [`Sink`]. Dropping the last one shuts the thread down and closes the device,
85/// which is why a `Sink` outliving its `Engine` still plays.
86pub(crate) struct Handle {
87 commands: driver::Commands,
88}
89
90impl Handle {
91 /// Nudge the driver to collect retired sinks and retry anything the mixer's
92 /// command queue was too full to take.
93 pub(crate) fn wake(&self) {
94 self.commands.sync();
95 }
96}
97
98impl Drop for Handle {
99 fn drop(&mut self) {
100 self.commands.shutdown();
101 }
102}
103
104impl Engine {
105 /// Open the output device described by `config`.
106 ///
107 /// Fails if there is no such device, or none at all. Later failures are the
108 /// driver's problem, not the caller's: it reopens the device with backoff
109 /// and existing sinks pick up where they left off.
110 pub async fn open(config: Config) -> Result<Self, Error> {
111 let (commands, requests) = driver::channel();
112 let (opened, ready) = tokio::sync::oneshot::channel();
113
114 let shared = Arc::new(driver::Shared::default());
115 // The audio thread cannot wake the observer itself, so it asks the driver to.
116 shared.observe.wake_with(commands.clone());
117 // A canceller holds no `Handle`, so `Shared` is where it reaches the
118 // driver to ask for a retry.
119 #[cfg(all(feature = "capture", feature = "playback"))]
120 shared.wake_with(commands.clone());
121
122 let engine = Self {
123 handle: Arc::new(Handle {
124 commands: commands.clone(),
125 }),
126 shared: shared.clone(),
127 };
128
129 // Everything slow or fallible about the device happens here, off the async
130 // runtime: opening it, switching it, and rebuilding it after an error.
131 std::thread::Builder::new()
132 .name("moq-audio-playback".into())
133 .spawn(move || driver::run(requests, commands, shared, config.device, opened))
134 .map_err(|err| Error::Playback(format!("cannot spawn the playback thread: {err}")))?;
135
136 ready
137 .await
138 .map_err(|_| Error::Playback("the playback thread stopped".into()))??;
139
140 Ok(engine)
141 }
142
143 /// Add a stream to the mix, taking PCM in the layout `input` describes.
144 ///
145 /// Independent of the device: several sinks can play at different rates and
146 /// layouts, and each is resampled and remixed to the device's on its way to
147 /// the mix. One device
148 /// mixes up to 64 of them, past which this returns an error rather than
149 /// handing back a sink that plays nothing.
150 pub fn sink(&self, input: Input) -> Result<Sink, Error> {
151 let sink = self
152 .shared
153 .add(|id, rate, bus| sink::new(id, rate, bus, input, self.shared.clone(), self.handle.clone()))?;
154
155 // Covers the case where the mixer's command queue was momentarily full,
156 // so a sink is never left silently unmixed.
157 self.handle.wake();
158 Ok(sink)
159 }
160
161 /// Watch what this engine plays: every buffer the device pulls, counted in
162 /// 128-frame quanta on the audio thread without blocking it.
163 ///
164 /// Returns [`Error::Busy`] while another observer from this engine is alive.
165 pub fn observe(&self) -> Result<Observer, Error> {
166 Observer::new(self.shared.observe.clone())
167 }
168
169 /// Build echo-cancellation controls for this engine and one microphone.
170 ///
171 /// Hand a clone to [`capture::Config::aec`](crate::capture::Config::aec) and
172 /// keep another for UI toggles. Only one control set can own this engine's
173 /// reference; a second call returns [`Error::Busy`] until every control and
174 /// microphone attachment from the first is dropped.
175 ///
176 /// Requires the `capture` and `playback` features.
177 #[cfg(all(feature = "capture", feature = "playback"))]
178 pub fn canceller(&self, config: crate::aec::Config) -> Result<crate::aec::Control, Error> {
179 crate::aec::Control::new(self.shared.clone(), config)
180 }
181
182 /// Move playback to the device `config` names, or back to the system default
183 /// when [`Config::device`] is `None`.
184 ///
185 /// Takes the same [`Config`] as [`open`](Self::open) rather than a bare
186 /// device id, so a future playback option applies to a switch without
187 /// changing this signature.
188 ///
189 /// Sinks survive the move: they keep the same handles and resample to the
190 /// new device's rate. Returns an error, and stays on no device, if the
191 /// requested one can't be opened. Also returns immediately with an error if
192 /// the driver already has its bounded maximum of switches waiting.
193 pub async fn switch(&self, config: Config) -> Result<(), Error> {
194 let (reply, response) = tokio::sync::oneshot::channel();
195 self.handle.commands.switch(config.device, reply)?;
196
197 response
198 .await
199 .map_err(|_| Error::Playback("the playback thread stopped".into()))?
200 }
201}