Skip to main content

moq_audio/playback/
device.rs

1//! Finding an output device and agreeing on a stream format with it.
2
3use std::str::FromStr;
4
5use cpal::traits::{DeviceTrait, HostTrait};
6
7use crate::Error;
8
9/// Rates to ask for, best first. 48 kHz is what Opus and the rest of the
10/// pipeline run at, so matching it skips a resample; 44.1 kHz is the usual
11/// second choice.
12const RATES: &[u32] = &[48_000, 44_100];
13
14/// The widest channel count with a well-known layout. Wider counts name no
15/// speaker positions to mix into, so they are never opened.
16const MAX_CHANNELS: u16 = 8;
17
18/// Sample formats we can write, best first: `f32` is what the mixer produces,
19/// and the rest are conversions on the way out.
20///
21/// The filter matters as much as the order. A device that offers several
22/// formats (an ALSA `plughw:` node offers every format ALSA can convert to,
23/// starting at 8-bit) will happily hand back one we can't write if we pick on
24/// sample rate alone.
25const FORMATS: &[cpal::SampleFormat] = &[
26	cpal::SampleFormat::F32,
27	cpal::SampleFormat::I32,
28	cpal::SampleFormat::I16,
29	cpal::SampleFormat::U16,
30];
31
32/// An audio output reported by [`devices`].
33#[derive(Clone, Debug)]
34#[non_exhaustive]
35pub struct Device {
36	/// Opaque identifier: pass to [`Config::device`](super::Config) or
37	/// [`Engine::switch`](super::Engine::switch). Stable across runs and
38	/// reboots where the host API can manage it.
39	pub id: String,
40	/// Human-readable name, e.g. "Built-in Output".
41	pub name: String,
42	/// Whether this is the system default output.
43	///
44	/// True for at most one device: the preferred host's default. Another host's
45	/// default is that host's, not the system's.
46	pub default: bool,
47	/// The host API this device is reached through, e.g. "PipeWire" or "ALSA".
48	///
49	/// The same hardware is usually reachable through several, so a caller that
50	/// offers a choice groups by this.
51	pub host: String,
52}
53
54/// List the audio outputs, across every host API the platform offers.
55pub async fn devices() -> Result<Vec<Device>, Error> {
56	// cpal enumerates devices with blocking host I/O, so keep it off the
57	// runtime's worker threads.
58	tokio::task::spawn_blocking(list)
59		.await
60		.map_err(|err| Error::Playback(format!("audio host thread failed: {err}")))?
61}
62
63fn list() -> Result<Vec<Device>, Error> {
64	// Every host, not just the preferred one. The same hardware appears under
65	// each, and which one a caller wants is its decision: PipeWire and PulseAudio
66	// carry the server's own names and routing, ALSA reaches a device directly.
67	// `Device::host` is what lets a caller group or filter them.
68	let preferred = cpal::default_host().id();
69	let mut devices = Vec::new();
70	let mut seen = std::collections::HashSet::new();
71
72	for id in cpal::available_hosts() {
73		// A host that will not open takes every device on it with it, so say so:
74		// the symptom is a device missing from the listing with no other trace.
75		let host = match cpal::host_from_id(id) {
76			Ok(host) => host,
77			Err(err) => {
78				tracing::debug!(host = id.name(), error = %err, "skipping an audio host that would not open");
79				continue;
80			}
81		};
82		let default = host.default_output_device().and_then(|d| d.id().ok());
83
84		let outputs = match host.output_devices() {
85			Ok(outputs) => outputs,
86			Err(err) => {
87				tracing::debug!(host = id.name(), error = %err, "skipping a host that would not list its outputs");
88				continue;
89			}
90		};
91		for device in outputs {
92			let Ok(device_id) = device.id() else {
93				tracing::debug!(host = id.name(), "skipping an output device with no id");
94				continue;
95			};
96			// A sound server reports one id per stream, not per device.
97			if !seen.insert(device_id.to_string()) {
98				continue;
99			}
100			devices.push(Device {
101				// Only the preferred host's default is the system default; the
102				// others are that host's idea of one.
103				default: id == preferred && Some(&device_id) == default.as_ref(),
104				name: describe(&device, &device_id),
105				host: id.name().to_string(),
106				id: device_id.to_string(),
107			});
108		}
109	}
110
111	Ok(devices)
112}
113
114/// Open the device `selector` names, or the system default when it is `None`.
115pub(super) fn open(selector: Option<&str>) -> Result<cpal::Device, Error> {
116	let Some(selector) = selector else {
117		return cpal::default_host()
118			.default_output_device()
119			.ok_or_else(|| Error::Device("no default output device".into()));
120	};
121
122	// Ids are host-qualified ("alsa:hw:0,0"), so route to the host that issued
123	// this one rather than searching every host for a match.
124	let id = cpal::DeviceId::from_str(selector).map_err(|err| Error::Device(format!("{selector:?}: {err}")))?;
125	let host = cpal::host_from_id(id.host()).map_err(|err| Error::Device(format!("{selector:?}: {err}")))?;
126	host.device_by_id(&id)
127		.ok_or_else(|| Error::Device(format!("output device {selector:?} not found")))
128}
129
130/// Pick the stream format to open `device` with.
131///
132/// Only considers formats in [`FORMATS`] and well-known layouts, and prefers in
133/// that order: the device's own channel count, the widest layout, a rate the
134/// pipeline already runs at, then a format we write without converting. Failing
135/// the rates it takes the highest the device supports, since resampling down is
136/// kinder than resampling up.
137pub(super) fn negotiate(device: &cpal::Device) -> Result<cpal::SupportedStreamConfig, Error> {
138	let supported = device
139		.supported_output_configs()
140		.map_err(|err| Error::Playback(format!("cannot enumerate output configs: {err}")))?;
141
142	// What the device is set up for: a 5.1 HDMI sink reports six channels and a
143	// headset two. Taken first because a sound server's plugin also accepts
144	// every count up to its limit, where the widest would upmix a headset.
145	let native = device.default_output_config().ok().map(|config| config.channels());
146
147	choose(supported, native).ok_or_else(|| {
148		Error::Unsupported("output device offers no sample format and speaker layout we can write".into())
149	})
150}
151
152/// The buffer size to open `device` with.
153///
154/// Every host's default is a period-sized buffer except PulseAudio's, a
155/// two-second buffer the server fills in bursts: the device pulls four seconds
156/// ahead, and a new sink's writes are dropped until the next burst reads it.
157/// Ask PulseAudio for 20 ms periods, its own default request size, instead.
158#[cfg_attr(
159	not(all(
160		feature = "pulseaudio",
161		any(
162			target_os = "linux",
163			target_os = "dragonfly",
164			target_os = "freebsd",
165			target_os = "netbsd"
166		)
167	)),
168	expect(unused_variables, reason = "only the PulseAudio host needs a size")
169)]
170pub(super) fn buffer_size(device: &cpal::Device, supported: &cpal::SupportedStreamConfig) -> cpal::BufferSize {
171	// cpal has a PulseAudio host only on these targets; elsewhere the feature is a no-op.
172	#[cfg(all(
173		feature = "pulseaudio",
174		any(
175			target_os = "linux",
176			target_os = "dragonfly",
177			target_os = "freebsd",
178			target_os = "netbsd"
179		)
180	))]
181	if let (Ok(id), cpal::SupportedBufferSize::Range { min, max }) = (device.id(), supported.buffer_size())
182		&& id.host() == cpal::HostId::PulseAudio
183	{
184		return cpal::BufferSize::Fixed((supported.sample_rate() / 50).clamp(*min, *max));
185	}
186	cpal::BufferSize::Default
187}
188
189/// Pick the best of the stream configurations a device reports.
190///
191/// Split out from [`negotiate`] so it can be tested without a device: the
192/// preference order is three levels deep and the outermost exists to fix an
193/// audible bug.
194fn choose(
195	supported: impl Iterator<Item = cpal::SupportedStreamConfigRange>,
196	native: Option<u16>,
197) -> Option<cpal::SupportedStreamConfig> {
198	supported
199		.filter(|config| FORMATS.contains(&config.sample_format()))
200		.filter(|config| (1..=MAX_CHANNELS).contains(&config.channels()))
201		.min_by_key(|config| preference(config, native))
202		.map(|config| match preferred_rate(&config) {
203			Some(rate) => config.try_with_sample_rate(rate).expect("a rate the range covers"),
204			None => config.with_max_sample_rate(),
205		})
206}
207
208/// Rank a configuration against the ones this crate would rather have, lowest
209/// first.
210///
211/// One key rather than nested loops because the levels are not independent: a
212/// stereo device offering only 96 kHz has to beat a mono one offering 48 kHz,
213/// and a pass per channel count that gave up when neither preferred rate matched
214/// would hand that to the mono device and downmix. The channel count leads
215/// because a downmix is audible where a resample is not.
216fn preference(
217	config: &cpal::SupportedStreamConfigRange,
218	native: Option<u16>,
219) -> ((bool, std::cmp::Reverse<u16>), usize, std::cmp::Reverse<u32>, usize) {
220	let channels = (native != Some(config.channels()), std::cmp::Reverse(config.channels()));
221	let rate = match preferred_rate(config) {
222		Some(rate) => (RATES.iter().position(|r| *r == rate).expect("from RATES"), rate),
223		// Nothing we asked for, so take the most the device offers: resampling
224		// down is kinder than resampling up.
225		None => (RATES.len(), config.max_sample_rate()),
226	};
227	(
228		channels,
229		rate.0,
230		std::cmp::Reverse(rate.1),
231		rank(config.sample_format()),
232	)
233}
234
235/// The first rate in [`RATES`] this configuration covers, if any.
236fn preferred_rate(config: &cpal::SupportedStreamConfigRange) -> Option<u32> {
237	RATES
238		.iter()
239		.copied()
240		.find(|rate| config.min_sample_rate() <= *rate && *rate <= config.max_sample_rate())
241}
242
243/// Where `format` sits in [`FORMATS`], so a lower rank is a better format.
244///
245/// Unlisted formats sort last, which is what makes this usable as a tie-break
246/// against a device offering something we filtered out.
247fn rank(format: cpal::SampleFormat) -> usize {
248	FORMATS.iter().position(|f| *f == format).unwrap_or(FORMATS.len())
249}
250
251/// A human-readable name, falling back to the id when the host can't describe
252/// the device.
253fn describe(device: &cpal::Device, id: &cpal::DeviceId) -> String {
254	device
255		.description()
256		.map(|d| d.name().to_string())
257		.unwrap_or_else(|_| id.id().to_string())
258}
259
260#[cfg(test)]
261mod tests {
262	use cpal::{SampleFormat, SupportedBufferSize, SupportedStreamConfigRange};
263
264	use super::*;
265
266	fn range(channels: u16, rate: u32, format: SampleFormat) -> SupportedStreamConfigRange {
267		SupportedStreamConfigRange::new(channels, rate, rate, SupportedBufferSize::Unknown, format)
268	}
269
270	/// The bug this ordering exists for: an ALSA plugin node that lists mono
271	/// first would otherwise be opened in mono, downmixing a stereo broadcast on
272	/// the way to a stereo sink.
273	#[test]
274	fn stereo_wins_even_when_the_device_lists_mono_first() {
275		let chosen = choose(
276			[range(1, 48_000, SampleFormat::F32), range(2, 48_000, SampleFormat::F32)].into_iter(),
277			None,
278		)
279		.expect("a config");
280		assert_eq!(chosen.channels(), 2);
281	}
282
283	/// Preferring stereo must not refuse a device that has no stereo to offer.
284	#[test]
285	fn mono_is_taken_when_that_is_all_there_is() {
286		let chosen = choose([range(1, 48_000, SampleFormat::F32)].into_iter(), None).expect("a config");
287		assert_eq!(chosen.channels(), 1);
288	}
289
290	/// A surround-only sink opens at its own width rather than being refused.
291	#[test]
292	fn a_surround_only_device_opens() {
293		let chosen = choose([range(6, 48_000, SampleFormat::F32)].into_iter(), None).expect("a config");
294		assert_eq!(chosen.channels(), 6);
295	}
296
297	/// A 5.1 HDMI sink opens at six channels rather than being folded to stereo.
298	#[test]
299	fn six_channels_are_chosen_when_offered() {
300		let offered = || [range(2, 48_000, SampleFormat::F32), range(6, 48_000, SampleFormat::F32)].into_iter();
301		assert_eq!(choose(offered(), None).expect("a config").channels(), 6);
302		assert_eq!(choose(offered(), Some(6)).expect("a config").channels(), 6);
303	}
304
305	/// A sound server's plugin accepts every count up to its limit, so the
306	/// device's own count beats the widest: a headset stays at two rather than
307	/// being upmixed to 7.1 and folded back down by the server.
308	#[test]
309	fn the_native_count_beats_the_widest() {
310		let offered = (1..=8).map(|channels| range(channels, 48_000, SampleFormat::F32));
311		assert_eq!(choose(offered, Some(2)).expect("a config").channels(), 2);
312	}
313
314	/// Past 7.1 there is no convention naming the speakers, so there is nothing
315	/// to remix into.
316	#[test]
317	fn counts_without_a_layout_are_refused() {
318		assert!(choose([range(12, 48_000, SampleFormat::F32)].into_iter(), Some(12)).is_none());
319		let chosen = choose(
320			[
321				range(12, 48_000, SampleFormat::F32),
322				range(2, 48_000, SampleFormat::F32),
323			]
324			.into_iter(),
325			Some(12),
326		)
327		.expect("a config");
328		assert_eq!(chosen.channels(), 2);
329	}
330
331	/// Rate is preferred within a channel count, not across one: a stereo config
332	/// at an awkward rate beats a mono config at the pipeline's own rate,
333	/// because resampling is inaudible and a downmix is not.
334	#[test]
335	fn channels_outrank_the_sample_rate() {
336		let chosen = choose(
337			[range(1, 48_000, SampleFormat::F32), range(2, 44_100, SampleFormat::F32)].into_iter(),
338			None,
339		)
340		.expect("a config");
341		assert_eq!((chosen.channels(), chosen.sample_rate()), (2, 44_100));
342	}
343
344	/// Within a channel count and rate, take the format the mixer already
345	/// produces rather than one that costs a conversion.
346	#[test]
347	fn f32_is_preferred_over_a_format_we_convert_to() {
348		let chosen = choose(
349			[range(2, 48_000, SampleFormat::I16), range(2, 48_000, SampleFormat::F32)].into_iter(),
350			None,
351		)
352		.expect("a config");
353		assert_eq!(chosen.sample_format(), SampleFormat::F32);
354	}
355
356	/// A device offering only formats we cannot write is an error rather than a
357	/// stream that plays noise.
358	#[test]
359	fn a_device_we_cannot_write_to_is_rejected() {
360		assert!(choose([range(2, 48_000, SampleFormat::I8)].into_iter(), None).is_none());
361		assert!(choose(std::iter::empty(), None).is_none());
362	}
363
364	/// Channels lead even when neither preferred rate is on offer.
365	///
366	/// The case two review bots found in the first version of this, which gave
367	/// up on a channel count as soon as no preferred rate matched it: a device
368	/// with stereo only at 96 kHz and mono at 48 kHz went to mono, which is the
369	/// downmix the whole preference exists to avoid.
370	#[test]
371	fn stereo_at_an_awkward_rate_beats_mono_at_a_preferred_one() {
372		let chosen = choose(
373			[range(1, 48_000, SampleFormat::F32), range(2, 96_000, SampleFormat::F32)].into_iter(),
374			None,
375		)
376		.expect("a config");
377		assert_eq!((chosen.channels(), chosen.sample_rate()), (2, 96_000));
378	}
379
380	/// The same with neither count on a preferred rate, so the ordering rests on
381	/// the channel rank alone rather than on one side matching a rate.
382	#[test]
383	fn stereo_beats_mono_when_neither_is_on_a_preferred_rate() {
384		let chosen = choose(
385			[
386				range(1, 192_000, SampleFormat::F32),
387				range(2, 96_000, SampleFormat::F32),
388			]
389			.into_iter(),
390			None,
391		)
392		.expect("a config");
393		assert_eq!((chosen.channels(), chosen.sample_rate()), (2, 96_000));
394	}
395
396	/// Nothing in the preferred lists matches, so the last resort picks the
397	/// highest rate and breaks the tie on format.
398	#[test]
399	fn the_last_resort_takes_the_highest_rate() {
400		let chosen = choose(
401			[
402				range(2, 96_000, SampleFormat::I16),
403				range(2, 96_000, SampleFormat::F32),
404				range(2, 32_000, SampleFormat::F32),
405			]
406			.into_iter(),
407			None,
408		)
409		.expect("a config");
410		assert_eq!(
411			(chosen.sample_rate(), chosen.sample_format()),
412			(96_000, SampleFormat::F32)
413		);
414	}
415}