1use std::f64::consts::PI;
8
9use super::envelope::*;
10use super::types::*;
11
12pub const HOA_MAX_ORDER: u8 = 3;
13pub const HOA_MAX_CHANNELS: usize = 16;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum HoaOrdering {
17 Acn,
18 FuMa,
19}
20
21impl HoaOrdering {
22 pub const fn as_str(self) -> &'static str {
23 match self {
24 Self::Acn => "ACN",
25 Self::FuMa => "FuMa",
26 }
27 }
28
29 pub fn parse(s: &str) -> Result<Self, ProfileError> {
30 match s {
31 "ACN" => Ok(Self::Acn),
32 "FuMa" => Ok(Self::FuMa),
33 _ => Err(ProfileError::InvalidMetadata("hoa_ordering")),
34 }
35 }
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum HoaNormalization {
40 Sn3d,
41 N3d,
42 MaxN,
43}
44
45impl HoaNormalization {
46 pub const fn as_str(self) -> &'static str {
47 match self {
48 Self::Sn3d => "SN3D",
49 Self::N3d => "N3D",
50 Self::MaxN => "maxN",
51 }
52 }
53
54 pub fn parse(s: &str) -> Result<Self, ProfileError> {
55 match s {
56 "SN3D" => Ok(Self::Sn3d),
57 "N3D" => Ok(Self::N3d),
58 "maxN" => Ok(Self::MaxN),
59 _ => Err(ProfileError::InvalidMetadata("hoa_normalization")),
60 }
61 }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum HoaDomain {
66 TimeSample,
68 Spectral,
70}
71
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum HoaDirectionConvention {
74 ListenerToSource,
76 PlaneWavePropagation,
78}
79
80impl HoaDirectionConvention {
81 pub const fn as_str(self) -> &'static str {
82 match self {
83 Self::ListenerToSource => "listener-to-source",
84 Self::PlaneWavePropagation => "plane-wave-propagation",
85 }
86 }
87}
88
89#[inline]
91pub fn hoa_channel_count(order: u8) -> Result<u32, ProfileError> {
92 if order > HOA_MAX_ORDER {
93 return Err(ProfileError::InvalidMetadata("hoa_order > 3 not supported in v1"));
94 }
95 let n = u32::from(order) + 1;
96 Ok(n * n)
97}
98
99#[inline]
100pub fn hoa_stride_bytes(order: u8) -> Result<u32, ProfileError> {
101 Ok(hoa_channel_count(order)? * 4)
102}
103
104pub fn evaluate_acn_sn3d_dir(order: u8, dir_xyz: [f64; 3]) -> Result<[f64; HOA_MAX_CHANNELS], ProfileError> {
107 if order > HOA_MAX_ORDER {
108 return Err(ProfileError::InvalidMetadata("hoa_order > 3"));
109 }
110 let norm = (dir_xyz[0] * dir_xyz[0] + dir_xyz[1] * dir_xyz[1] + dir_xyz[2] * dir_xyz[2]).sqrt();
111 if !norm.is_finite() || norm <= 0.0 {
112 return Err(ProfileError::InvalidUnitVector);
113 }
114 let x = dir_xyz[0] / norm;
115 let y = dir_xyz[1] / norm;
116 let z = (dir_xyz[2] / norm).clamp(-1.0, 1.0);
117 let az = y.atan2(x);
118 let el = z.asin();
119
120 let cos_el = el.cos();
121 let sin_el = el.sin();
122 let cos_az = az.cos();
123 let sin_az = az.sin();
124 let cos_2az = (2.0 * az).cos();
125 let sin_2az = (2.0 * az).sin();
126 let cos_3az = (3.0 * az).cos();
127 let sin_3az = (3.0 * az).sin();
128 let cos_el2 = cos_el * cos_el;
129 let cos_el3 = cos_el2 * cos_el;
130 let sin_el2 = sin_el * sin_el;
131
132 let mut out = [0.0f64; HOA_MAX_CHANNELS];
133 out[0] = 1.0;
135 if order >= 1 {
136 out[1] = sin_az * cos_el;
138 out[2] = sin_el;
139 out[3] = cos_az * cos_el;
140 }
141 if order >= 2 {
142 let s3_2 = 0.75f64.sqrt(); let s3 = 3.0f64.sqrt();
144 out[4] = s3_2 * sin_2az * cos_el2;
145 out[5] = s3 * sin_az * sin_el * cos_el;
146 out[6] = 0.5 * (3.0 * sin_el2 - 1.0);
147 out[7] = s3 * cos_az * sin_el * cos_el;
148 out[8] = s3_2 * cos_2az * cos_el2;
149 }
150 if order >= 3 {
151 let s5_8 = (5.0 / 8.0f64).sqrt();
152 let s15_2 = (15.0 / 2.0f64).sqrt();
153 let s3_8 = (3.0 / 8.0f64).sqrt();
154 out[9] = s5_8 * sin_3az * cos_el3;
155 out[10] = s15_2 * sin_2az * sin_el * cos_el2;
156 out[11] = s3_8 * sin_az * cos_el * (5.0 * sin_el2 - 1.0);
157 out[12] = 0.5 * sin_el * (5.0 * sin_el2 - 3.0);
158 out[13] = s3_8 * cos_az * cos_el * (5.0 * sin_el2 - 1.0);
159 out[14] = s15_2 * cos_2az * sin_el * cos_el2;
160 out[15] = s5_8 * cos_3az * cos_el3;
161 }
162 Ok(out)
163}
164
165pub fn convert_sn3d_n3d(
167 order: u8,
168 src: &[f32],
169 from: HoaNormalization,
170 to: HoaNormalization,
171 out: &mut [f32],
172) -> Result<(), ProfileError> {
173 let ch = hoa_channel_count(order)? as usize;
174 if src.len() != ch || out.len() != ch {
175 return Err(ProfileError::InvalidPayloadLength);
176 }
177 if src.iter().any(|v| !v.is_finite()) {
178 return Err(ProfileError::NonFiniteFloat);
179 }
180 match (from, to) {
181 (HoaNormalization::Sn3d, HoaNormalization::Sn3d)
182 | (HoaNormalization::N3d, HoaNormalization::N3d) => {
183 out.copy_from_slice(src);
184 Ok(())
185 }
186 (HoaNormalization::Sn3d, HoaNormalization::N3d) => {
187 for (acn, (&v, dst)) in src.iter().zip(out.iter_mut()).enumerate() {
188 let l = (acn as f64).sqrt().floor();
189 let scale = (2.0 * l + 1.0).sqrt();
190 *dst = (f64::from(v) * scale) as f32;
191 }
192 Ok(())
193 }
194 (HoaNormalization::N3d, HoaNormalization::Sn3d) => {
195 for (acn, (&v, dst)) in src.iter().zip(out.iter_mut()).enumerate() {
196 let l = (acn as f64).sqrt().floor();
197 let scale = 1.0 / (2.0 * l + 1.0).sqrt();
198 *dst = (f64::from(v) * scale) as f32;
199 }
200 Ok(())
201 }
202 _ => Err(ProfileError::InvalidDomainConversion(
203 "use explicit FuMa<->ACN helpers for MaxN/FuMa",
204 )),
205 }
206}
207
208pub fn acn_sn3d_to_fuma_maxn(order: u8, acn_sn3d: &[f32], fuma_out: &mut [f32]) -> Result<(), ProfileError> {
210 let ch = hoa_channel_count(order)? as usize;
211 if acn_sn3d.len() != ch || fuma_out.len() != ch {
212 return Err(ProfileError::InvalidPayloadLength);
213 }
214 if acn_sn3d.iter().any(|v| !v.is_finite()) {
215 return Err(ProfileError::NonFiniteFloat);
216 }
217 let inv_sqrt2 = 0.5f64.sqrt();
218 fuma_out[0] = (f64::from(acn_sn3d[0]) * inv_sqrt2) as f32;
220 if order >= 1 {
221 fuma_out[1] = acn_sn3d[3];
223 fuma_out[2] = acn_sn3d[1];
224 fuma_out[3] = acn_sn3d[2];
225 }
226 if order >= 2 {
227 let s2_3 = (4.0 / 3.0f64).sqrt();
229 fuma_out[4] = acn_sn3d[6];
230 fuma_out[5] = (f64::from(acn_sn3d[7]) * s2_3) as f32;
231 fuma_out[6] = (f64::from(acn_sn3d[5]) * s2_3) as f32;
232 fuma_out[7] = (f64::from(acn_sn3d[8]) * s2_3) as f32;
233 fuma_out[8] = (f64::from(acn_sn3d[4]) * s2_3) as f32;
234 }
235 if order >= 3 {
236 let f1 = (45.0 / 32.0f64).sqrt();
238 let f2 = (9.0 / 5.0f64).sqrt();
239 let f3 = (8.0 / 5.0f64).sqrt();
240 fuma_out[9] = acn_sn3d[12];
241 fuma_out[10] = (f64::from(acn_sn3d[13]) * f1) as f32;
242 fuma_out[11] = (f64::from(acn_sn3d[11]) * f1) as f32;
243 fuma_out[12] = (f64::from(acn_sn3d[14]) * f2) as f32;
244 fuma_out[13] = (f64::from(acn_sn3d[10]) * f2) as f32;
245 fuma_out[14] = (f64::from(acn_sn3d[15]) * f3) as f32;
246 fuma_out[15] = (f64::from(acn_sn3d[9]) * f3) as f32;
247 }
248 Ok(())
249}
250
251pub fn rotate_acn_sn3d_frame(
256 order: u8,
257 q: &QuaternionXyzw,
258 src: &[f32],
259 out: &mut [f32],
260) -> Result<(), ProfileError> {
261 let ch = hoa_channel_count(order)? as usize;
262 if src.len() != ch || out.len() != ch {
263 return Err(ProfileError::InvalidPayloadLength);
264 }
265 if src.iter().any(|v| !v.is_finite()) {
266 return Err(ProfileError::NonFiniteFloat);
267 }
268 let sqrt30 = 30.0f64.sqrt();
269 let x1 = ((15.0 - 2.0 * sqrt30) / 35.0).sqrt();
270 let x2 = ((15.0 + 2.0 * sqrt30) / 35.0).sqrt();
271 let w1 = (18.0 + sqrt30) / 36.0;
272 let w2 = (18.0 - sqrt30) / 36.0;
273 let gl_nodes = [(-x2, w2), (-x1, w1), (x1, w1), (x2, w2)];
274
275 let mut d_mat = [0.0f64; HOA_MAX_CHANNELS * HOA_MAX_CHANNELS];
276 let d_phi = 2.0 * PI / 8.0;
277
278 for &(mu, w_mu) in &gl_nodes {
279 let r_xy = (1.0 - mu * mu).max(0.0).sqrt();
280 for k in 0..8 {
281 let phi = (k as f64) * d_phi;
282 let n_dir = [r_xy * phi.cos(), r_xy * phi.sin(), mu];
283 let rot_dir = q.rotate_vec3(n_dir);
284 let y_n = evaluate_acn_sn3d_dir(order, n_dir)?;
285 let y_rot = evaluate_acn_sn3d_dir(order, rot_dir)?;
286 let w_omega = w_mu * d_phi;
287
288 for l in 0..=usize::from(order) {
289 let start = l * l;
290 let end = (l + 1) * (l + 1);
291 let factor = ((2 * l + 1) as f64 / (4.0 * PI)) * w_omega;
292 for mp in start..end {
293 for m in start..end {
294 d_mat[mp * HOA_MAX_CHANNELS + m] += factor * y_rot[mp] * y_n[m];
295 }
296 }
297 }
298 }
299 }
300
301 for (mp, slot) in out.iter_mut().enumerate().take(ch) {
302 let mut acc = 0.0f64;
303 for (m, &v) in src.iter().enumerate() {
304 acc += d_mat[mp * HOA_MAX_CHANNELS + m] * f64::from(v);
305 }
306 *slot = acc as f32;
307 }
308 Ok(())
309}
310
311pub struct HoaChunkView<'a> {
313 bytes: &'a [u8],
314 order: u8,
315 channels: usize,
316 stride: usize,
317 mask: Option<&'a [u8]>,
318}
319
320impl<'a> HoaChunkView<'a> {
321 pub fn frame_count(&self) -> usize {
322 self.bytes.len() / self.stride
323 }
324
325 pub fn order(&self) -> u8 {
326 self.order
327 }
328
329 pub fn channels(&self) -> usize {
330 self.channels
331 }
332
333 pub fn read_frame(&self, index: usize, out: &mut [f32]) -> Result<(), ProfileError> {
334 if out.len() != self.channels {
335 return Err(ProfileError::InvalidPayloadLength);
336 }
337 let start = index.checked_mul(self.stride).ok_or(ProfileError::Overflow)?;
338 let end = start.checked_add(self.stride).ok_or(ProfileError::Overflow)?;
339 let slice = self
340 .bytes
341 .get(start..end)
342 .ok_or(ProfileError::OutOfBoundsIndex("hoa frame"))?;
343 let ext_valid = self.mask.map_or(true, |m| m[index] != 0);
344 for (i, dst) in out.iter_mut().enumerate() {
345 let v = read_f32_finite(slice, i * 4)?;
346 require_zero_when_masked(ext_valid, v)?;
347 *dst = v;
348 }
349 Ok(())
350 }
351}
352
353#[derive(Debug, Clone)]
355pub struct HoaProfileSpec<'a> {
356 pub order: u8,
357 pub ordering: HoaOrdering,
358 pub normalization: HoaNormalization,
359 pub direction_convention: HoaDirectionConvention,
360 pub units: &'a str,
361 pub sample_rate: RationalRate,
362}
363
364pub fn write_hoa_temporal_qac(
366 frames: &[&[f32]],
367 spec: &HoaProfileSpec<'_>,
368 clock: &ClockSpec,
369 frame: &FrameSpec<'_>,
370 provenance: &ProvenanceSpec<'_>,
371 validity_mask: Option<&[u8]>,
372 limits: ProfileLimits,
373) -> Result<Vec<u8>, ProfileError> {
374 if frames.is_empty() {
375 return Err(ProfileError::InvalidPayloadLength);
376 }
377 if spec.ordering == HoaOrdering::FuMa && spec.normalization == HoaNormalization::Sn3d {
378 return Err(ProfileError::InvalidMetadata("FuMa cannot claim SN3D normalization"));
379 }
380 let ch = hoa_channel_count(spec.order)? as usize;
381 let stride = ch * 4;
382 if let Some(m) = validity_mask {
383 if m.len() != frames.len() || m.iter().any(|&b| b > 1) {
384 return Err(ProfileError::InvalidValidityBits);
385 }
386 }
387 let mut payload = vec![0u8; frames.len() * stride];
388 for (idx, row) in frames.iter().enumerate() {
389 if row.len() != ch {
390 return Err(ProfileError::InvalidPayloadLength);
391 }
392 let ext_valid = validity_mask.map_or(true, |m| m[idx] != 0);
393 for (c, &v) in row.iter().enumerate() {
394 if !v.is_finite() {
395 return Err(ProfileError::NonFiniteFloat);
396 }
397 require_zero_when_masked(ext_valid, v)?;
398 write_f32_finite(&mut payload, idx * stride + c * 4, v)?;
399 }
400 }
401
402 let mut meta = MetadataBuilder::new();
403 meta.push_clock(1, clock)?;
404 meta.push_frame(2, frame)?;
405 meta.push_provenance(3, provenance)?;
406 meta.push_block(OwnedBlock {
407 id: 4,
408 schema_type: 204,
409 revision: 1,
410 critical: true,
411 fields: vec![
412 OwnedField::crit(1, OwnedValue::Utf8("HOA".to_owned())),
413 OwnedField::crit(2, OwnedValue::U32(vec![u32::from(spec.order)])),
414 OwnedField::crit(3, OwnedValue::Utf8(spec.ordering.as_str().to_owned())),
415 OwnedField::crit(4, OwnedValue::Utf8(spec.normalization.as_str().to_owned())),
416 OwnedField::opt(13, OwnedValue::MetadataRefs(vec![2])),
417 ],
418 })?;
419 let shape = [frames.len() as u64, ch as u64];
420 meta.push_model_grid(
421 5,
422 &ModelGridSpec {
423 model_uri: spec.direction_convention.as_str(),
424 model_version: "1",
425 discretization: Some("hoa-time-domain"),
426 component_offsets_xyz: &[],
427 component_time_offset_num: &[],
428 component_time_offset_den: &[],
429 timestep: Some(spec.sample_rate),
430 tolerance_abs: None,
431 tolerance_rel: None,
432 tensor_shape: &shape,
433 component_names: spec.ordering.as_str(),
434 },
435 )?;
436
437 let valid_count = validity_mask.map(|m| m.iter().filter(|&&b| b == 1).count() as u64);
438 let mask_entry_idx = if validity_mask.is_some() { Some(2) } else { None };
439 let ext = [4u32, 5u32];
440 meta.push_descriptor(
441 6,
442 &DescriptorSpec {
443 clock_id: Some(1),
444 frame_id: Some(2),
445 provenance_id: 3,
446 medium_id: None,
447 transform_id: None,
448 calibration_id: None,
449 quantity: "hoa-temporal-coefficients",
450 units: spec.units,
451 channels: Some(ch as u32),
452 layout: Some("time-channel"),
453 scalar: Some(AuxScalar::F32),
454 model_uri: "urn:qac:mode:0x0102:v1",
455 sample_rate: Some(spec.sample_rate),
456 valid_record_count: valid_count,
457 validity_mask_entry: mask_entry_idx,
458 source_entries: &[],
459 extension_metadata: &ext,
460 },
461 )?;
462
463 let mut entries = vec![OwnedEntry {
464 mode: MODE_HOA_SPATIAL,
465 flags: 3,
466 stream_id: 1,
467 frame_id: 2,
468 start_tick: 0,
469 time_count: frames.len() as u64,
470 spatial_key: 0,
471 record_count: frames.len() as u64,
472 stride: stride as u32,
473 descriptor_id: 6,
474 payload,
475 }];
476 if let Some(mask) = validity_mask {
477 entries.push(push_validity_mask_entry(
478 &mut meta,
479 7,
480 3,
481 1,
482 0,
483 frames.len() as u64,
484 mask,
485 )?);
486 }
487 assemble_qac_v1(&meta, &entries, limits)
488}
489
490pub struct HoaTemporalView<'a> {
491 pub chunk: HoaChunkView<'a>,
492 pub order: u8,
493 pub ordering: HoaOrdering,
494 pub normalization: HoaNormalization,
495 pub domain: HoaDomain,
496}
497
498pub fn read_hoa_temporal_qac<'a>(
500 bytes: &'a [u8],
501 entry_index: u32,
502 limits: ProfileLimits,
503) -> Result<HoaTemporalView<'a>, ProfileError> {
504 let env = AdmittedEnvelope::open_alloc(bytes, limits)?;
505 let e = env.entry(entry_index)?;
506 if e.mode() == MODE_STFT_PRESERVATION {
507 return Err(ProfileError::InvalidDomainConversion(
508 "mode 0x0101 is spectral HOA/STFT, not temporal HOA mode 0x0102",
509 ));
510 }
511 if e.mode() != MODE_HOA_SPATIAL {
512 return Err(ProfileError::InvalidMode(e.mode()));
513 }
514 let desc = env.descriptor_for_entry(e)?;
515 if field_opt(desc, 5).is_some() {
516 return Err(ProfileError::InvalidDomainConversion(
517 "temporal HOA mode 0x0102 must not attach spectral Schema 201 transform",
518 ));
519 }
520 let s204 = env
521 .extension_block(desc, 204)?
522 .ok_or(ProfileError::MissingRequiredSchema(204))?;
523 if field_str(field_req(s204, 1)?)? != "HOA" {
524 return Err(ProfileError::InvalidMetadata("Schema 204 representation must be HOA"));
525 }
526 let order_u32 = field_u32(field_req(s204, 2)?)?;
527 let order = u8::try_from(order_u32).map_err(|_| ProfileError::InvalidMetadata("hoa_order"))?;
528 let ordering = HoaOrdering::parse(field_str(field_req(s204, 3)?)?)?;
529 let normalization = HoaNormalization::parse(field_str(field_req(s204, 4)?)?)?;
530 let expected_ch = hoa_channel_count(order)?;
531 let expected_stride = hoa_stride_bytes(order)?;
532 if field_u32(field_req(desc, 9)?)? != expected_ch
533 || field_u32(field_req(desc, 11)?)? != AuxScalar::F32 as u32
534 || e.stride() != expected_stride
535 {
536 return Err(ProfileError::InvalidStride {
537 expected: expected_stride,
538 actual: e.stride(),
539 });
540 }
541 let s205 = env
542 .extension_block(desc, 205)?
543 .ok_or(ProfileError::MissingRequiredSchema(205))?;
544 let shape = field_u64_vec(field_req(s205, 14)?)?;
545 if shape.len() != 2 || shape[0] != e.record_count() || shape[1] != u64::from(expected_ch) {
546 return Err(ProfileError::InvalidMetadata("HOA tensor_shape mismatch"));
547 }
548 let payload = env.verify_chunk(entry_index)?;
549 let mask = env.read_validity_mask(desc, e.record_count())?;
550 let chunk = HoaChunkView {
551 bytes: payload,
552 order,
553 channels: expected_ch as usize,
554 stride: expected_stride as usize,
555 mask,
556 };
557 let mut scratch_frame = vec![0.0f32; expected_ch as usize];
558 for i in 0..chunk.frame_count() {
559 chunk.read_frame(i, &mut scratch_frame)?;
560 }
561 Ok(HoaTemporalView {
562 chunk,
563 order,
564 ordering,
565 normalization,
566 domain: HoaDomain::TimeSample,
567 })
568}