1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum AudioChannelLayout {
16 Mono,
18 Stereo,
20 Stereo21,
22 Surround51,
24 Surround71,
26 Unknown,
28}
29
30impl AudioChannelLayout {
31 #[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 #[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#[derive(Clone)]
64pub struct Audio {
65 data: Matrix,
66 sample_rate: u32,
67 layout: AudioChannelLayout,
68 semantic: Rc<AudioSemantic>,
69}
70
71pub(crate) struct AudioSemantic {
73 pub(crate) id: u64,
74}
75
76impl Audio {
77 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 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 #[must_use]
127 pub const fn as_matrix(&self) -> &Matrix {
128 &self.data
129 }
130
131 #[must_use]
133 pub fn channels(&self) -> usize {
134 self.data.shape()[0]
135 }
136
137 #[must_use]
139 pub fn samples(&self) -> usize {
140 self.data.shape()[1]
141 }
142
143 #[must_use]
145 pub const fn sample_rate(&self) -> u32 {
146 self.sample_rate
147 }
148
149 #[must_use]
151 pub const fn layout(&self) -> AudioChannelLayout {
152 self.layout
153 }
154
155 #[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}