Skip to main content

qualia_core_db/audio/qac/profiles/
ray_rir.rs

1//! Q05 Mode `0x0003`: Ray / RIR path contributions (`64 B`) with band transfer, phase, and diffraction metadata.
2//!
3//! Strictly enforces unit direction norm (`<= 1e-5` in `f64`), nonnegative distance/delay,
4//! energy-ratio vs signed/complex pressure amplitude distinction (never inventing phase from energy),
5//! explicit diffraction models (`none`, `UTD-wedge`, `BTM-aperture`), and bounds-checked `band_row`.
6
7use super::envelope::*;
8use super::types::*;
9
10pub const RAY_RECORD_STRIDE: u32 = 64;
11pub const RAY_VALID_DELAY: u32 = 1 << 0;
12pub const RAY_VALID_DOPPLER: u32 = 1 << 1;
13pub const RAY_VALID_ALL: u32 = RAY_VALID_DELAY | RAY_VALID_DOPPLER;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum GainQuantity {
17    EnergyRatio,
18    PressureAmplitudeRatio,
19}
20
21impl GainQuantity {
22    pub const fn as_str(self) -> &'static str {
23        match self {
24            Self::EnergyRatio => "energy-ratio",
25            Self::PressureAmplitudeRatio => "pressure-amplitude-ratio",
26        }
27    }
28
29    pub fn parse(s: &str) -> Result<Self, ProfileError> {
30        match s {
31            "energy-ratio" => Ok(Self::EnergyRatio),
32            "pressure-amplitude-ratio" => Ok(Self::PressureAmplitudeRatio),
33            _ => Err(ProfileError::InvalidMetadata("gain_quantity")),
34        }
35    }
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub enum DiffractionModel {
40    None,
41    UtdWedge,
42    BtmAperture,
43}
44
45impl DiffractionModel {
46    pub const fn as_str(self) -> &'static str {
47        match self {
48            Self::None => "none",
49            Self::UtdWedge => "UTD-wedge",
50            Self::BtmAperture => "BTM-aperture",
51        }
52    }
53
54    pub fn parse(s: &str) -> Result<Self, ProfileError> {
55        match s {
56            "none" => Ok(Self::None),
57            "UTD-wedge" => Ok(Self::UtdWedge),
58            "BTM-aperture" => Ok(Self::BtmAperture),
59            _ => Err(ProfileError::InvalidMetadata("diffraction_model")),
60        }
61    }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum BandPhaseModel {
66    /// Non-negative broadband energy scalars (`EnergyRatio` only); no phase information present.
67    EnergyOnlyNoPhase,
68    /// Real signed pressure amplitude ratios preserving 0 / pi phase inversions.
69    SignedAmplitudeReal,
70    /// Complex `[re, im]` transfer values per `[ray, band]`.
71    ComplexPerBandTransfer,
72}
73
74/// Exact 64-byte wire record for `mode 0x0003` (`RayContribution`).
75#[derive(Debug, Clone, Copy, PartialEq)]
76pub struct RayContributionRecord {
77    pub origin_m: [f32; 3],
78    pub distance_m: f32,
79    pub direction: [f32; 3],
80    pub delay_s: f32,
81    pub ray_id: u64,
82    pub band_row: u32,
83    pub material_ref: u32,
84    pub specular_count: u16,
85    pub diffraction_count: u16,
86    pub scattering_coefficient: f32,
87    pub doppler_ratio: f32,
88    pub validity_bits: u32,
89}
90
91impl RayContributionRecord {
92    pub fn validate(&self, externally_valid: bool) -> Result<(), ProfileError> {
93        if self.origin_m.iter().any(|v| !v.is_finite())
94            || !self.distance_m.is_finite()
95            || !self.delay_s.is_finite()
96            || !self.scattering_coefficient.is_finite()
97            || !self.doppler_ratio.is_finite()
98        {
99            return Err(ProfileError::NonFiniteFloat);
100        }
101        if self.validity_bits & !RAY_VALID_ALL != 0 {
102            return Err(ProfileError::InvalidValidityBits);
103        }
104        if !externally_valid {
105            if self.validity_bits != 0
106                || self.origin_m.iter().any(|v| v.to_bits() != 0)
107                || self.distance_m.to_bits() != 0
108                || self.direction.iter().any(|v| v.to_bits() != 0)
109                || self.delay_s.to_bits() != 0
110                || self.scattering_coefficient.to_bits() != 0
111                || self.doppler_ratio.to_bits() != 0
112            {
113                return Err(ProfileError::MaskedLaneNonZero);
114            }
115            return Ok(());
116        }
117        let _ = UnitDirection3::new(self.direction)?;
118        if self.distance_m < 0.0 || !(0.0..=1.0).contains(&self.scattering_coefficient) {
119            return Err(ProfileError::InvalidMetadata("ray distance or scattering range"));
120        }
121        let has_delay = (self.validity_bits & RAY_VALID_DELAY) != 0;
122        require_zero_when_masked(has_delay, self.delay_s)?;
123        if has_delay && self.delay_s < 0.0 {
124            return Err(ProfileError::InvalidMetadata("ray delay_s < 0"));
125        }
126        let has_doppler = (self.validity_bits & RAY_VALID_DOPPLER) != 0;
127        require_zero_when_masked(has_doppler, self.doppler_ratio)?;
128        if has_doppler && self.doppler_ratio <= 0.0 {
129            return Err(ProfileError::InvalidMetadata("ray doppler_ratio <= 0"));
130        }
131        Ok(())
132    }
133
134    pub fn decode(bytes: &[u8], externally_valid: bool) -> Result<Self, ProfileError> {
135        if bytes.len() != RAY_RECORD_STRIDE as usize {
136            return Err(ProfileError::InvalidPayloadLength);
137        }
138        let rec = Self {
139            origin_m: read_f32_3(bytes, 0)?,
140            distance_m: read_f32_finite(bytes, 12)?,
141            direction: read_f32_3(bytes, 16)?,
142            delay_s: read_f32_finite(bytes, 28)?,
143            ray_id: read_u64(bytes, 32)?,
144            band_row: read_u32(bytes, 40)?,
145            material_ref: read_u32(bytes, 44)?,
146            specular_count: read_u16(bytes, 48)?,
147            diffraction_count: read_u16(bytes, 50)?,
148            scattering_coefficient: read_f32_finite(bytes, 52)?,
149            doppler_ratio: read_f32_finite(bytes, 56)?,
150            validity_bits: read_u32(bytes, 60)?,
151        };
152        rec.validate(externally_valid)?;
153        Ok(rec)
154    }
155
156    pub fn encode_into(&self, out: &mut [u8], externally_valid: bool) -> Result<(), ProfileError> {
157        if out.len() != RAY_RECORD_STRIDE as usize {
158            return Err(ProfileError::InvalidPayloadLength);
159        }
160        self.validate(externally_valid)?;
161        out.fill(0);
162        write_f32_slice(out, 0, &self.origin_m)?;
163        write_f32_finite(out, 12, self.distance_m)?;
164        write_f32_slice(out, 16, &self.direction)?;
165        write_f32_finite(out, 28, self.delay_s)?;
166        write_u64(out, 32, self.ray_id);
167        write_u32(out, 40, self.band_row);
168        write_u32(out, 44, self.material_ref);
169        write_u16(out, 48, self.specular_count);
170        write_u16(out, 50, self.diffraction_count);
171        write_f32_finite(out, 52, self.scattering_coefficient)?;
172        write_f32_finite(out, 56, self.doppler_ratio)?;
173        write_u32(out, 60, self.validity_bits);
174        Ok(())
175    }
176}
177
178/// Zero-heap borrowed view over verified `0x0003` ray records.
179pub struct RayContributionChunkView<'a> {
180    bytes: &'a [u8],
181    mask: Option<&'a [u8]>,
182}
183
184impl<'a> RayContributionChunkView<'a> {
185    pub fn len(&self) -> usize {
186        self.bytes.len() / RAY_RECORD_STRIDE as usize
187    }
188
189    pub fn is_empty(&self) -> bool {
190        self.bytes.is_empty()
191    }
192
193    pub fn get(&self, index: usize) -> Result<RayContributionRecord, ProfileError> {
194        let start = index
195            .checked_mul(RAY_RECORD_STRIDE as usize)
196            .ok_or(ProfileError::Overflow)?;
197        let end = start
198            .checked_add(RAY_RECORD_STRIDE as usize)
199            .ok_or(ProfileError::Overflow)?;
200        let slice = self
201            .bytes
202            .get(start..end)
203            .ok_or(ProfileError::OutOfBoundsIndex("ray record"))?;
204        let ext_valid = self.mask.map_or(true, |m| m[index] != 0);
205        RayContributionRecord::decode(slice, ext_valid)
206    }
207}
208
209/// Decoded band transfer values preserving energy vs signed vs complex phase distinctions.
210#[derive(Debug, Clone, PartialEq)]
211pub enum RayBandValues {
212    EnergyRatio { bands: usize, values: Vec<f32> },
213    SignedPressureRatio { bands: usize, values: Vec<f32> },
214    ComplexTransfer { bands: usize, re_im: Vec<[f32; 2]> },
215}
216
217impl RayBandValues {
218    pub fn phase_model(&self) -> BandPhaseModel {
219        match self {
220            Self::EnergyRatio { .. } => BandPhaseModel::EnergyOnlyNoPhase,
221            Self::SignedPressureRatio { .. } => BandPhaseModel::SignedAmplitudeReal,
222            Self::ComplexTransfer { .. } => BandPhaseModel::ComplexPerBandTransfer,
223        }
224    }
225
226    pub fn gain_quantity(&self) -> GainQuantity {
227        match self {
228            Self::EnergyRatio { .. } => GainQuantity::EnergyRatio,
229            Self::SignedPressureRatio { .. } | Self::ComplexTransfer { .. } => {
230                GainQuantity::PressureAmplitudeRatio
231            }
232        }
233    }
234
235    pub fn bands(&self) -> usize {
236        match self {
237            Self::EnergyRatio { bands, .. }
238            | Self::SignedPressureRatio { bands, .. }
239            | Self::ComplexTransfer { bands, .. } => *bands,
240        }
241    }
242
243    pub fn row_count(&self) -> usize {
244        let b = self.bands().max(1);
245        match self {
246            Self::EnergyRatio { values, .. } | Self::SignedPressureRatio { values, .. } => {
247                values.len() / b
248            }
249            Self::ComplexTransfer { re_im, .. } => re_im.len() / b,
250        }
251    }
252
253    /// Synthesizes signed broadband impulse contributions per tap from amplitude rays.
254    /// Rejects `EnergyRatio` because energy carries no phase / polarity!
255    pub fn synthesize_signed_rir_impulse(
256        &self,
257        rays: &[RayContributionRecord],
258        band_index: usize,
259        sample_rate_hz: f64,
260        taps: usize,
261    ) -> Result<Vec<f32>, ProfileError> {
262        if matches!(self, Self::EnergyRatio { .. }) {
263            return Err(ProfileError::InvalidDomainConversion(
264                "cannot synthesize phase-bearing signed RIR impulse from energy-only ray gains",
265            ));
266        }
267        if band_index >= self.bands() || !sample_rate_hz.is_finite() || sample_rate_hz <= 0.0 {
268            return Err(ProfileError::OutOfBoundsIndex("band_index"));
269        }
270        let mut ir = vec![0.0f64; taps];
271        let b = self.bands();
272        for r in rays {
273            if (r.validity_bits & RAY_VALID_DELAY) == 0 {
274                continue;
275            }
276            let row = r.band_row as usize;
277            if row >= self.row_count() {
278                return Err(ProfileError::OutOfBoundsIndex("ray band_row"));
279            }
280            let amp = match self {
281                Self::SignedPressureRatio { values, .. } => f64::from(values[row * b + band_index]),
282                Self::ComplexTransfer { re_im, .. } => f64::from(re_im[row * b + band_index][0]),
283                Self::EnergyRatio { .. } => unreachable!(),
284            };
285            let idx = (f64::from(r.delay_s) * sample_rate_hz).round() as usize;
286            if idx < taps {
287                ir[idx] += amp;
288            }
289        }
290        Ok(ir.into_iter().map(|v| v as f32).collect())
291    }
292}
293
294/// Normal-incidence reflection & transmission energy conservation helper:
295/// `R_p = (Z2 - Z1) / (Z2 + Z1)`, `E_reflected = R_p^2`, `E_transmitted = 1 - R_p^2`.
296pub fn planar_impedance_reflection_energy(z1: f64, z2: f64) -> Result<(f64, f64, f64), ProfileError> {
297    if !z1.is_finite() || !z2.is_finite() || z1 <= 0.0 || z2 <= 0.0 {
298        return Err(ProfileError::MediumMissingOrUnknown("positive acoustic impedances required"));
299    }
300    let r_p = (z2 - z1) / (z2 + z1);
301    let e_refl = r_p * r_p;
302    let e_trans = 1.0 - e_refl;
303    Ok((r_p, e_refl, e_trans))
304}
305
306/// Writes canonical QAC v1 `mode 0x0003` rays + auxiliary band centers/values/weights (`0x0107`).
307pub fn write_ray_contributions_qac(
308    rays: &[RayContributionRecord],
309    band_centers_hz: &[f32],
310    band_values: &RayBandValues,
311    reference_distance_m: f64,
312    diffraction: DiffractionModel,
313    ray_weights: Option<&[f32]>,
314    launch_time: Option<&InstantSpec>,
315    clock: &ClockSpec,
316    frame: &FrameSpec<'_>,
317    provenance: &ProvenanceSpec<'_>,
318    limits: ProfileLimits,
319) -> Result<Vec<u8>, ProfileError> {
320    if rays.is_empty() || band_centers_hz.is_empty() || band_centers_hz.len() != band_values.bands() {
321        return Err(ProfileError::InvalidPayloadLength);
322    }
323    if !reference_distance_m.is_finite() || reference_distance_m <= 0.0 {
324        return Err(ProfileError::InvalidMetadata("reference_distance_m <= 0"));
325    }
326    for w in band_centers_hz.windows(2) {
327        if !w[0].is_finite() || !w[1].is_finite() || w[0] <= 0.0 || w[0] >= w[1] {
328            return Err(ProfileError::InvalidMetadata("band_centers_hz must be strictly increasing > 0"));
329        }
330    }
331    let rows = band_values.row_count();
332    if rows == 0 {
333        return Err(ProfileError::InvalidPayloadLength);
334    }
335    if let Some(rw) = ray_weights {
336        if rw.len() != rays.len() || rw.iter().any(|&w| !w.is_finite() || w < 0.0) {
337            return Err(ProfileError::InvalidMetadata("ray_weights"));
338        }
339    }
340    let mut main_payload = vec![0u8; rays.len() * RAY_RECORD_STRIDE as usize];
341    for (i, r) in rays.iter().enumerate() {
342        if r.band_row as usize >= rows {
343            return Err(ProfileError::OutOfBoundsIndex("ray band_row >= rows"));
344        }
345        if diffraction == DiffractionModel::None && r.diffraction_count > 0 {
346            return Err(ProfileError::InvalidMetadata("diffraction_count > 0 under DiffractionModel::None"));
347        }
348        let off = i * RAY_RECORD_STRIDE as usize;
349        r.encode_into(&mut main_payload[off..off + RAY_RECORD_STRIDE as usize], true)?;
350    }
351
352    let mut meta = MetadataBuilder::new();
353    meta.push_clock(1, clock)?;
354    meta.push_frame(2, frame)?;
355    meta.push_provenance(3, provenance)?;
356    let launch_id = if let Some(lt) = launch_time {
357        Some(meta.push_instant(10, lt)?)
358    } else {
359        None
360    };
361
362    // Entries: 1 = 0x0003 rays, 2 = 0x0107 band_centers, 3 = 0x0107 band_values, 4 = optional ray_weights.
363    // All stream_id=0 static or stream_id=1? Use stream_id=0 with 0x0003 < 0x0107 and desc_id 7 < 8 < 9.
364    let e_centers = push_aux_f32_entry(&mut meta, 7, 3, "band-centers-hz", "Hz", 1, AuxScalar::F32, band_centers_hz)?;
365    let e_values = match band_values {
366        RayBandValues::EnergyRatio { values, .. } => {
367            if values.iter().any(|&v| !v.is_finite() || v < 0.0) {
368                return Err(ProfileError::InvalidMetadata("negative energy-ratio band value"));
369            }
370            push_aux_f32_entry(&mut meta, 8, 3, "ray-band-energy", "1", band_values.bands() as u32, AuxScalar::F32, values)?
371        }
372        RayBandValues::SignedPressureRatio { values, .. } => {
373            push_aux_f32_entry(&mut meta, 8, 3, "ray-band-amplitude", "Pa/Pa", band_values.bands() as u32, AuxScalar::F32, values)?
374        }
375        RayBandValues::ComplexTransfer { re_im, .. } => {
376            let mut flat = Vec::with_capacity(re_im.len() * 2);
377            for &[re, im] in re_im {
378                flat.push(re);
379                flat.push(im);
380            }
381            push_aux_f32_entry(&mut meta, 8, 3, "ray-band-complex-transfer", "Pa/Pa", band_values.bands() as u32, AuxScalar::ComplexF32, &flat)?
382        }
383    };
384
385    let mut s206_fields = vec![
386        OwnedField::crit(1, OwnedValue::Utf8("geometric_rays".to_owned())),
387        OwnedField::opt(2, OwnedValue::EntryRefs(vec![2])),
388        OwnedField::crit(3, OwnedValue::Utf8(band_values.gain_quantity().as_str().to_owned())),
389        OwnedField::crit(4, OwnedValue::F64(vec![reference_distance_m])),
390        OwnedField::opt(10, OwnedValue::Utf8(diffraction.as_str().to_owned())),
391        OwnedField::opt(12, OwnedValue::EntryRefs(vec![3])),
392    ];
393    if let Some(lid) = launch_id {
394        s206_fields.push(OwnedField::opt(5, OwnedValue::MetadataRefs(vec![lid])));
395    }
396
397    let mut entries = vec![
398        OwnedEntry {
399            mode: MODE_RAY_CONTRIBUTION,
400            flags: 1,
401            stream_id: 0,
402            frame_id: 2,
403            start_tick: 0,
404            time_count: 0,
405            spatial_key: 0,
406            record_count: rays.len() as u64,
407            stride: RAY_RECORD_STRIDE,
408            descriptor_id: 6,
409            payload: main_payload,
410        },
411        e_centers,
412        e_values,
413    ];
414    if let Some(rw) = ray_weights {
415        let e_w = push_aux_f32_entry(&mut meta, 9, 3, "ray-weights", "1", 1, AuxScalar::F32, rw)?;
416        s206_fields.push(OwnedField::opt(11, OwnedValue::EntryRefs(vec![4])));
417        entries.push(e_w);
418    }
419
420    meta.push_block(OwnedBlock {
421        id: 4,
422        schema_type: 206,
423        revision: 1,
424        critical: true,
425        fields: s206_fields,
426    })?;
427    let shape = [rays.len() as u64];
428    meta.push_model_grid(
429        5,
430        &ModelGridSpec {
431            model_uri: "urn:qac:model:geometric-ray-paths:v1",
432            model_version: "1",
433            discretization: Some("ray-path-contributions"),
434            component_offsets_xyz: &[],
435            component_time_offset_num: &[],
436            component_time_offset_den: &[],
437            timestep: None,
438            tolerance_abs: None,
439            tolerance_rel: None,
440            tensor_shape: &shape,
441            component_names: "ray_contribution",
442        },
443    )?;
444    let ext = [4u32, 5u32];
445    meta.push_descriptor(
446        6,
447        &DescriptorSpec {
448            clock_id: None,
449            frame_id: Some(2),
450            provenance_id: 3,
451            medium_id: None,
452            transform_id: None,
453            calibration_id: None,
454            quantity: "ray-path-contributions",
455            units: "mixed:mode-registry",
456            channels: None,
457            layout: None,
458            scalar: None,
459            model_uri: "urn:qac:mode:0x0003:v1",
460            sample_rate: None,
461            valid_record_count: None,
462            validity_mask_entry: None,
463            source_entries: &[],
464            extension_metadata: &ext,
465        },
466    )?;
467
468    assemble_qac_v1(&meta, &entries, limits)
469}
470
471pub(crate) fn push_aux_f32_entry(
472    meta: &mut MetadataBuilder,
473    desc_id: u32,
474    prov_id: u32,
475    qty: &str,
476    units: &str,
477    channels: u32,
478    scalar: AuxScalar,
479    vals: &[f32],
480) -> Result<OwnedEntry, ProfileError> {
481    let mut payload = vec![0u8; vals.len() * 4];
482    write_f32_slice(&mut payload, 0, vals)?;
483    let stride = channels * scalar.byte_size();
484    let rec_count = (payload.len() as u64) / u64::from(stride);
485    meta.push_descriptor(
486        desc_id,
487        &DescriptorSpec {
488            clock_id: None,
489            frame_id: None,
490            provenance_id: prov_id,
491            medium_id: None,
492            transform_id: None,
493            calibration_id: None,
494            quantity: qty,
495            units,
496            channels: Some(channels),
497            layout: Some("record-component"),
498            scalar: Some(scalar),
499            model_uri: "urn:qac:mode:0x0107:v1",
500            sample_rate: None,
501            valid_record_count: None,
502            validity_mask_entry: None,
503            source_entries: &[],
504            extension_metadata: &[],
505        },
506    )?;
507    Ok(OwnedEntry {
508        mode: MODE_AUX_ARRAY,
509        flags: 1,
510        stream_id: 0,
511        frame_id: 0,
512        start_tick: 0,
513        time_count: 0,
514        spatial_key: 0,
515        record_count: rec_count,
516        stride,
517        descriptor_id: desc_id,
518        payload,
519    })
520}
521
522pub struct RayContributionView<'a> {
523    pub records: RayContributionChunkView<'a>,
524    pub gain_quantity: GainQuantity,
525    pub diffraction_model: DiffractionModel,
526    pub band_centers_hz: Vec<f32>,
527    pub band_values: RayBandValues,
528}
529
530pub fn read_ray_contributions_qac<'a>(
531    bytes: &'a [u8],
532    entry_index: u32,
533    limits: ProfileLimits,
534) -> Result<RayContributionView<'a>, ProfileError> {
535    let env = AdmittedEnvelope::open_alloc(bytes, limits)?;
536    let (_e, desc, payload, mask) = env.check_structured_entry(
537        entry_index,
538        MODE_RAY_CONTRIBUTION,
539        RAY_RECORD_STRIDE,
540        false,
541        Some(206),
542    )?;
543    let s206 = env
544        .extension_block(desc, 206)?
545        .ok_or(ProfileError::MissingRequiredSchema(206))?;
546    let gain_quantity = GainQuantity::parse(field_str(field_req(s206, 3)?)?)?;
547    let diffraction_model = field_opt(s206, 10)
548        .map(field_str)
549        .transpose()?
550        .map(DiffractionModel::parse)
551        .transpose()?
552        .unwrap_or(DiffractionModel::None);
553
554    let centers_idx = field_u32(field_req(s206, 2)?)?;
555    let c_bytes = env.verify_chunk(centers_idx)?;
556    if c_bytes.len() % 4 != 0 || c_bytes.is_empty() {
557        return Err(ProfileError::InvalidPayloadLength);
558    }
559    let mut band_centers_hz = Vec::with_capacity(c_bytes.len() / 4);
560    for i in 0..c_bytes.len() / 4 {
561        band_centers_hz.push(read_f32_finite(c_bytes, i * 4)?);
562    }
563    let bands = band_centers_hz.len();
564
565    let vals_idx = field_u32(field_req(s206, 12)?)?;
566    let v_entry = env.entry(vals_idx)?;
567    let v_desc = env.descriptor_for_entry(v_entry)?;
568    let v_scalar = AuxScalar::from_u32(field_u32(field_req(v_desc, 11)?)?)
569        .ok_or(ProfileError::InvalidMetadata("band_values scalar"))?;
570    let v_bytes = env.verify_chunk(vals_idx)?;
571
572    let band_values = match (gain_quantity, v_scalar) {
573        (GainQuantity::EnergyRatio, AuxScalar::F32) => {
574            let mut vals = Vec::with_capacity(v_bytes.len() / 4);
575            for i in 0..v_bytes.len() / 4 {
576                let v = read_f32_finite(v_bytes, i * 4)?;
577                if v < 0.0 {
578                    return Err(ProfileError::InvalidMetadata("negative energy-ratio"));
579                }
580                vals.push(v);
581            }
582            RayBandValues::EnergyRatio { bands, values: vals }
583        }
584        (GainQuantity::PressureAmplitudeRatio, AuxScalar::F32) => {
585            let mut vals = Vec::with_capacity(v_bytes.len() / 4);
586            for i in 0..v_bytes.len() / 4 {
587                vals.push(read_f32_finite(v_bytes, i * 4)?);
588            }
589            RayBandValues::SignedPressureRatio { bands, values: vals }
590        }
591        (GainQuantity::PressureAmplitudeRatio, AuxScalar::ComplexF32) => {
592            if v_bytes.len() % 8 != 0 {
593                return Err(ProfileError::InvalidPayloadLength);
594            }
595            let mut pairs = Vec::with_capacity(v_bytes.len() / 8);
596            for i in 0..v_bytes.len() / 8 {
597                pairs.push(read_f32_2(v_bytes, i * 8)?);
598            }
599            RayBandValues::ComplexTransfer { bands, re_im: pairs }
600        }
601        _ => {
602            return Err(ProfileError::InvalidDomainConversion(
603                "energy-ratio cannot store complex phase transfer scalar",
604            ));
605        }
606    };
607    let rows = band_values.row_count();
608    let chunk = RayContributionChunkView {
609        bytes: payload,
610        mask,
611    };
612    for i in 0..chunk.len() {
613        let r = chunk.get(i)?;
614        if (r.band_row as usize) >= rows {
615            return Err(ProfileError::OutOfBoundsIndex("ray band_row out of bounds"));
616        }
617        if diffraction_model == DiffractionModel::None && r.diffraction_count > 0 {
618            return Err(ProfileError::InvalidMetadata("diffraction_count under DiffractionModel::None"));
619        }
620    }
621    Ok(RayContributionView {
622        records: chunk,
623        gain_quantity,
624        diffraction_model,
625        band_centers_hz,
626        band_values,
627    })
628}