1use bytemuck::{Pod, Zeroable};
5
6use super::audio_spectral_sheet::{
7 parse_sidecar_header, parse_v2_subheader, AudioSpectralSidecarHeader,
8 SPECTRAL_SIDECAR_MAGIC,
9};
10
11pub const Q4AU_VERSION_V3: u16 = 3;
13
14pub const Q4AU_V3_HEADER_BYTES: usize = 64;
16
17pub const Q4AU_HOA_MAX_ORDER: u8 = 3;
19
20pub const Q4AU_HOA_MAX_CHANNELS: usize = 16;
22
23pub const TRANSFORM_KIND_STFT: u16 = 0;
25pub const TRANSFORM_KIND_CQT: u16 = 1;
26pub const TRANSFORM_KIND_HOA_STFT: u16 = 2;
27
28pub const NORMALIZATION_SN3D_ACN: u8 = 0;
30pub const NORMALIZATION_N3D_ACN: u8 = 1;
31
32pub const SOFA_DEFAULT_FIR_TAPS: usize = 64;
34
35#[repr(C, align(64))]
37#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
38pub struct Q4AuHeaderV3 {
39 pub magic: u32,
41 pub version: u16,
43 pub transform_kind: u16,
45 pub bin_count: u32,
47 pub frame_count: u32,
49 pub sample_rate: u32,
51 pub ambisonic_order: u8,
53 pub channel_normalization: u8,
55 pub sofa_fir_taps: u16,
57 pub sofa_direction_count: u32,
59 pub sofa_block_offset: u32,
61 pub mel_count: u16,
63 pub mfcc_count: u16,
65 pub rt60_bands_sec: [f32; 3],
67 pub portal_coupling_did_hash: u64,
69 pub portal_transmission_gain: f32,
71 pub header_crc32c: u32,
73}
74
75impl Q4AuHeaderV3 {
76 #[inline]
78 pub const fn empty() -> Self {
79 Self {
80 magic: SPECTRAL_SIDECAR_MAGIC,
81 version: Q4AU_VERSION_V3,
82 transform_kind: TRANSFORM_KIND_STFT,
83 bin_count: 0,
84 frame_count: 0,
85 sample_rate: 48_000,
86 ambisonic_order: 0,
87 channel_normalization: NORMALIZATION_SN3D_ACN,
88 sofa_fir_taps: 0,
89 sofa_direction_count: 0,
90 sofa_block_offset: 0,
91 mel_count: 0,
92 mfcc_count: 0,
93 rt60_bands_sec: [0.0; 3],
94 portal_coupling_did_hash: 0,
95 portal_transmission_gain: 1.0,
96 header_crc32c: 0,
97 }
98 }
99
100 #[inline]
102 pub fn compute_crc32c(&self) -> u32 {
103 let bytes = bytemuck::bytes_of(self);
104 crate::container_10d::crc32c::crc32c(&bytes[..60])
105 }
106
107 #[inline]
109 pub fn update_crc(&mut self) {
110 self.header_crc32c = self.compute_crc32c();
111 }
112
113 #[inline]
115 pub fn validate(&self) -> bool {
116 self.magic == SPECTRAL_SIDECAR_MAGIC
117 && self.version == Q4AU_VERSION_V3
118 && self.ambisonic_order <= Q4AU_HOA_MAX_ORDER
119 && self.bin_count > 0
120 && self.frame_count > 0
121 && self.header_crc32c == self.compute_crc32c()
122 }
123
124 #[inline]
126 pub fn hoa_channel_count(&self) -> usize {
127 ((self.ambisonic_order as usize) + 1).pow(2)
128 }
129
130 #[inline]
132 pub fn payload_bytes(&self) -> usize {
133 (self.bin_count as usize)
134 .saturating_mul(self.frame_count as usize)
135 .saturating_mul(self.hoa_channel_count())
136 .saturating_mul(4)
137 }
138
139 #[inline]
141 pub fn sofa_bytes(&self) -> usize {
142 (self.sofa_direction_count as usize).saturating_mul(std::mem::size_of::<SofaHrirEntry>())
143 }
144}
145
146#[repr(C)]
148#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
149pub struct SofaHrirEntry {
150 pub azimuth_deg: f32,
152 pub elevation_deg: f32,
154 pub itd_samples: f32,
156 pub left_fir: [f32; SOFA_DEFAULT_FIR_TAPS],
158 pub right_fir: [f32; SOFA_DEFAULT_FIR_TAPS],
160}
161
162#[inline]
167pub fn encode_hoa_acn_sn3d(
168 order: u8,
169 azimuth_rad: f32,
170 elevation_rad: f32,
171 out_gains: &mut [f32; Q4AU_HOA_MAX_CHANNELS],
172) -> usize {
173 let cos_el = elevation_rad.cos();
174 let sin_el = elevation_rad.sin();
175 let cos_az = azimuth_rad.cos();
176 let sin_az = azimuth_rad.sin();
177
178 let cos_2az = (2.0 * azimuth_rad).cos();
179 let sin_2az = (2.0 * azimuth_rad).sin();
180 let cos_3az = (3.0 * azimuth_rad).cos();
181 let sin_3az = (3.0 * azimuth_rad).sin();
182
183 let cos_el2 = cos_el * cos_el;
184 let cos_el3 = cos_el2 * cos_el;
185 let sin_el2 = sin_el * sin_el;
186
187 out_gains[0] = 1.0;
189
190 out_gains[1] = sin_az * cos_el;
192 out_gains[2] = sin_el;
193 out_gains[3] = cos_az * cos_el;
194
195 const SQRT_3_OVER_2: f32 = 0.866_025_4;
197 const SQRT_3: f32 = 1.732_050_8;
198 out_gains[4] = SQRT_3_OVER_2 * sin_2az * cos_el2;
199 out_gains[5] = SQRT_3 * sin_az * sin_el * cos_el;
200 out_gains[6] = 0.5 * (3.0 * sin_el2 - 1.0);
201 out_gains[7] = SQRT_3 * cos_az * sin_el * cos_el;
202 out_gains[8] = SQRT_3_OVER_2 * cos_2az * cos_el2;
203
204 const SQRT_5_OVER_8: f32 = 0.790_569_4;
206 const SQRT_15_OVER_2: f32 = 1.936_491_7;
207 const SQRT_3_OVER_8: f32 = 0.612_372_4;
208 out_gains[9] = SQRT_5_OVER_8 * sin_3az * cos_el3;
209 out_gains[10] = SQRT_15_OVER_2 * sin_2az * sin_el * cos_el2;
210 out_gains[11] = SQRT_3_OVER_8 * sin_az * cos_el * (5.0 * sin_el2 - 1.0);
211 out_gains[12] = 0.5 * sin_el * (5.0 * sin_el2 - 3.0);
212 out_gains[13] = SQRT_3_OVER_8 * cos_az * cos_el * (5.0 * sin_el2 - 1.0);
213 out_gains[14] = SQRT_15_OVER_2 * cos_2az * sin_el * cos_el2;
214 out_gains[15] = SQRT_5_OVER_8 * cos_3az * cos_el3;
215
216 let effective_order = order.min(Q4AU_HOA_MAX_ORDER);
217 let count = ((effective_order as usize) + 1).pow(2);
218 for slot in out_gains.iter_mut().skip(count) {
219 *slot = 0.0;
220 }
221 count
222}
223
224#[inline]
226pub fn sample_sofa_hrir_zero_heap<'a>(
227 table: &'a [SofaHrirEntry],
228 azimuth_deg: f32,
229 elevation_deg: f32,
230) -> Option<&'a SofaHrirEntry> {
231 if table.is_empty() {
232 return None;
233 }
234 let az_rad = azimuth_deg.to_radians();
235 let el_rad = elevation_deg.to_radians();
236 let tx = el_rad.cos() * az_rad.cos();
237 let ty = el_rad.cos() * az_rad.sin();
238 let tz = el_rad.sin();
239
240 let mut best_entry = &table[0];
241 let mut max_dot = -f32::INFINITY;
242
243 for entry in table {
244 let e_az = entry.azimuth_deg.to_radians();
245 let e_el = entry.elevation_deg.to_radians();
246 let ex = e_el.cos() * e_az.cos();
247 let ey = e_el.cos() * e_az.sin();
248 let ez = e_el.sin();
249 let dot = tx * ex + ty * ey + tz * ez;
250 if dot > max_dot {
251 max_dot = dot;
252 best_entry = entry;
253 }
254 }
255 Some(best_entry)
256}
257
258#[inline]
260pub fn parse_v3_header(bytes: &[u8]) -> Option<Q4AuHeaderV3> {
261 if bytes.len() < Q4AU_V3_HEADER_BYTES {
262 return None;
263 }
264 let header = bytemuck::pod_read_unaligned::<Q4AuHeaderV3>(&bytes[..Q4AU_V3_HEADER_BYTES]);
265 header.validate().then_some(header)
266}
267
268#[inline]
270pub fn v3_frame_view<'a>(bytes: &'a [u8], frame_index: u32) -> Option<&'a [f32]> {
271 let header = parse_v3_header(bytes)?;
272 if frame_index >= header.frame_count {
273 return None;
274 }
275 let channels = header.hoa_channel_count();
276 let frame_floats = (header.bin_count as usize).saturating_mul(channels);
277 let offset_bytes = Q4AU_V3_HEADER_BYTES
278 + (frame_index as usize).saturating_mul(frame_floats).saturating_mul(4);
279 let len_bytes = frame_floats.saturating_mul(4);
280 if bytes.len() < offset_bytes.saturating_add(len_bytes) {
281 return None;
282 }
283 bytemuck::try_cast_slice(&bytes[offset_bytes..offset_bytes + len_bytes]).ok()
284}
285
286#[inline]
288pub fn v3_sofa_table<'a>(bytes: &'a [u8]) -> Option<&'a [SofaHrirEntry]> {
289 let header = parse_v3_header(bytes)?;
290 if header.sofa_direction_count == 0 || (header.sofa_block_offset as usize) < Q4AU_V3_HEADER_BYTES {
291 return None;
292 }
293 let start = header.sofa_block_offset as usize;
294 let end = start.checked_add(header.sofa_bytes())?;
295 if bytes.len() < end {
296 return None;
297 }
298 bytemuck::try_cast_slice(&bytes[start..end]).ok()
299}
300
301pub fn upgrade_q4au_v1_or_v2_to_v3(
306 legacy_bytes: &[u8],
307 ambisonic_order: u8,
308 rt60_bands_sec: [f32; 3],
309) -> Option<(Q4AuHeaderV3, Vec<u8>)> {
310 if ambisonic_order != 0 {
311 return None;
312 }
313 let legacy_header = parse_sidecar_header(legacy_bytes)?;
314 let frame_count = usize::try_from(legacy_header.frame_count).ok()?;
315 let plane0_bytes = usize::try_from(legacy_header.bin_count)
316 .ok()?
317 .checked_mul(frame_count)?
318 .checked_mul(std::mem::size_of::<f32>())?;
319 let header_size = std::mem::size_of::<AudioSpectralSidecarHeader>();
320 let plane0_end = header_size.checked_add(plane0_bytes)?;
321 let plane0 = legacy_bytes.get(header_size..plane0_end)?;
322
323 let mut mel_count = 0u16;
324 let mut mfcc_count = 0u16;
325 let mut features = &[][..];
326 if legacy_header.version == AudioSpectralSidecarHeader::VERSION_V2 {
327 let v2_sub = parse_v2_subheader(legacy_bytes)?;
328 mel_count = u16::try_from(v2_sub.n_mel).ok()?;
329 mfcc_count = u16::try_from(v2_sub.n_mfcc).ok()?;
330 let sub_size = std::mem::size_of::<super::audio_spectral_sheet::SpectralV2SubHeader>();
331 let feature_start = plane0_end.checked_add(sub_size)?;
332 let mel_bytes = frame_count
333 .checked_mul(usize::from(mel_count))?
334 .checked_mul(std::mem::size_of::<f32>())?;
335 let mfcc_bytes = frame_count
336 .checked_mul(usize::from(mfcc_count))?
337 .checked_mul(std::mem::size_of::<f32>())?;
338 let feature_end = feature_start
339 .checked_add(mel_bytes)?
340 .checked_add(mfcc_bytes)?;
341 features = legacy_bytes.get(feature_start..feature_end)?;
342 }
343
344 let payload_bytes = plane0_bytes.checked_add(features.len())?;
346 let mut payload = Vec::new();
347 payload.try_reserve_exact(payload_bytes).ok()?;
348 payload.extend_from_slice(plane0);
349 payload.extend_from_slice(features);
350
351 let mut v3_header = Q4AuHeaderV3 {
352 magic: SPECTRAL_SIDECAR_MAGIC,
353 version: Q4AU_VERSION_V3,
354 transform_kind: legacy_header._pad,
355 bin_count: legacy_header.bin_count,
356 frame_count: legacy_header.frame_count,
357 sample_rate: legacy_header.sample_rate,
358 ambisonic_order,
359 channel_normalization: NORMALIZATION_SN3D_ACN,
360 sofa_fir_taps: 0,
361 sofa_direction_count: 0,
362 sofa_block_offset: 0,
363 mel_count,
364 mfcc_count,
365 rt60_bands_sec,
366 portal_coupling_did_hash: 0,
367 portal_transmission_gain: 1.0,
368 header_crc32c: 0,
369 };
370 v3_header.update_crc();
371
372 Some((v3_header, payload))
373}
374
375#[cfg(test)]
376mod tests {
377 use super::*;
378
379 #[test]
380 fn v3_header_size_and_alignment_are_exact() {
381 assert_eq!(std::mem::size_of::<Q4AuHeaderV3>(), 64);
382 assert_eq!(std::mem::align_of::<Q4AuHeaderV3>(), 64);
383 }
384
385 #[test]
386 fn v3_header_crc_and_validation() {
387 let mut hdr = Q4AuHeaderV3::empty();
388 hdr.bin_count = 64;
389 hdr.frame_count = 100;
390 hdr.update_crc();
391 assert!(hdr.validate());
392 assert_eq!(hdr.hoa_channel_count(), 1);
393
394 hdr.bin_count = 0;
395 assert!(!hdr.validate());
396 }
397
398 #[test]
399 fn hoa_acn_sn3d_encoding() {
400 let mut gains = [0.0f32; Q4AU_HOA_MAX_CHANNELS];
401 let channels = encode_hoa_acn_sn3d(3, 0.0, 0.0, &mut gains);
402 assert_eq!(channels, 16);
403 assert_eq!(gains[0], 1.0); assert_eq!(gains[1], 0.0); assert_eq!(gains[2], 0.0); assert_eq!(gains[3], 1.0); let _ = encode_hoa_acn_sn3d(3, 0.0, std::f32::consts::FRAC_PI_2, &mut gains);
410 assert_eq!(gains[0], 1.0); assert_eq!(gains[2], 1.0); assert_eq!(gains[6], 1.0); assert_eq!(gains[12], 1.0); }
415
416 #[test]
417 fn sofa_hrir_nearest_direction_sampling() {
418 let mut front = SofaHrirEntry {
419 azimuth_deg: 0.0,
420 elevation_deg: 0.0,
421 itd_samples: 0.0,
422 left_fir: [0.0; SOFA_DEFAULT_FIR_TAPS],
423 right_fir: [0.0; SOFA_DEFAULT_FIR_TAPS],
424 };
425 front.left_fir[0] = 1.0;
426
427 let mut left = SofaHrirEntry {
428 azimuth_deg: 90.0,
429 elevation_deg: 0.0,
430 itd_samples: 12.0,
431 left_fir: [0.0; SOFA_DEFAULT_FIR_TAPS],
432 right_fir: [0.0; SOFA_DEFAULT_FIR_TAPS],
433 };
434 left.left_fir[0] = 2.0;
435
436 let table = [front, left];
437 let sample1 = sample_sofa_hrir_zero_heap(&table, 5.0, 0.0).unwrap();
438 assert_eq!(sample1.azimuth_deg, 0.0);
439 assert_eq!(sample1.left_fir[0], 1.0);
440
441 let sample2 = sample_sofa_hrir_zero_heap(&table, 85.0, 0.0).unwrap();
442 assert_eq!(sample2.azimuth_deg, 90.0);
443 assert_eq!(sample2.left_fir[0], 2.0);
444 }
445
446 #[test]
447 fn upgrade_v1_to_v3() {
448 let mut legacy = Vec::new();
449 let hdr = AudioSpectralSidecarHeader {
450 magic: SPECTRAL_SIDECAR_MAGIC,
451 version: AudioSpectralSidecarHeader::VERSION,
452 _pad: TRANSFORM_KIND_STFT,
453 bin_count: 8,
454 frame_count: 4,
455 sample_rate: 44_100,
456 };
457 legacy.extend_from_slice(bytemuck::bytes_of(&hdr));
458 legacy.resize(legacy.len() + 8 * 4 * 4, 0x11);
459
460 let (v3_hdr, payload) =
461 upgrade_q4au_v1_or_v2_to_v3(&legacy, 0, [0.5, 0.4, 0.3]).expect("valid upgrade");
462 assert!(v3_hdr.validate());
463 assert_eq!(v3_hdr.version, Q4AU_VERSION_V3);
464 assert_eq!(v3_hdr.ambisonic_order, 0);
465 assert_eq!(v3_hdr.hoa_channel_count(), 1);
466 assert_eq!(v3_hdr.sample_rate, 44_100);
467 assert_eq!(
468 payload,
469 legacy[std::mem::size_of::<AudioSpectralSidecarHeader>()..]
470 );
471 assert_eq!(v3_hdr.rt60_bands_sec, [0.5, 0.4, 0.3]);
472 }
473
474 fn legacy_v2_fixture(n_mel: u32, n_mfcc: u32) -> Vec<u8> {
475 use super::super::audio_spectral_sheet::{
476 SpectralV2SubHeader, SPECTRAL_V2_SUBHEADER_MAGIC,
477 };
478 let header = AudioSpectralSidecarHeader {
479 magic: SPECTRAL_SIDECAR_MAGIC,
480 version: AudioSpectralSidecarHeader::VERSION_V2,
481 _pad: TRANSFORM_KIND_CQT,
482 bin_count: 2,
483 frame_count: 2,
484 sample_rate: 48_000,
485 };
486 let sub = SpectralV2SubHeader {
487 magic: SPECTRAL_V2_SUBHEADER_MAGIC,
488 n_mel,
489 n_mfcc,
490 };
491 let mut bytes = bytemuck::bytes_of(&header).to_vec();
492 bytes.extend_from_slice(&[0x11; 16]);
493 bytes.extend_from_slice(bytemuck::bytes_of(&sub));
494 bytes
495 }
496
497 #[test]
498 fn upgrade_v2_preserves_mono_and_feature_bytes() {
499 let mut bytes = legacy_v2_fixture(3, 2);
500 let feature_start = bytes.len();
501 bytes.extend_from_slice(&[0x22; 24]);
502 bytes.extend_from_slice(&[0x33; 16]);
503 let source = bytes.clone();
504 let (header, payload) = upgrade_q4au_v1_or_v2_to_v3(&bytes, 0, [0.0; 3]).unwrap();
505 assert!(header.validate());
506 assert_eq!((header.mel_count, header.mfcc_count), (3, 2));
507 assert_eq!(header.transform_kind, TRANSFORM_KIND_CQT);
508 assert_eq!(header.payload_bytes(), 16);
509 assert_eq!(payload, [&bytes[20..36], &bytes[feature_start..]].concat());
510 assert_eq!(bytes, source);
511 }
512
513 #[test]
514 fn upgrade_rejects_nonzero_hoa_orders() {
515 let mut bytes = legacy_v2_fixture(1, 1);
516 bytes.extend_from_slice(&[0; 16]);
517 for version in [
518 AudioSpectralSidecarHeader::VERSION,
519 AudioSpectralSidecarHeader::VERSION_V2,
520 ] {
521 bytes[4..6].copy_from_slice(&version.to_le_bytes());
522 for order in 1..=u8::MAX {
523 assert!(upgrade_q4au_v1_or_v2_to_v3(&bytes, order, [0.0; 3]).is_none());
524 }
525 }
526 }
527
528 #[test]
529 fn upgrade_rejects_every_truncated_v2_extent() {
530 let mut bytes = legacy_v2_fixture(3, 2);
531 bytes.extend_from_slice(&[0x22; 40]);
532 for len in 0..bytes.len() {
533 assert!(
534 upgrade_q4au_v1_or_v2_to_v3(&bytes[..len], 0, [0.0; 3]).is_none(),
535 "length {len}"
536 );
537 }
538 assert!(upgrade_q4au_v1_or_v2_to_v3(&bytes, 0, [0.0; 3]).is_some());
539 }
540
541 #[test]
542 fn upgrade_rejects_invalid_v2_magic_or_counts() {
543 let mut bad_magic = legacy_v2_fixture(1, 1);
544 bad_magic[36..40].fill(0);
545 bad_magic.extend_from_slice(&[0; 16]);
546 assert!(upgrade_q4au_v1_or_v2_to_v3(&bad_magic, 0, [0.0; 3]).is_none());
547 for (mel, mfcc) in [
548 (0, 1),
549 (1, 0),
550 (65_536, 1),
551 (1, 65_536),
552 (u32::MAX, 1),
553 (1, u32::MAX),
554 ] {
555 let mut bytes = legacy_v2_fixture(mel, mfcc);
556 if mel <= 65_536 && mfcc <= 65_536 {
559 bytes.resize(bytes.len() + (mel as usize + mfcc as usize) * 8, 0);
560 }
561 assert!(upgrade_q4au_v1_or_v2_to_v3(&bytes, 0, [0.0; 3]).is_none());
562 }
563 }
564
565 #[test]
566 fn upgrade_accepts_maximum_v3_feature_count() {
567 let mut bytes = legacy_v2_fixture(u16::MAX as u32, 1);
568 bytes.resize(bytes.len() + (u16::MAX as usize + 1) * 8, 0x44);
569 let (header, payload) = upgrade_q4au_v1_or_v2_to_v3(&bytes, 0, [0.0; 3]).unwrap();
570 assert_eq!(header.mel_count, u16::MAX);
571 assert_eq!(payload.len(), 16 + (u16::MAX as usize + 1) * 8);
572 }
573
574 #[test]
575 fn upgrade_rejects_unrepresentable_plane_extent() {
576 let header = AudioSpectralSidecarHeader {
577 bin_count: u32::MAX,
578 frame_count: u32::MAX,
579 ..AudioSpectralSidecarHeader::empty()
580 };
581 assert!(upgrade_q4au_v1_or_v2_to_v3(bytemuck::bytes_of(&header), 0, [0.0; 3]).is_none());
582 }
583}