Skip to main content

oa/audio/
audio.rs

1//! Finite planar FP32 audio value — foundational semantic type composing [`crate::Matrix`].
2
3use std::{
4	rc::Rc,
5	sync::atomic::{AtomicU64, Ordering},
6};
7
8use crate::{
9	DType, Engine, Error, Matrix, Result,
10	runtime::{EngineHandle, Storage},
11};
12
13/// Speaker layout carried by an [`Audio`] value.
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum AudioChannelLayout {
16	/// One center channel.
17	Mono,
18	/// Left and right channels.
19	Stereo,
20	/// Left, right, and low-frequency-effects channels.
21	Stereo21,
22	/// 5.1 surround channels.
23	Surround51,
24	/// 7.1 surround channels.
25	Surround71,
26	/// The channel count does not determine an unambiguous speaker layout.
27	Unknown,
28}
29
30impl AudioChannelLayout {
31	/// Return the required channel count, or `None` for an unknown layout.
32	#[must_use]
33	pub const fn channel_count(self) -> Option<usize> {
34		match self {
35			Self::Mono => Some(1),
36			Self::Stereo => Some(2),
37			Self::Stereo21 => Some(3),
38			Self::Surround51 => Some(6),
39			Self::Surround71 => Some(8),
40			Self::Unknown => None,
41		}
42	}
43
44	/// Infer the unambiguous conventional layout for a channel count.
45	///
46	/// Three channels deliberately remain unknown because the count cannot
47	/// distinguish L/R/LFE (2.1) from L/C/R (3.0).
48	#[must_use]
49	pub const fn for_channel_count(channels: usize) -> Self {
50		match channels {
51			1 => Self::Mono,
52			2 => Self::Stereo,
53			6 => Self::Surround51,
54			8 => Self::Surround71,
55			_ => Self::Unknown,
56		}
57	}
58}
59
60/// Whole-audio value backed by a planar FP32 `[channels, samples]` matrix.
61///
62/// Clones retain the same matrix storage and semantic audio metadata.
63#[derive(Clone)]
64pub struct Audio {
65	data: Matrix,
66	sample_rate: u32,
67	layout: AudioChannelLayout,
68	semantic: Rc<AudioSemantic>,
69}
70
71/// Persistent semantic identity shared by clones of one Audio value.
72pub(crate) struct AudioSemantic {
73	pub(crate) id: u64,
74}
75
76impl Audio {
77	/// Attach audio semantics to a planar FP32 matrix.
78	///
79	/// # Errors
80	///
81	/// Returns an error unless `data` is a non-empty rank-two FP32 matrix, the
82	/// sample rate is non-zero, and a known layout agrees with the matrix's
83	/// channel extent.
84	pub fn new(data: Matrix, sample_rate: u32, layout: AudioChannelLayout) -> Result<Self> {
85		validate_audio_matrix(&data, sample_rate, layout)?;
86		Ok(Self {
87			data,
88			sample_rate,
89			layout,
90			semantic: Rc::new(AudioSemantic {
91				id: next_audio_value_id()?,
92			}),
93		})
94	}
95
96	/// Upload planar FP32 samples and attach audio metadata.
97	///
98	/// `samples` contains all samples for channel zero, followed by all samples
99	/// for channel one, and so on.
100	///
101	/// # Errors
102	///
103	/// Returns an error for zero channels, an empty or incomplete planar
104	/// buffer, a zero sample rate, incompatible layout metadata, checked-size
105	/// overflow, or device allocation/upload failure.
106	pub fn new_from_planar_f32(
107		engine: &Engine,
108		samples: &[f32],
109		channel_count: usize,
110		sample_rate: u32,
111		layout: AudioChannelLayout,
112	) -> Result<Self> {
113		let samples_per_channel = validate_sample_buffer(samples, channel_count, sample_rate)?;
114		if let Some(expected) = layout.channel_count()
115			&& expected != channel_count
116		{
117			return Err(Error::invalid_argument(format!(
118				"audio layout {layout:?} requires {expected} channels; received {channel_count}"
119			)));
120		}
121		let data = Matrix::new_from_f32_on(engine, [channel_count, samples_per_channel], samples)?;
122		Self::new(data, sample_rate, layout)
123	}
124
125	/// Return the zero-copy planar matrix view.
126	#[must_use]
127	pub const fn as_matrix(&self) -> &Matrix {
128		&self.data
129	}
130
131	/// Return the number of channels.
132	#[must_use]
133	pub fn channels(&self) -> usize {
134		self.data.shape()[0]
135	}
136
137	/// Return the sample count per channel.
138	#[must_use]
139	pub fn samples(&self) -> usize {
140		self.data.shape()[1]
141	}
142
143	/// Return the sample rate in hertz.
144	#[must_use]
145	pub const fn sample_rate(&self) -> u32 {
146		self.sample_rate
147	}
148
149	/// Return the semantic speaker layout.
150	#[must_use]
151	pub const fn layout(&self) -> AudioChannelLayout {
152		self.layout
153	}
154
155	/// Return the clip duration in seconds.
156	#[must_use]
157	pub fn duration_seconds(&self) -> f64 {
158		self.samples() as f64 / f64::from(self.sample_rate)
159	}
160
161	pub(crate) const fn engine_handle(&self) -> &EngineHandle {
162		self.data.engine_handle()
163	}
164
165	pub(crate) fn storage(&self) -> &Storage {
166		self.data.storage()
167	}
168
169	pub(crate) fn value_id(&self) -> u64 {
170		self.semantic.id
171	}
172}
173
174fn next_audio_value_id() -> Result<u64> {
175	static NEXT_AUDIO_VALUE_ID: AtomicU64 = AtomicU64::new(1);
176	NEXT_AUDIO_VALUE_ID
177		.try_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
178			value.checked_add(1)
179		})
180		.map_err(|_| Error::resource_exhausted("audio semantic value identity space is exhausted"))
181}
182
183pub(crate) fn validate_sample_buffer(
184	samples: &[f32],
185	channel_count: usize,
186	sample_rate: u32,
187) -> Result<usize> {
188	if sample_rate == 0 {
189		return Err(Error::invalid_argument(
190			"audio sample rate must be non-zero",
191		));
192	}
193	if channel_count == 0 {
194		return Err(Error::invalid_argument(
195			"audio channel count must be non-zero",
196		));
197	}
198	if samples.is_empty() || !samples.len().is_multiple_of(channel_count) {
199		return Err(Error::invalid_argument(
200			"audio samples must contain complete, non-empty frames",
201		));
202	}
203	Ok(samples.len() / channel_count)
204}
205
206fn validate_audio_matrix(
207	data: &Matrix,
208	sample_rate: u32,
209	layout: AudioChannelLayout,
210) -> Result<()> {
211	let [channels, samples] = data.shape() else {
212		return Err(Error::invalid_argument(format!(
213			"audio data must be rank two [channels, samples]; received {:?}",
214			data.shape()
215		)));
216	};
217	if *channels == 0 || *samples == 0 {
218		return Err(Error::invalid_argument(
219			"audio data must contain at least one channel and sample",
220		));
221	}
222	if data.dtype() != DType::F32 {
223		return Err(Error::invalid_argument(format!(
224			"audio data must use f32 storage; received {}",
225			data.dtype().token()
226		)));
227	}
228	if sample_rate == 0 {
229		return Err(Error::invalid_argument(
230			"audio sample rate must be non-zero",
231		));
232	}
233	if let Some(expected) = layout.channel_count()
234		&& *channels != expected
235	{
236		return Err(Error::invalid_argument(format!(
237			"audio layout {layout:?} requires {expected} channels; received {channels}"
238		)));
239	}
240	Ok(())
241}