Skip to main content

ahi/
audio_hardware_interface.rs

1/// A borrowed mono audio buffer with signed 16-bit samples.
2pub type Mono16Bit<'a> = &'a [i16];
3/// A borrowed stereo audio buffer with signed 16-bit samples.
4pub type Stereo16Bit<'a> = &'a [(i16, i16)];
5/// A borrowed mono audio buffer with 32-bit floating-point samples.
6pub type MonoFloat32<'a> = &'a [f32];
7/// A borrowed stereo audio buffer with 32-bit floating-point samples.
8pub type StereoFloat32<'a> = &'a [(f32, f32)];
9
10/// A mutably borrowed mono audio buffer with signed 16-bit samples.
11pub type Mono16BitMut<'a> = &'a mut [i16];
12/// A mutably borrowed stereo audio buffer with signed 16-bit samples.
13pub type Stereo16BitMut<'a> = &'a mut [(i16, i16)];
14/// A mutably borrowed mono audio buffer with 32-bit floating-point samples.
15pub type MonoFloat32Mut<'a> = &'a mut [f32];
16/// A mutably borrowed stereo audio buffer with 32-bit floating-point samples.
17pub type StereoFloat32Mut<'a> = &'a mut [(f32, f32)];
18
19/// An audio buffer in a format supported by the active backend.
20pub enum Streams<'a> {
21	/// Mono audio with signed 16-bit samples.
22	Mono16Bit(Mono16BitMut<'a>),
23	/// Stereo audio with signed 16-bit samples.
24	Stereo16Bit(Stereo16BitMut<'a>),
25	/// Mono audio with 32-bit floating-point samples.
26	MonoFloat32(MonoFloat32Mut<'a>),
27	/// Stereo audio with 32-bit floating-point samples.
28	StereoFloat32(StereoFloat32Mut<'a>),
29}
30
31impl Streams<'_> {
32	/// Fills every sample with silence.
33	pub fn zero(&mut self) {
34		match self {
35			Self::Mono16Bit(buf) => buf.fill(0),
36			Self::Stereo16Bit(buf) => buf.fill((0, 0)),
37			Self::MonoFloat32(buf) => buf.fill(0.0),
38			Self::StereoFloat32(buf) => buf.fill((0.0, 0.0)),
39		}
40	}
41
42	pub fn frames(&self) -> usize {
43		match self {
44			Self::Mono16Bit(buf) => buf.len(),
45			Self::Stereo16Bit(buf) => buf.len(),
46			Self::MonoFloat32(buf) => buf.len(),
47			Self::StereoFloat32(buf) => buf.len(),
48		}
49	}
50}
51
52/// An error that prevents audio playback.
53#[derive(Clone, Copy, Debug, PartialEq, Eq)]
54pub enum AudioPlayError {
55	/// The backend could not recover the hardware stream after an audio device error.
56	RecoveryFailed,
57	/// The backend could not start the hardware stream after audio data was queued.
58	StartFailed,
59	/// The requested audio format is not supported by the active backend.
60	UnsupportedFormat,
61}
62
63impl std::fmt::Display for AudioPlayError {
64	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
65		match self {
66			Self::RecoveryFailed => write!(
67				formatter,
68				"Audio stream recovery failed. The most likely cause is that the audio device entered an unrecoverable error state."
69			),
70			Self::StartFailed => write!(
71				formatter,
72				"Audio stream start failed. The most likely cause is that the audio device rejected the configured playback stream."
73			),
74			Self::UnsupportedFormat => write!(
75				formatter,
76				"Audio playback format is unsupported. The most likely cause is that the requested channel count or bit depth is unavailable on this backend."
77			),
78		}
79	}
80}
81
82impl std::error::Error for AudioPlayError {}
83
84pub trait Mono16BitBufferPlayFunction = FnOnce(Mono16Bit);
85pub trait Stereo16BitBufferPlayFunction = FnOnce(Stereo16Bit);
86pub trait MonoFloat32BufferPlayFunction = FnOnce(MonoFloat32);
87pub trait StereoFloat32BufferPlayFunction = FnOnce(StereoFloat32);
88
89/// The `WritePlayFunction` trait lets clients write audio into a hardware-owned buffer.
90pub trait WritePlayFunction = FnOnce(Streams);
91
92/// The `AudioHardwareInterface` trait provides a platform-independent playback boundary.
93pub trait AudioHardwareInterface {
94	fn new(params: HardwareParameters) -> Result<Self, String>
95	where
96		Self: Sized;
97
98	fn get_period_size(&self) -> usize;
99
100	/// Returns the number of hardware callback cycles that encountered at least one buffer underrun.
101	///
102	/// Backends that cannot provide this metric should return `0`.
103	fn get_underrun_count(&self) -> usize {
104		0
105	}
106
107	/// Waits until playback can accept more data without dropping or busy spinning.
108	///
109	/// Backends that cannot provide a direct wait mechanism should yield briefly.
110	fn wait_for_playback_space(&self) {
111		std::thread::yield_now();
112	}
113
114	/// Writes audio data to a hardware buffer and submits it for playback.
115	///
116	/// Returns the number of submitted frames.
117	fn play(&self, wpf: impl WritePlayFunction) -> Result<usize, AudioPlayError>;
118
119	/// Notifies the hardware that playback has been paused.
120	/// This may be used to improve performance by reducing CPU usage.
121	fn pause(&self);
122}
123
124/// The `HardwareParameters` struct configures the format requested from an audio device.
125#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
126pub struct HardwareParameters {
127	/// The sample rate of the audio hardware, in Hz.
128	pub(crate) sample_rate: u32,
129	/// The number of channels in the audio hardware.
130	pub(crate) channels: u32,
131	/// The bit depth of the audio hardware.
132	pub(crate) bit_depth: u32,
133}
134
135impl HardwareParameters {
136	/// Creates parameters for 48 kHz, stereo, 16-bit playback.
137	///
138	/// # Defaults
139	///
140	/// - Sample rate: 48,000 Hz
141	/// - Channels: 2
142	/// - Bit depth: 16
143	pub fn new() -> Self {
144		HardwareParameters {
145			sample_rate: 48000,
146			channels: 2,
147			bit_depth: 16,
148		}
149	}
150
151	pub fn sample_rate(mut self, sample_rate: u32) -> Self {
152		self.sample_rate = sample_rate;
153		self
154	}
155
156	pub fn channels(mut self, channels: u32) -> Self {
157		self.channels = channels;
158		self
159	}
160
161	pub fn bit_depth(mut self, bit_depth: u32) -> Self {
162		self.bit_depth = bit_depth;
163		self
164	}
165
166	pub fn get_sample_rate(&self) -> u32 {
167		self.sample_rate
168	}
169
170	pub fn get_channels(&self) -> u32 {
171		self.channels
172	}
173
174	pub fn get_bit_depth(&self) -> u32 {
175		self.bit_depth
176	}
177}
178
179impl Default for HardwareParameters {
180	fn default() -> Self {
181		Self::new()
182	}
183}
184
185#[cfg(test)]
186mod tests {
187	use super::*;
188
189	#[test]
190	fn test_default_ahi_hardware_parameters() {
191		let params = HardwareParameters::new();
192		assert_eq!(params.sample_rate, 48000);
193		assert_eq!(params.channels, 2);
194		assert_eq!(params.bit_depth, 16);
195	}
196
197	#[test]
198	fn stream_frame_count_uses_typed_samples_not_byte_width() {
199		let mut mono_i16 = [1i16, 2, 3];
200		let mut stereo_i16 = [(1i16, 2i16), (3, 4), (5, 6)];
201		let mut mono_f32 = [1.0f32, 2.0, 3.0];
202		let mut stereo_f32 = [(1.0f32, 2.0f32), (3.0, 4.0), (5.0, 6.0)];
203
204		assert_eq!(Streams::Mono16Bit(&mut mono_i16).frames(), 3);
205		assert_eq!(Streams::Stereo16Bit(&mut stereo_i16).frames(), 3);
206		assert_eq!(Streams::MonoFloat32(&mut mono_f32).frames(), 3);
207		assert_eq!(Streams::StereoFloat32(&mut stereo_f32).frames(), 3);
208	}
209
210	#[test]
211	fn zero_silences_every_supported_stream_format() {
212		let mut mono_i16 = [1i16, -2, 3];
213		let mut stereo_i16 = [(1i16, -2i16), (3, -4)];
214		let mut mono_f32 = [1.0f32, -2.0, 3.0];
215		let mut stereo_f32 = [(1.0f32, -2.0f32), (3.0, -4.0)];
216
217		Streams::Mono16Bit(&mut mono_i16).zero();
218		Streams::Stereo16Bit(&mut stereo_i16).zero();
219		Streams::MonoFloat32(&mut mono_f32).zero();
220		Streams::StereoFloat32(&mut stereo_f32).zero();
221
222		assert_eq!(mono_i16, [0; 3]);
223		assert_eq!(stereo_i16, [(0, 0); 2]);
224		assert_eq!(mono_f32, [0.0; 3]);
225		assert_eq!(stereo_f32, [(0.0, 0.0); 2]);
226	}
227
228	#[test]
229	fn hardware_parameter_builders_are_independent() {
230		let defaults = HardwareParameters::default();
231		let configured = defaults.sample_rate(96_000).channels(1).bit_depth(32);
232
233		assert_eq!(defaults.get_sample_rate(), 48_000);
234		assert_eq!(defaults.get_channels(), 2);
235		assert_eq!(defaults.get_bit_depth(), 16);
236		assert_eq!(configured.get_sample_rate(), 96_000);
237		assert_eq!(configured.get_channels(), 1);
238		assert_eq!(configured.get_bit_depth(), 32);
239	}
240
241	#[test]
242	fn playback_errors_include_failure_and_likely_cause() {
243		for error in [
244			AudioPlayError::RecoveryFailed,
245			AudioPlayError::StartFailed,
246			AudioPlayError::UnsupportedFormat,
247		] {
248			let message = error.to_string();
249			assert!(message.contains("failed") || message.contains("unsupported"));
250			assert!(message.contains("most likely cause"));
251		}
252	}
253}