byte-engine-ahi 0.1.0

Audio hardware interface layer used by Byte-Engine.
Documentation
/// A borrowed mono audio buffer with signed 16-bit samples.
pub type Mono16Bit<'a> = &'a [i16];
/// A borrowed stereo audio buffer with signed 16-bit samples.
pub type Stereo16Bit<'a> = &'a [(i16, i16)];
/// A borrowed mono audio buffer with 32-bit floating-point samples.
pub type MonoFloat32<'a> = &'a [f32];
/// A borrowed stereo audio buffer with 32-bit floating-point samples.
pub type StereoFloat32<'a> = &'a [(f32, f32)];

/// A mutably borrowed mono audio buffer with signed 16-bit samples.
pub type Mono16BitMut<'a> = &'a mut [i16];
/// A mutably borrowed stereo audio buffer with signed 16-bit samples.
pub type Stereo16BitMut<'a> = &'a mut [(i16, i16)];
/// A mutably borrowed mono audio buffer with 32-bit floating-point samples.
pub type MonoFloat32Mut<'a> = &'a mut [f32];
/// A mutably borrowed stereo audio buffer with 32-bit floating-point samples.
pub type StereoFloat32Mut<'a> = &'a mut [(f32, f32)];

/// An audio buffer in a format supported by the active backend.
pub enum Streams<'a> {
	/// Mono audio with signed 16-bit samples.
	Mono16Bit(Mono16BitMut<'a>),
	/// Stereo audio with signed 16-bit samples.
	Stereo16Bit(Stereo16BitMut<'a>),
	/// Mono audio with 32-bit floating-point samples.
	MonoFloat32(MonoFloat32Mut<'a>),
	/// Stereo audio with 32-bit floating-point samples.
	StereoFloat32(StereoFloat32Mut<'a>),
}

impl Streams<'_> {
	/// Fills every sample with silence.
	pub fn zero(&mut self) {
		match self {
			Self::Mono16Bit(buf) => buf.fill(0),
			Self::Stereo16Bit(buf) => buf.fill((0, 0)),
			Self::MonoFloat32(buf) => buf.fill(0.0),
			Self::StereoFloat32(buf) => buf.fill((0.0, 0.0)),
		}
	}

	pub fn frames(&self) -> usize {
		match self {
			Self::Mono16Bit(buf) => buf.len(),
			Self::Stereo16Bit(buf) => buf.len(),
			Self::MonoFloat32(buf) => buf.len(),
			Self::StereoFloat32(buf) => buf.len(),
		}
	}
}

/// An error that prevents audio playback.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AudioPlayError {
	/// The backend could not recover the hardware stream after an audio device error.
	RecoveryFailed,
	/// The backend could not start the hardware stream after audio data was queued.
	StartFailed,
	/// The requested audio format is not supported by the active backend.
	UnsupportedFormat,
}

impl std::fmt::Display for AudioPlayError {
	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::RecoveryFailed => write!(
				formatter,
				"Audio stream recovery failed. The most likely cause is that the audio device entered an unrecoverable error state."
			),
			Self::StartFailed => write!(
				formatter,
				"Audio stream start failed. The most likely cause is that the audio device rejected the configured playback stream."
			),
			Self::UnsupportedFormat => write!(
				formatter,
				"Audio playback format is unsupported. The most likely cause is that the requested channel count or bit depth is unavailable on this backend."
			),
		}
	}
}

impl std::error::Error for AudioPlayError {}

pub trait Mono16BitBufferPlayFunction = FnOnce(Mono16Bit);
pub trait Stereo16BitBufferPlayFunction = FnOnce(Stereo16Bit);
pub trait MonoFloat32BufferPlayFunction = FnOnce(MonoFloat32);
pub trait StereoFloat32BufferPlayFunction = FnOnce(StereoFloat32);

/// The `WritePlayFunction` trait lets clients write audio into a hardware-owned buffer.
pub trait WritePlayFunction = FnOnce(Streams);

/// The `AudioHardwareInterface` trait provides a platform-independent playback boundary.
pub trait AudioHardwareInterface {
	fn new(params: HardwareParameters) -> Result<Self, String>
	where
		Self: Sized;

	fn get_period_size(&self) -> usize;

	/// Returns the number of hardware callback cycles that encountered at least one buffer underrun.
	///
	/// Backends that cannot provide this metric should return `0`.
	fn get_underrun_count(&self) -> usize {
		0
	}

	/// Waits until playback can accept more data without dropping or busy spinning.
	///
	/// Backends that cannot provide a direct wait mechanism should yield briefly.
	fn wait_for_playback_space(&self) {
		std::thread::yield_now();
	}

