1use std::borrow::Cow;
2
3use crate::Error;
4
5#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum Format {
17 U8,
19 S16,
21 S32,
23 #[default]
26 F32,
27 U8Planar,
29 S16Planar,
31 S32Planar,
33 F32Planar,
35}
36
37impl Format {
38 pub fn bytes_per_sample(self) -> usize {
40 match self {
41 Self::U8 | Self::U8Planar => 1,
42 Self::S16 | Self::S16Planar => 2,
43 Self::S32 | Self::S32Planar | Self::F32 | Self::F32Planar => 4,
44 }
45 }
46
47 pub fn as_interleaved_f32<'a>(self, data: &'a [u8], channels: u32) -> Result<Cow<'a, [f32]>, Error> {
53 let channels = channels as usize;
54 if channels == 0 {
55 return Err(Error::Unsupported("channel count must be > 0".into()));
56 }
57
58 let bps = self.bytes_per_sample();
59 if !data.len().is_multiple_of(bps * channels) {
60 return Err(Error::Misaligned {
61 got: data.len(),
62 expected: data.len().next_multiple_of(bps * channels),
63 });
64 }
65
66 if self == Self::F32 {
68 let (head, body, tail) = unsafe { data.align_to::<f32>() };
69 if head.is_empty() && tail.is_empty() {
70 return Ok(Cow::Borrowed(body));
71 }
72 }
73
74 Ok(Cow::Owned(self.to_interleaved_f32_owned(data, channels)))
75 }
76
77 fn to_interleaved_f32_owned(self, data: &[u8], channels: usize) -> Vec<f32> {
78 let total_samples = data.len() / self.bytes_per_sample();
79 let frames = total_samples / channels;
80 let mut out = vec![0.0f32; total_samples];
81
82 match self {
83 Self::F32 => {
84 for (i, chunk) in data.as_chunks::<4>().0.iter().enumerate() {
85 out[i] = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
86 }
87 }
88 Self::F32Planar => {
89 for ch in 0..channels {
90 let plane = &data[ch * frames * 4..(ch + 1) * frames * 4];
91 for (frame, chunk) in plane.as_chunks::<4>().0.iter().enumerate() {
92 out[frame * channels + ch] = f32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
93 }
94 }
95 }
96 Self::S16 => {
97 for (i, chunk) in data.as_chunks::<2>().0.iter().enumerate() {
98 let v = i16::from_le_bytes([chunk[0], chunk[1]]);
99 out[i] = (v as f32) / 32768.0;
100 }
101 }
102 Self::S16Planar => {
103 for ch in 0..channels {
104 let plane = &data[ch * frames * 2..(ch + 1) * frames * 2];
105 for (frame, chunk) in plane.as_chunks::<2>().0.iter().enumerate() {
106 let v = i16::from_le_bytes([chunk[0], chunk[1]]);
107 out[frame * channels + ch] = (v as f32) / 32768.0;
108 }
109 }
110 }
111 Self::S32 => {
112 for (i, chunk) in data.as_chunks::<4>().0.iter().enumerate() {
113 let v = i32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
114 out[i] = (v as f32) / (i32::MAX as f32 + 1.0);
115 }
116 }
117 Self::S32Planar => {
118 for ch in 0..channels {
119 let plane = &data[ch * frames * 4..(ch + 1) * frames * 4];
120 for (frame, chunk) in plane.as_chunks::<4>().0.iter().enumerate() {
121 let v = i32::from_le_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]);
122 out[frame * channels + ch] = (v as f32) / (i32::MAX as f32 + 1.0);
123 }
124 }
125 }
126 Self::U8 => {
127 for (i, &b) in data.iter().enumerate() {
128 out[i] = (b as f32 - 128.0) / 128.0;
129 }
130 }
131 Self::U8Planar => {
132 for ch in 0..channels {
133 let plane = &data[ch * frames..(ch + 1) * frames];
134 for (frame, &b) in plane.iter().enumerate() {
135 out[frame * channels + ch] = (b as f32 - 128.0) / 128.0;
136 }
137 }
138 }
139 }
140
141 out
142 }
143
144 pub fn from_interleaved_f32(self, samples: &[f32], channels: u32) -> Result<Vec<u8>, Error> {
148 let channels = channels as usize;
149 if channels == 0 {
150 return Err(Error::Unsupported("channel count must be > 0".into()));
151 }
152 if !samples.len().is_multiple_of(channels) {
153 return Err(Error::Misaligned {
154 got: samples.len(),
155 expected: samples.len().next_multiple_of(channels),
156 });
157 }
158
159 let frames = samples.len() / channels;
160 let mut out = vec![0u8; samples.len() * self.bytes_per_sample()];
161
162 match self {
163 Self::F32 => {
164 for (i, &s) in samples.iter().enumerate() {
165 out[i * 4..i * 4 + 4].copy_from_slice(&s.to_le_bytes());
166 }
167 }
168 Self::F32Planar => {
169 for ch in 0..channels {
170 let plane = &mut out[ch * frames * 4..(ch + 1) * frames * 4];
171 for (frame, chunk) in plane.as_chunks_mut::<4>().0.iter_mut().enumerate() {
172 chunk.copy_from_slice(&samples[frame * channels + ch].to_le_bytes());
173 }
174 }
175 }
176 Self::S16 => {
177 for (i, &s) in samples.iter().enumerate() {
178 let v = (s.clamp(-1.0, 1.0) * 32767.0).round() as i16;
179 out[i * 2..i * 2 + 2].copy_from_slice(&v.to_le_bytes());
180 }
181 }
182 Self::S16Planar => {
183 for ch in 0..channels {
184 let plane = &mut out[ch * frames * 2..(ch + 1) * frames * 2];
185 for (frame, chunk) in plane.as_chunks_mut::<2>().0.iter_mut().enumerate() {
186 let v = (samples[frame * channels + ch].clamp(-1.0, 1.0) * 32767.0).round() as i16;
187 chunk.copy_from_slice(&v.to_le_bytes());
188 }
189 }
190 }
191 Self::S32 => {
192 for (i, &s) in samples.iter().enumerate() {
193 let v = (s.clamp(-1.0, 1.0) as f64 * i32::MAX as f64).round() as i32;
194 out[i * 4..i * 4 + 4].copy_from_slice(&v.to_le_bytes());
195 }
196 }
197 Self::S32Planar => {
198 for ch in 0..channels {
199 let plane = &mut out[ch * frames * 4..(ch + 1) * frames * 4];
200 for (frame, chunk) in plane.as_chunks_mut::<4>().0.iter_mut().enumerate() {
201 let v =
202 (samples[frame * channels + ch].clamp(-1.0, 1.0) as f64 * i32::MAX as f64).round() as i32;
203 chunk.copy_from_slice(&v.to_le_bytes());
204 }
205 }
206 }
207 Self::U8 => {
208 for (i, &s) in samples.iter().enumerate() {
209 out[i] = ((s.clamp(-1.0, 1.0) * 127.0).round() + 128.0) as u8;
210 }
211 }
212 Self::U8Planar => {
213 for ch in 0..channels {
214 let plane = &mut out[ch * frames..(ch + 1) * frames];
215 for (frame, byte) in plane.iter_mut().enumerate() {
216 *byte = ((samples[frame * channels + ch].clamp(-1.0, 1.0) * 127.0).round() + 128.0) as u8;
217 }
218 }
219 }
220 }
221
222 Ok(out)
223 }
224}
225
226#[cfg(test)]
227mod tests {
228 use super::*;
229
230 #[test]
231 fn f32_interleaved_is_borrowed() {
232 let samples: Vec<f32> = vec![0.1, 0.2, 0.3, 0.4];
233 let bytes: Vec<u8> = samples.iter().flat_map(|s| s.to_le_bytes()).collect();
234 let cow = Format::F32.as_interleaved_f32(&bytes, 2).unwrap();
235 assert!(matches!(cow, Cow::Borrowed(_)));
236 assert_eq!(cow.as_ref(), samples.as_slice());
237 }
238
239 #[test]
240 fn s16_interleaved_is_owned_but_close() {
241 let samples = vec![-1.0_f32, -0.5, 0.0, 0.5, 0.9999];
242 let bytes = Format::S16.from_interleaved_f32(&samples, 1).unwrap();
243 let cow = Format::S16.as_interleaved_f32(&bytes, 1).unwrap();
244 assert!(matches!(cow, Cow::Owned(_)));
245 for (a, b) in samples.iter().zip(cow.iter()) {
246 assert!((a - b).abs() < 1.0 / 32767.0, "{a} vs {b}");
247 }
248 }
249
250 #[test]
251 fn planar_to_interleaved_orders_correctly() {
252 let planar: Vec<f32> = vec![0.1, 0.2, 0.3, 0.4, 0.5, 0.6];
253 let bytes: Vec<u8> = planar.iter().flat_map(|s| s.to_le_bytes()).collect();
254 let cow = Format::F32Planar.as_interleaved_f32(&bytes, 2).unwrap();
255 assert_eq!(cow.as_ref(), &[0.1, 0.4, 0.2, 0.5, 0.3, 0.6]);
256 }
257
258 #[test]
259 fn s16_clamps_out_of_range() {
260 let samples = vec![2.0_f32, -3.0];
261 let bytes = Format::S16.from_interleaved_f32(&samples, 1).unwrap();
262 let cow = Format::S16.as_interleaved_f32(&bytes, 1).unwrap();
263 assert!((cow[0] - 0.99997).abs() < 1e-4);
264 assert!((cow[1] + 1.0).abs() < 1e-4);
265 }
266
267 #[test]
268 fn rejects_misaligned_buffer() {
269 let result = Format::S16.as_interleaved_f32(&[0u8; 5], 2);
270 assert!(matches!(result, Err(Error::Misaligned { .. })));
271 }
272}