Skip to main content

qualia_core_db/audio/qac/profiles/
ultrasound_codec.rs

1//! QAC v1 passive codec for Q07 Ultrasound (`mode 0x0107` beam summary, `mode 0x0105` raw RF/IQ,
2//! array geometry, transmit delays, and context-qualified `TI` validation).
3
4use super::envelope::*;
5use super::hrir::{push_aux_f32_vec3_entry, push_aux_f64_scalar_entry};
6use super::types::*;
7use super::ultrasound::{
8    RawUltrasoundPayload, UltrasoundAcquisitionSpec, UltrasoundBeamSummaryRecord,
9    UltrasoundChunkView, UltrasoundRole, ULTRASOUND_SUMMARY_STRIDE, US_VALID_TI,
10};
11
12/// Writes a Q07 ultrasound QAC v1 container (`mode 0x0107` beam summaries plus optional
13/// `mode 0x0105` raw RF/IQ, transducer element positions, channel map, transmit delays, and calibration).
14pub fn write_ultrasound_qac(
15    records: &[UltrasoundBeamSummaryRecord],
16    spec: &UltrasoundAcquisitionSpec<'_>,
17    raw_source: Option<&RawUltrasoundPayload<'_>>,
18    clock: &ClockSpec,
19    sample_rate: RationalRate,
20    frame: &FrameSpec<'_>,
21    provenance: &ProvenanceSpec<'_>,
22    validity_mask: Option<&[u8]>,
23    limits: ProfileLimits,
24) -> Result<Vec<u8>, ProfileError> {
25    if records.is_empty() {
26        return Err(ProfileError::InvalidPayloadLength);
27    }
28    if let Some(m) = validity_mask {
29        if m.len() != records.len() || m.iter().any(|&b| b > 1) {
30            return Err(ProfileError::InvalidValidityBits);
31        }
32    }
33    if let Some(fc) = spec.center_frequency_hz {
34        if !fc.is_finite() || fc <= 0.0 {
35            return Err(ProfileError::InvalidMetadata("Schema 208 center_frequency_hz <= 0"));
36        }
37    }
38    if let Some(phi0) = spec.demodulation_phase_rad {
39        let _ = require_finite_f64(phi0)?;
40    }
41
42    let has_valid_ti = records.iter().enumerate().any(|(i, r)| {
43        validity_mask.map_or(true, |m| m[i] != 0) && (r.validity_bits & US_VALID_TI != 0)
44    });
45    if has_valid_ti && (spec.thermal_model_uri.is_none() || spec.exposure_context.is_none()) {
46        return Err(ProfileError::MissingThermalModel(
47            "valid Thermal Index requires Schema 208 thermal_model_URI and exposure_context",
48        ));
49    }
50
51    const ACQ_BLOCK_ID: u32 = 4;
52    let mut main_payload = vec![0u8; records.len() * ULTRASOUND_SUMMARY_STRIDE as usize];
53    for (idx, r) in records.iter().enumerate() {
54        if r.acquisition_ref != ACQ_BLOCK_ID {
55            return Err(ProfileError::InvalidMetadata("acquisition_ref must match Schema 208 ID 4"));
56        }
57        let ext_valid = validity_mask.map_or(true, |m| m[idx] != 0);
58        let off = idx * ULTRASOUND_SUMMARY_STRIDE as usize;
59        r.encode_into(&mut main_payload[off..off + ULTRASOUND_SUMMARY_STRIDE as usize], ext_valid)?;
60    }
61
62    let mut meta = MetadataBuilder::new();
63    meta.push_clock(1, clock)?;
64    meta.push_frame(2, frame)?;
65
66    let cal_id = if let Some(cal) = &spec.calibration {
67        Some(meta.push_calibration(11, cal)?)
68    } else {
69        None
70    };
71    let target_frame_id = if let Some(tf) = &spec.target_frame {
72        Some(meta.push_frame(12, tf)?)
73    } else {
74        None
75    };
76
77    // Stream 0 static auxiliary arrays precede stream 1 temporal entries (`0x0105` < `0x0106` < `0x0107`).
78    let mut static_entries: Vec<OwnedEntry> = Vec::new();
79    let mut s208_fields = vec![OwnedField::crit(
80        1,
81        OwnedValue::Utf8(spec.role.as_str().to_owned()),
82    )];
83    if let Some(fc) = spec.center_frequency_hz {
84        s208_fields.push(OwnedField::opt(2, OwnedValue::F64(vec![fc])));
85    }
86
87    if let Some(pos) = spec.element_positions_m {
88        if pos.is_empty() {
89            return Err(ProfileError::InvalidMetadata("empty element_positions"));
90        }
91        let idx = (static_entries.len() as u32) + 1;
92        s208_fields.push(OwnedField::opt(3, OwnedValue::EntryRefs(vec![idx])));
93        static_entries.push(push_aux_f32_vec3_entry(
94            &mut meta,
95            20,
96            3,
97            "transducer-element-positions",
98            "m",
99            pos,
100        )?);
101    }
102    if let Some(cmap) = spec.channel_map {
103        if cmap.is_empty() {
104            return Err(ProfileError::InvalidMetadata("empty channel_map"));
105        }
106        let idx = (static_entries.len() as u32) + 1;
107        s208_fields.push(OwnedField::opt(4, OwnedValue::EntryRefs(vec![idx])));
108        let mut cm_bytes = vec![0u8; cmap.len() * 4];
109        for (i, &ch) in cmap.iter().enumerate() {
110            write_u32(&mut cm_bytes, i * 4, ch);
111        }
112        meta.push_descriptor(
113            21,
114            &DescriptorSpec {
115                clock_id: None,
116                frame_id: None,
117                provenance_id: 3,
118                medium_id: None,
119                transform_id: None,
120                calibration_id: None,
121                quantity: "ultrasound-channel-map",
122                units: "1",
123                channels: Some(1),
124                layout: Some("record-component"),
125                scalar: Some(AuxScalar::I32),
126                model_uri: "urn:qac:mode:0x0107:v1",
127                sample_rate: None,
128                valid_record_count: None,
129                validity_mask_entry: None,
130                source_entries: &[],
131                extension_metadata: &[],
132            },
133        )?;
134        static_entries.push(OwnedEntry {
135            mode: MODE_AUX_ARRAY,
136            flags: 1,
137            stream_id: 0,
138            frame_id: 0,
139            start_tick: 0,
140            time_count: 0,
141            spatial_key: 0,
142            record_count: cmap.len() as u64,
143            stride: 4,
144            descriptor_id: 21,
145            payload: cm_bytes,
146        });
147    }
148    if let Some(delays) = spec.transmit_delays_s {
149        if delays.is_empty() {
150            return Err(ProfileError::InvalidMetadata("empty transmit_delays_s"));
151        }
152        let idx = (static_entries.len() as u32) + 1;
153        s208_fields.push(OwnedField::opt(5, OwnedValue::EntryRefs(vec![idx])));
154        static_entries.push(push_aux_f64_scalar_entry(
155            &mut meta,
156            22,
157            3,
158            "transmit-delays-s",
159            "s",
160            delays,
161        )?);
162    }
163
164    if let Some(phi0) = spec.demodulation_phase_rad {
165        s208_fields.push(OwnedField::opt(6, OwnedValue::F64(vec![phi0])));
166    }
167    if let Some(prf) = spec.prf {
168        s208_fields.push(OwnedField::opt(7, OwnedValue::U64(vec![prf.num])));
169        s208_fields.push(OwnedField::opt(8, OwnedValue::U64(vec![prf.den])));
170    }
171    if let Some(dm) = spec.derating_model_uri {
172        validate_identifier_str(dm, "derating_model_URI")?;
173        s208_fields.push(OwnedField::opt(10, OwnedValue::Utf8(dm.to_owned())));
174    }
175    if let Some(ctx) = spec.exposure_context {
176        validate_identifier_str(ctx, "exposure_context")?;
177        s208_fields.push(OwnedField::opt(11, OwnedValue::Utf8(ctx.to_owned())));
178    }
179    if let Some(tm) = spec.thermal_model_uri {
180        validate_identifier_str(tm, "thermal_model_URI")?;
181        s208_fields.push(OwnedField::opt(12, OwnedValue::Utf8(tm.to_owned())));
182    }
183    if let Some(idig) = spec.instrument_digest {
184        s208_fields.push(OwnedField::opt(14, OwnedValue::Bytes(idig.to_vec())));
185    }
186    if let Some(adig) = spec.authority_receipt_digest {
187        s208_fields.push(OwnedField::opt(15, OwnedValue::Bytes(adig.to_vec())));
188    }
189    if let Some(tf_id) = target_frame_id {
190        s208_fields.push(OwnedField::opt(16, OwnedValue::MetadataRefs(vec![tf_id])));
191    }
192
193    let mut temporal_entries: Vec<OwnedEntry> = Vec::new();
194    let mut raw_entry_idx: Option<u32> = None;
195    let mut raw_digest: Option<[u8; 32]> = None;
196
197    if let Some(raw) = raw_source {
198        let (ch, rate, scalar, qty, payload, rec_cnt, stride) = match raw {
199            RawUltrasoundPayload::RawRfF32 {
200                channels,
201                sample_rate: rr,
202                samples_interleaved,
203            } => {
204                if *channels == 0
205                    || samples_interleaved.is_empty()
206                    || samples_interleaved.len() % (*channels as usize) != 0
207                {
208                    return Err(ProfileError::InvalidPayloadLength);
209                }
210                let mut bytes = vec![0u8; samples_interleaved.len() * 4];
211                write_f32_slice(&mut bytes, 0, samples_interleaved)?;
212                let frames = (samples_interleaved.len() / (*channels as usize)) as u64;
213                (*channels, *rr, AuxScalar::F32, "ultrasound-raw-rf", bytes, frames, *channels * 4)
214            }
215            RawUltrasoundPayload::BasebandIqComplexF32 {
216                channels,
217                sample_rate: iq_rate,
218                iq_interleaved,
219            } => {
220                if *channels == 0
221                    || iq_interleaved.is_empty()
222                    || iq_interleaved.len() % (*channels as usize) != 0
223                {
224                    return Err(ProfileError::InvalidPayloadLength);
225                }
226                let mut bytes = vec![0u8; iq_interleaved.len() * 8];
227                for (i, &[re, im]) in iq_interleaved.iter().enumerate() {
228                    write_f32_finite(&mut bytes, i * 8, re)?;
229                    write_f32_finite(&mut bytes, i * 8 + 4, im)?;
230                }
231                let frames = (iq_interleaved.len() / (*channels as usize)) as u64;
232                (*channels, *iq_rate, AuxScalar::ComplexF32, "ultrasound-baseband-iq", bytes, frames, *channels * 8)
233            }
234        };
235        let digest = *blake3::hash(&payload).as_bytes();
236        raw_digest = Some(digest);
237        let idx = (static_entries.len() + temporal_entries.len() + 1) as u32;
238        raw_entry_idx = Some(idx);
239        s208_fields.push(OwnedField::opt(17, OwnedValue::EntryRefs(vec![idx])));
240        let ext_raw = [ACQ_BLOCK_ID];
241        meta.push_descriptor(
242            18,
243            &DescriptorSpec {
244                clock_id: Some(1),
245                frame_id: Some(2),
246                provenance_id: 3,
247                medium_id: None,
248                transform_id: None,
249                calibration_id: cal_id,
250                quantity: qty,
251                units: "Pa",
252                channels: Some(ch),
253                layout: Some("frame-channel"),
254                scalar: Some(scalar),
255                model_uri: "urn:qac:mode:0x0105:ultrasound-raw:v1",
256                sample_rate: Some(rate),
257                valid_record_count: None,
258                validity_mask_entry: None,
259                source_entries: &[],
260                extension_metadata: &ext_raw,
261            },
262        )?;
263        temporal_entries.push(OwnedEntry {
264            mode: MODE_RAW_RF_IQ,
265            flags: 3,
266            stream_id: 1,
267            frame_id: 2,
268            start_tick: 0,
269            time_count: rec_cnt,
270            spatial_key: 0,
271            record_count: rec_cnt,
272            stride,
273            descriptor_id: 18,
274            payload,
275        });
276    }
277
278    meta.push_provenance(3, provenance)?;
279    let beam_prov_id = if let Some(rdig) = raw_digest {
280        let digs = [rdig];
281        meta.push_provenance(
282            13,
283            &ProvenanceSpec {
284                role: provenance.role,
285                source_digests: &digs,
286                algorithm: provenance.algorithm,
287                algorithm_version: provenance.algorithm_version,
288                instrument_uri: provenance.instrument_uri,
289                authority_receipt_digest: provenance.authority_receipt_digest,
290                lineage: provenance.lineage,
291            },
292        )?
293    } else {
294        3
295    };
296
297    let mask_entry_idx = if let Some(mb) = validity_mask {
298        let idx = (static_entries.len() + temporal_entries.len() + 1) as u32;
299        temporal_entries.push(push_validity_mask_entry(&mut meta, 7, 3, 1, 0, 1, mb)?);
300        Some(idx)
301    } else {
302        None
303    };
304
305    meta.push_block(OwnedBlock {
306        id: ACQ_BLOCK_ID,
307        schema_type: 208,
308        revision: 1,
309        critical: true,
310        fields: s208_fields,
311    })?;
312
313    let shape = [records.len() as u64];
314    meta.push_model_grid(
315        5,
316        &ModelGridSpec {
317            model_uri: "urn:qac:model:ultrasound-beam-summary:v1",
318            model_version: "1",
319            discretization: Some("beam-summary-focus"),
320            component_offsets_xyz: &[],
321            component_time_offset_num: &[],
322            component_time_offset_den: &[],
323            timestep: Some(sample_rate),
324            tolerance_abs: None,
325            tolerance_rel: None,
326            tensor_shape: &shape,
327            component_names: "pos,fc,pr,ispta,mi,ti,iq,v_axial,harmonic",
328        },
329    )?;
330
331    let valid_count = validity_mask.map(|m| m.iter().filter(|&&b| b == 1).count() as u64);
332    let src_entries: Vec<u32> = raw_entry_idx.into_iter().collect();
333    let ext = [ACQ_BLOCK_ID, 5u32];
334    meta.push_descriptor(
335        6,
336        &DescriptorSpec {
337            clock_id: Some(1),
338            frame_id: Some(2),
339            provenance_id: beam_prov_id,
340            medium_id: None,
341            transform_id: None,
342            calibration_id: cal_id,
343            quantity: "ultrasound-beam-summary",
344            units: "mixed:mode-registry",
345            channels: None,
346            layout: None,
347            scalar: None,
348            model_uri: "urn:qac:mode:0x0107:v1",
349            sample_rate: Some(sample_rate),
350            valid_record_count: valid_count,
351            validity_mask_entry: mask_entry_idx,
352            source_entries: &src_entries,
353            extension_metadata: &ext,
354        },
355    )?;
356
357    temporal_entries.push(OwnedEntry {
358        mode: MODE_ULTRASOUND_SUMMARY,
359        flags: 3,
360        stream_id: 1,
361        frame_id: 2,
362        start_tick: 0,
363        time_count: 1,
364        spatial_key: 0,
365        record_count: records.len() as u64,
366        stride: ULTRASOUND_SUMMARY_STRIDE,
367        descriptor_id: 6,
368        payload: main_payload,
369    });
370
371    let mut all_entries = static_entries;
372    all_entries.extend(temporal_entries);
373    assemble_qac_v1(&meta, &all_entries, limits)
374}
375
376/// Decoded passive Q07 ultrasound view retaining raw RF links, geometry, and derived metrics.
377pub struct UltrasoundDocumentView<'a> {
378    pub records: UltrasoundChunkView<'a>,
379    pub role: UltrasoundRole,
380    pub center_frequency_hz: Option<f64>,
381    pub demodulation_phase_rad: Option<f64>,
382    pub exposure_context: Option<&'a str>,
383    pub thermal_model_uri: Option<&'a str>,
384    pub element_positions_m: Option<Vec<[f32; 3]>>,
385    pub channel_map: Option<Vec<u32>>,
386    pub transmit_delays_s: Option<Vec<f64>>,
387    pub raw_source_bytes: Option<&'a [u8]>,
388}
389
390/// Admits and passively decodes a `mode 0x0107` ultrasound beam summary entry.
391/// Preserves valid high `MI`/`ISPTA` physical measurements without clinical veto,
392/// while rejecting missing `thermal_model_URI` / `exposure_context` whenever `TI` valid bit is set.
393pub fn read_ultrasound_qac<'a>(
394    bytes: &'a [u8],
395    entry_index: u32,
396    limits: ProfileLimits,
397) -> Result<UltrasoundDocumentView<'a>, ProfileError> {
398    let env = AdmittedEnvelope::open_alloc(bytes, limits)?;
399    let (_e, desc, payload, mask) = env.check_structured_entry(
400        entry_index,
401        MODE_ULTRASOUND_SUMMARY,
402        ULTRASOUND_SUMMARY_STRIDE,
403        false,
404        Some(205),
405    )?;
406    let s208 = env
407        .extension_block(desc, 208)?
408        .ok_or(ProfileError::MissingRequiredSchema(208))?;
409    let role = UltrasoundRole::parse(field_str(field_req(s208, 1)?)?)?;
410    let center_frequency_hz = field_opt(s208, 2).map(field_f64).transpose()?;
411    let demodulation_phase_rad = field_opt(s208, 6).map(field_f64).transpose()?;
412    let exposure_context = field_opt(s208, 11).map(field_str).transpose()?;
413    let thermal_model_uri = field_opt(s208, 12).map(field_str).transpose()?;
414
415    let element_positions_m = if let Some(f) = field_opt(s208, 3) {
416        let b = env.verify_chunk(field_u32(f)?)?;
417        if b.len() % 12 != 0 {
418            return Err(ProfileError::InvalidPayloadLength);
419        }
420        let mut pts = Vec::with_capacity(b.len() / 12);
421        for i in 0..b.len() / 12 {
422            pts.push(read_f32_3(b, i * 12)?);
423        }
424        Some(pts)
425    } else {
426        None
427    };
428
429    let channel_map = if let Some(f) = field_opt(s208, 4) {
430        let b = env.verify_chunk(field_u32(f)?)?;
431        if b.len() % 4 != 0 {
432            return Err(ProfileError::InvalidPayloadLength);
433        }
434        let mut ch = Vec::with_capacity(b.len() / 4);
435        for i in 0..b.len() / 4 {
436            ch.push(read_u32(b, i * 4)?);
437        }
438        Some(ch)
439    } else {
440        None
441    };
442
443    let transmit_delays_s = if let Some(f) = field_opt(s208, 5) {
444        let b = env.verify_chunk(field_u32(f)?)?;
445        if b.len() % 8 != 0 {
446            return Err(ProfileError::InvalidPayloadLength);
447        }
448        let mut d = Vec::with_capacity(b.len() / 8);
449        for i in 0..b.len() / 8 {
450            let v = f64::from_le_bytes([
451                b[i * 8],
452                b[i * 8 + 1],
453                b[i * 8 + 2],
454                b[i * 8 + 3],
455                b[i * 8 + 4],
456                b[i * 8 + 5],
457                b[i * 8 + 6],
458                b[i * 8 + 7],
459            ]);
460            d.push(require_finite_f64(v)?);
461        }
462        Some(d)
463    } else {
464        None
465    };
466
467    let raw_source_bytes = if let Some(f) = field_opt(s208, 17) {
468        let raw_idx = field_u32(f)?;
469        let raw_entry = env.entry(raw_idx)?;
470        if raw_entry.mode() != MODE_RAW_RF_IQ
471            && raw_entry.mode() != MODE_PCM_PRESERVATION
472            && raw_entry.mode() != MODE_OPAQUE_SOURCE
473        {
474            return Err(ProfileError::InvalidMode(raw_entry.mode()));
475        }
476        Some(env.verify_chunk(raw_idx)?)
477    } else {
478        None
479    };
480
481    let chunk = UltrasoundChunkView::new(payload, mask);
482    let expected_ref = s208.id();
483    for i in 0..chunk.len() {
484        let rec = chunk.get(i)?;
485        if rec.acquisition_ref != expected_ref {
486            return Err(ProfileError::InvalidMetadata("acquisition_ref disagrees with Schema 208 ID"));
487        }
488        let ext_valid = mask.map_or(true, |m| m[i] != 0);
489        if ext_valid
490            && (rec.validity_bits & US_VALID_TI != 0)
491            && (thermal_model_uri.is_none() || exposure_context.is_none())
492        {
493            return Err(ProfileError::MissingThermalModel(
494                "TI bit set without thermal_model_URI and exposure_context",
495            ));
496        }
497    }
498
499    Ok(UltrasoundDocumentView {
500        records: chunk,
501        role,
502        center_frequency_hz,
503        demodulation_phase_rad,
504        exposure_context,
505        thermal_model_uri,
506        element_positions_m,
507        channel_map,
508        transmit_delays_s,
509        raw_source_bytes,
510    })
511}
512
513/// Finds the 1-based directory index of the first `mode 0x0107` ultrasound beam summary
514/// entry (64-byte stride + `Schema 208`), skipping `mode 0x0107` auxiliary array entries.
515pub fn find_ultrasound_summary_entry_index(
516    bytes: &[u8],
517    limits: ProfileLimits,
518) -> Result<u32, ProfileError> {
519    let env = AdmittedEnvelope::open_alloc(bytes, limits)?;
520    for idx in 1..=env.view().entry_count() {
521        let e = env.entry(idx)?;
522        if e.mode() == MODE_ULTRASOUND_SUMMARY && e.stride() == ULTRASOUND_SUMMARY_STRIDE {
523            let desc = env.descriptor_for_entry(e)?;
524            if env.extension_block(desc, 208)?.is_some() {
525                return Ok(idx);
526            }
527        }
528    }
529    Err(ProfileError::MissingRequiredSchema(208))
530}