	/// Writes audio data to a hardware buffer and submits it for playback.
	///
	/// Returns the number of submitted frames.
	fn play(&self, wpf: impl WritePlayFunction) -> Result<usize, AudioPlayError>;

	/// Notifies the hardware that playback has been paused.
	/// This may be used to improve performance by reducing CPU usage.
	fn pause(&self);
}

/// The `HardwareParameters` struct configures the format requested from an audio device.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct HardwareParameters {
	/// The sample rate of the audio hardware, in Hz.
	pub(crate) sample_rate: u32,
	/// The number of channels in the audio hardware.
	pub(crate) channels: u32,
	/// The bit depth of the audio hardware.
	pub(crate) bit_depth: u32,
}

impl HardwareParameters {
	/// Creates parameters for 48 kHz, stereo, 16-bit playback.
	///
	/// # Defaults
	///
	/// - Sample rate: 48,000 Hz
	/// - Channels: 2
	/// - Bit depth: 16
	pub fn new() -> Self {
		HardwareParameters {
			sample_rate: 48000,
			channels: 2,
			bit_depth: 16,
		}
	}

	pub fn sample_rate(mut self, sample_rate: u32) -> Self {
		self.sample_rate = sample_rate;
		self
	}

	pub fn channels(mut self, channels: u32) -> Self {
		self.channels = channels;
		self
	}

	pub fn bit_depth(mut self, bit_depth: u32) -> Self {
		self.bit_depth = bit_depth;
		self
	}

	pub fn get_sample_rate(&self) -> u32 {
		self.sample_rate
	}

	pub fn get_channels(&self) -> u32 {
		self.channels
	}

	pub fn get_bit_depth(&self) -> u32 {
		self.bit_depth
	}
}

impl Default for HardwareParameters {
	fn default() -> Self {
		Self::new()
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn test_default_ahi_hardware_parameters() {
		let params = HardwareParameters::new();
		assert_eq!(params.sample_rate, 48000);
		assert_eq!(params.channels, 2);
		assert_eq!(params.bit_depth, 16);
	}

	#[test]
	fn stream_frame_count_uses_typed_samples_not_byte_width() {
		let mut mono_i16 = [1i16, 2, 3];
		let mut stereo_i16 = [(1i16, 2i16), (3, 4), (5, 6)];
		let mut mono_f32 = [1.0f32, 2.0, 3.0];
		let mut stereo_f32 = [(1.0f32, 2.0f32), (3.0, 4.0), (5.0, 6.0)];

		assert_eq!(Streams::Mono16Bit(&mut mono_i16).frames(), 3);
		assert_eq!(Streams::Stereo16Bit(&mut stereo_i16).frames(), 3);
		assert_eq!(Streams::MonoFloat32(&mut mono_f32).frames(), 3);
		assert_eq!(Streams::StereoFloat32(&mut stereo_f32).frames(), 3);
	}

	#[test]
	fn zero_silences_every_supported_stream_format() {
		let mut mono_i16 = [1i16, -2, 3];
		let mut stereo_i16 = [(1i16, -2i16), (3, -4)];
		let mut mono_f32 = [1.0f32, -2.0, 3.0];
		let mut stereo_f32 = [(1.0f32, -2.0f32), (3.0, -4.0)];

		Streams::Mono16Bit(&mut mono_i16).zero();
		Streams::Stereo16Bit(&mut stereo_i16).zero();
		Streams::MonoFloat32(&mut mono_f32).zero();
		Streams::StereoFloat32(&mut stereo_f32).zero();

		assert_eq!(mono_i16, [0; 3]);
		assert_eq!(stereo_i16, [(0, 0); 2]);
		assert_eq!(mono_f32, [0.0; 3]);
		assert_eq!(stereo_f32, [(0.0, 0.0); 2]);
	}

	#[test]
	fn hardware_parameter_builders_are_independent() {
		let defaults = HardwareParameters::default();
		let configured = defaults.sample_rate(96_000).channels(1).bit_depth(32);

		assert_eq!(defaults.get_sample_rate(), 48_000);
		assert_eq!(defaults.get_channels(), 2);
		assert_eq!(defaults.get_bit_depth(), 16);
		assert_eq!(configured.get_sample_rate(), 96_000);
		assert_eq!(configured.get_channels(), 1);
		assert_eq!(configured.get_bit_depth(), 32);
	}

	#[test]
	fn playback_errors_include_failure_and_likely_cause() {
		for error in [
			AudioPlayError::RecoveryFailed,
			AudioPlayError::StartFailed,
			AudioPlayError::UnsupportedFormat,
		] {
			let message = error.to_string();
			assert!(message.contains("failed") || message.contains("unsupported"));
			assert!(message.contains("most likely cause"));
		}
	}
}