Skip to main content

qualia_core_db/audio/qac/profiles/
modal.rs

1//! Q06 Mode `0x0104`: Damped acoustic modal resonance bank (`32 B` per mode).
2//!
3//! Enforces positive frequency, signed finite amplitude preservation, nonnegative decay `d`
4//! with exact amplitude `T60 = ln(1000)/d` (`d = 0 => None`, never `+inf`), explicit mode shape
5//! and excitation coupling arrays (`0x0107`), explicit silence/unvoiced status, and clean
6//! disambiguation from `0x0104` opaque byte preservation (`stride 1` vs `stride 32` + `Schema 206`).
7
8use std::f64::consts::PI;
9
10use super::envelope::*;
11use super::ray_rir::push_aux_f32_entry;
12use super::types::*;
13
14pub const MODAL_RECORD_STRIDE: u32 = 32;
15
16/// Exact 32-byte wire record for `mode 0x0104` (`modal_resonance`).
17#[derive(Debug, Clone, Copy, PartialEq)]
18pub struct ModalRecord {
19    pub frequency_hz: f32,
20    pub amplitude_pa: f32,
21    pub decay_rate_s1: f32,
22    pub phase_rad: f32,
23    pub mode_shape_index: u32,
24    pub material_ref: u32,
25    pub excitation_index: u32,
26}
27
28impl ModalRecord {
29    pub fn validate(&self, externally_valid: bool) -> Result<(), ProfileError> {
30        if !self.frequency_hz.is_finite()
31            || !self.amplitude_pa.is_finite()
32            || !self.decay_rate_s1.is_finite()
33            || !self.phase_rad.is_finite()
34        {
35            return Err(ProfileError::NonFiniteFloat);
36        }
37        if !externally_valid {
38            if self.frequency_hz.to_bits() != 0
39                || self.amplitude_pa.to_bits() != 0
40                || self.decay_rate_s1.to_bits() != 0
41                || self.phase_rad.to_bits() != 0
42            {
43                return Err(ProfileError::MaskedLaneNonZero);
44            }
45            return Ok(());
46        }
47        if self.frequency_hz <= 0.0 {
48            return Err(ProfileError::InvalidMetadata("modal frequency_hz must be > 0"));
49        }
50        if self.decay_rate_s1 < 0.0 {
51            return Err(ProfileError::InvalidMetadata("modal decay_rate_s1 must be >= 0"));
52        }
53        Ok(())
54    }
55
56    pub fn decode(bytes: &[u8], externally_valid: bool) -> Result<Self, ProfileError> {
57        if bytes.len() != MODAL_RECORD_STRIDE as usize {
58            return Err(ProfileError::InvalidPayloadLength);
59        }
60        if read_u32(bytes, 28)? != 0 {
61            return Err(ProfileError::NonZeroPadding);
62        }
63        let rec = Self {
64            frequency_hz: read_f32_finite(bytes, 0)?,
65            amplitude_pa: read_f32_finite(bytes, 4)?,
66            decay_rate_s1: read_f32_finite(bytes, 8)?,
67            phase_rad: read_f32_finite(bytes, 12)?,
68            mode_shape_index: read_u32(bytes, 16)?,
69            material_ref: read_u32(bytes, 20)?,
70            excitation_index: read_u32(bytes, 24)?,
71        };
72        rec.validate(externally_valid)?;
73        Ok(rec)
74    }
75
76    pub fn encode_into(&self, out: &mut [u8], externally_valid: bool) -> Result<(), ProfileError> {
77        if out.len() != MODAL_RECORD_STRIDE as usize {
78            return Err(ProfileError::InvalidPayloadLength);
79        }
80        self.validate(externally_valid)?;
81        out.fill(0);
82        write_f32_finite(out, 0, self.frequency_hz)?;
83        write_f32_finite(out, 4, self.amplitude_pa)?;
84        write_f32_finite(out, 8, self.decay_rate_s1)?;
85        write_f32_finite(out, 12, self.phase_rad)?;
86        write_u32(out, 16, self.mode_shape_index);
87        write_u32(out, 20, self.material_ref);
88        write_u32(out, 24, self.excitation_index);
89        write_u32(out, 28, 0);
90        Ok(())
91    }
92
93    /// Critical damping ratio `zeta = d / (2 * pi * f)`.
94    pub fn damping_ratio(&self) -> Result<f64, ProfileError> {
95        self.validate(true)?;
96        Ok(f64::from(self.decay_rate_s1) / (2.0 * PI * f64::from(self.frequency_hz)))
97    }
98
99    /// Exact amplitude decay `T60 = ln(1000) / d = 3*ln(10)/d` (`-60 dB` amplitude and energy).
100    /// Returns `Ok(None)` when `decay_rate_s1 == 0.0` (never `+inf`).
101    pub fn t60_seconds(&self) -> Result<Option<f64>, ProfileError> {
102        self.validate(true)?;
103        if self.decay_rate_s1 == 0.0 {
104            return Ok(None);
105        }
106        Ok(Some(1000.0f64.ln() / f64::from(self.decay_rate_s1)))
107    }
108
109    /// Evaluates damped sinusoidal response `A * exp(-d * t) * sin(2 * pi * f * t + phi)`.
110    pub fn evaluate_at(&self, t_s: f64) -> Result<f64, ProfileError> {
111        if !t_s.is_finite() || t_s < 0.0 {
112            return Err(ProfileError::InvalidTimeSpec);
113        }
114        self.validate(true)?;
115        let amp = f64::from(self.amplitude_pa);
116        let d = f64::from(self.decay_rate_s1);
117        let f = f64::from(self.frequency_hz);
118        let phi = f64::from(self.phase_rad);
119        Ok(amp * (-d * t_s).exp() * (2.0 * PI * f * t_s + phi).sin())
120    }
121}
122
123/// Evaluates modal synthesis output at `t_s >= 0` for receiver `dof`, multiplying each valid mode
124/// by its mode-shape coupling `mode_shapes[mode_shape_index * dofs + dof]` and excitation weight.
125pub fn synthesize_modal_sample(
126    modes: &[ModalRecord],
127    statuses: Option<&[SampleStatus]>,
128    mode_shapes: &[f32],
129    dofs: usize,
130    dof: usize,
131    excitations: &[f32],
132    t_s: f64,
133) -> Result<f64, ProfileError> {
134    if dofs == 0 || dof >= dofs || mode_shapes.len() % dofs != 0 {
135        return Err(ProfileError::OutOfBoundsIndex("modal dof/shapes"));
136    }
137    if let Some(st) = statuses {
138        if st.len() != modes.len() {
139            return Err(ProfileError::InvalidPayloadLength);
140        }
141    }
142    let shape_rows = mode_shapes.len() / dofs;
143    let mut sum = 0.0f64;
144    for (idx, m) in modes.iter().enumerate() {
145        let is_valid = statuses.map_or(true, |s| s[idx] == SampleStatus::Valid);
146        m.validate(is_valid)?;
147        if !is_valid {
148            continue;
149        }
150        if (m.mode_shape_index as usize) >= shape_rows {
151            return Err(ProfileError::OutOfBoundsIndex("mode_shape_index"));
152        }
153        if (m.excitation_index as usize) >= excitations.len() {
154            return Err(ProfileError::OutOfBoundsIndex("excitation_index"));
155        }
156        let shape_w = f64::from(mode_shapes[m.mode_shape_index as usize * dofs + dof]);
157        let exc_w = f64::from(excitations[m.excitation_index as usize]);
158        sum += shape_w * exc_w * m.evaluate_at(t_s)?;
159    }
160    Ok(sum)
161}
162
163/// Zero-heap borrowed view over verified `0x0104` modal oscillator records.
164pub struct ModalChunkView<'a> {
165    bytes: &'a [u8],
166    mask: Option<&'a [u8]>,
167}
168
169impl<'a> ModalChunkView<'a> {
170    pub fn len(&self) -> usize {
171        self.bytes.len() / MODAL_RECORD_STRIDE as usize
172    }
173
174    pub fn is_empty(&self) -> bool {
175        self.bytes.is_empty()
176    }
177
178    pub fn get(&self, index: usize) -> Result<ModalRecord, ProfileError> {
179        let start = index
180            .checked_mul(MODAL_RECORD_STRIDE as usize)
181            .ok_or(ProfileError::Overflow)?;
182        let end = start
183            .checked_add(MODAL_RECORD_STRIDE as usize)
184            .ok_or(ProfileError::Overflow)?;
185        let slice = self
186            .bytes
187            .get(start..end)
188            .ok_or(ProfileError::OutOfBoundsIndex("modal record"))?;
189        let ext_valid = self.mask.map_or(true, |m| m[index] != 0);
190        ModalRecord::decode(slice, ext_valid)
191    }
192}
193
194/// Writes canonical QAC v1 `mode 0x0104` modal bank (`Schema 206`), required `mode_shapes` &
195/// `excitation` (`0x0107`) arrays, optional `0x0106` validity mask, and optional per-mode status codes (`0x0107`).
196pub fn write_modal_bank_qac(
197    modes: &[ModalRecord],
198    mode_shapes: &[f32],
199    dofs: u32,
200    excitations: &[f32],
201    statuses: Option<&[SampleStatus]>,
202    clock: &ClockSpec,
203    sample_rate: RationalRate,
204    provenance: &ProvenanceSpec<'_>,
205    limits: ProfileLimits,
206) -> Result<Vec<u8>, ProfileError> {
207    if modes.is_empty()
208        || dofs == 0
209        || mode_shapes.is_empty()
210        || mode_shapes.len() % (dofs as usize) != 0
211        || excitations.is_empty()
212    {
213        return Err(ProfileError::InvalidPayloadLength);
214    }
215    let shape_rows = mode_shapes.len() / (dofs as usize);
216    if let Some(st) = statuses {
217        if st.len() != modes.len() {
218            return Err(ProfileError::InvalidPayloadLength);
219        }
220    }
221    let mask_bytes: Option<Vec<u8>> = statuses.map(|st| {
222        st.iter()
223            .map(|&s| if s == SampleStatus::Valid { 1 } else { 0 })
224            .collect()
225    });
226    let mut main_payload = vec![0u8; modes.len() * MODAL_RECORD_STRIDE as usize];
227    for (idx, m) in modes.iter().enumerate() {
228        let valid = mask_bytes.as_ref().map_or(true, |mb| mb[idx] != 0);
229        if (m.mode_shape_index as usize) >= shape_rows {
230            return Err(ProfileError::OutOfBoundsIndex("mode_shape_index"));
231        }
232        if (m.excitation_index as usize) >= excitations.len() {
233            return Err(ProfileError::OutOfBoundsIndex("excitation_index"));
234        }
235        let off = idx * MODAL_RECORD_STRIDE as usize;
236        m.encode_into(&mut main_payload[off..off + MODAL_RECORD_STRIDE as usize], valid)?;
237    }
238
239    let mut meta = MetadataBuilder::new();
240    meta.push_clock(1, clock)?;
241    meta.push_provenance(3, provenance)?;
242
243    // Canonical directory order with stream_id=1:
244    // Entry 1: mode 0x0104 (descriptor 6)
245    // Entry 2 (optional mask): mode 0x0106 (descriptor 7)
246    // Aux entries (desc 8 excitation, desc 9 mode_shapes, desc 10 optional status): mode 0x0107
247    // Note: 0x0104 < 0x0106 < 0x0107! Putting all in stream_id=1 ensures Entry 1 is index 1,
248    // mask (if any) is index 2, excitation is index 2 or 3, mode_shapes is index 3 or 4!
249    let mut next_idx = 2u32;
250    let mask_idx = if mask_bytes.is_some() {
251        let idx = next_idx;
252        next_idx += 1;
253        Some(idx)
254    } else {
255        None
256    };
257    let exc_idx = next_idx;
258    next_idx += 1;
259    let shapes_idx = next_idx;
260    next_idx += 1;
261    let status_idx = if statuses.is_some() {
262        Some(next_idx)
263    } else {
264        None
265    };
266
267    meta.push_block(OwnedBlock {
268        id: 4,
269        schema_type: 206,
270        revision: 1,
271        critical: true,
272        fields: vec![
273            OwnedField::crit(1, OwnedValue::Utf8("modal_bank".to_owned())),
274            OwnedField::crit(8, OwnedValue::EntryRefs(vec![exc_idx])),
275            OwnedField::crit(9, OwnedValue::EntryRefs(vec![shapes_idx])),
276        ],
277    })?;
278    let tensor_shape = [modes.len() as u64];
279    meta.push_model_grid(
280        5,
281        &ModelGridSpec {
282            model_uri: "urn:qac:model:modal-resonance-bank:v1",
283            model_version: "1",
284            discretization: Some("damped-harmonic-modes"),
285            component_offsets_xyz: &[],
286            component_time_offset_num: &[],
287            component_time_offset_den: &[],
288            timestep: Some(sample_rate),
289            tolerance_abs: None,
290            tolerance_rel: None,
291            tensor_shape: &tensor_shape,
292            component_names: "frequency_hz,amplitude_pa,decay_rate_s1,phase_rad",
293        },
294    )?;
295
296    let valid_count = mask_bytes
297        .as_ref()
298        .map(|mb| mb.iter().filter(|&&b| b == 1).count() as u64);
299    let ext = [4u32, 5u32];
300    meta.push_descriptor(
301        6,
302        &DescriptorSpec {
303            clock_id: Some(1),
304            frame_id: None,
305            provenance_id: 3,
306            medium_id: None,
307            transform_id: None,
308            calibration_id: None,
309            quantity: "modal-resonance",
310            units: "Pa",
311            channels: None,
312            layout: None,
313            scalar: None,
314            model_uri: "urn:qac:mode:0x0104:modal-resonance:v1",
315            sample_rate: Some(sample_rate),
316            valid_record_count: valid_count,
317            validity_mask_entry: mask_idx,
318            source_entries: &[],
319            extension_metadata: &ext,
320        },
321    )?;
322
323    let mut entries = vec![OwnedEntry {
324        mode: MODE_MODAL_RESONANCE,
325        flags: 3,
326        stream_id: 1,
327        frame_id: 0,
328        start_tick: 0,
329        time_count: 1,
330        spatial_key: 0,
331        record_count: modes.len() as u64,
332        stride: MODAL_RECORD_STRIDE,
333        descriptor_id: 6,
334        payload: main_payload,
335    }];
336    if let Some(mb) = &mask_bytes {
337        entries.push(push_validity_mask_entry(&mut meta, 7, 3, 1, 0, 1, mb)?);
338    }
339    let mut e_exc = push_aux_f32_entry(&mut meta, 8, 3, "modal-excitation", "1", 1, AuxScalar::F32, excitations)?;
340    e_exc.stream_id = 1;
341    let mut e_shapes = push_aux_f32_entry(&mut meta, 9, 3, "modal-mode-shapes", "1", dofs, AuxScalar::F32, mode_shapes)?;
342    e_shapes.stream_id = 1;
343    entries.push(e_exc);
344    entries.push(e_shapes);
345
346    if let (Some(st), Some(_)) = (statuses, status_idx) {
347        let status_u8: Vec<u8> = st.iter().map(|&s| s as u8).collect();
348        meta.push_descriptor(
349            10,
350            &DescriptorSpec {
351                clock_id: None,
352                frame_id: None,
353                provenance_id: 3,
354                medium_id: None,
355                transform_id: None,
356                calibration_id: None,
357                quantity: "modal-sample-status",
358                units: "1",
359                channels: Some(1),
360                layout: Some("record-component"),
361                scalar: Some(AuxScalar::U8),
362                model_uri: "urn:qac:mode:0x0107:sample-status:v1",
363                sample_rate: None,
364                valid_record_count: None,
365                validity_mask_entry: None,
366                source_entries: &[],
367                extension_metadata: &[],
368            },
369        )?;
370        entries.push(OwnedEntry {
371            mode: MODE_AUX_ARRAY,
372            flags: 1,
373            stream_id: 1,
374            frame_id: 0,
375            start_tick: 0,
376            time_count: 0,
377            spatial_key: 0,
378            record_count: status_u8.len() as u64,
379            stride: 1,
380            descriptor_id: 10,
381            payload: status_u8,
382        });
383    }
384    assemble_qac_v1(&meta, &entries, limits)
385}
386
387pub struct ModalBankView<'a> {
388    pub records: ModalChunkView<'a>,
389    pub mode_shapes: Vec<f32>,
390    pub shape_dofs: usize,
391    pub excitations: Vec<f32>,
392}
393
394/// Reads and validates a `mode 0x0104` modal resonance bank.
395/// Rejects `opaque_source_preservation` (`stride == 1` / missing Schema 206) without conflation.
396pub fn read_modal_bank_qac<'a>(
397    bytes: &'a [u8],
398    entry_index: u32,
399    limits: ProfileLimits,
400) -> Result<ModalBankView<'a>, ProfileError> {
401    let env = AdmittedEnvelope::open_alloc(bytes, limits)?;
402    let (_e, desc, payload, mask) = env.check_structured_entry(
403        entry_index,
404        MODE_MODAL_RESONANCE,
405        MODAL_RECORD_STRIDE,
406        false,
407        Some(206),
408    )?;
409    let s206 = env
410        .extension_block(desc, 206)?
411        .ok_or(ProfileError::MissingRequiredSchema(206))?;
412    if field_str(field_req(s206, 1)?)? != "modal_bank" {
413        return Err(ProfileError::InvalidMetadata("Schema 206 kind must be modal_bank"));
414    }
415    let exc_idx = field_u32(field_req(s206, 8)?)?;
416    let exc_bytes = env.verify_chunk(exc_idx)?;
417    if exc_bytes.len() % 4 != 0 || exc_bytes.is_empty() {
418        return Err(ProfileError::InvalidPayloadLength);
419    }
420    let mut excitations = Vec::with_capacity(exc_bytes.len() / 4);
421    for i in 0..exc_bytes.len() / 4 {
422        excitations.push(read_f32_finite(exc_bytes, i * 4)?);
423    }
424
425    let shp_idx = field_u32(field_req(s206, 9)?)?;
426    let shp_entry = env.entry(shp_idx)?;
427    let shp_desc = env.descriptor_for_entry(shp_entry)?;
428    let shape_dofs = field_u32(field_req(shp_desc, 9)?)? as usize;
429    if shape_dofs == 0 {
430        return Err(ProfileError::InvalidMetadata("mode_shapes dofs == 0"));
431    }
432    let shp_bytes = env.verify_chunk(shp_idx)?;
433    if shp_bytes.len() % (shape_dofs * 4) != 0 || shp_bytes.is_empty() {
434        return Err(ProfileError::InvalidPayloadLength);
435    }
436    let mut mode_shapes = Vec::with_capacity(shp_bytes.len() / 4);
437    for i in 0..shp_bytes.len() / 4 {
438        mode_shapes.push(read_f32_finite(shp_bytes, i * 4)?);
439    }
440    let shape_rows = mode_shapes.len() / shape_dofs;
441
442    let chunk = ModalChunkView {
443        bytes: payload,
444        mask,
445    };
446    for i in 0..chunk.len() {
447        let rec = chunk.get(i)?;
448        if (rec.mode_shape_index as usize) >= shape_rows {
449            return Err(ProfileError::OutOfBoundsIndex("mode_shape_index"));
450        }
451        if (rec.excitation_index as usize) >= excitations.len() {
452            return Err(ProfileError::OutOfBoundsIndex("excitation_index"));
453        }
454    }
455    Ok(ModalBankView {
456        records: chunk,
457        mode_shapes,
458        shape_dofs,
459        excitations,
460    })
461}