Skip to main content

qualia_core_db/audio/qac/profiles/
ultrasound.rs

1//! Q07 Mode `0x0107` (`ultrasound_beam_summary`, 64 B) & Mode `0x0105` (`raw_RF` / `baseband_IQ`, `Schema 208`).
2//!
3//! Preserves raw transducer channel acquisition, array geometry, element delays, calibration,
4//! and derived beam summaries (`MI`, `ISPTA`, context-qualified `TI`, Doppler axial velocity,
5//! and positive-carrier IQ `Re{(I + iQ) exp(+i(2*pi*fc*t + phi0))}`).
6
7use super::types::*;
8pub use super::ultrasound_codec::*;
9
10/// Frozen wire stride in bytes for `mode 0x0107` ultrasound beam summary records.
11pub const ULTRASOUND_SUMMARY_STRIDE: u32 = 64;
12
13/// Bitmask constants for `UltrasoundBeamSummaryRecord::validity_bits` (`0..=6`).
14pub const US_VALID_PR: u32 = 1 << 0;
15pub const US_VALID_ISPTA: u32 = 1 << 1;
16pub const US_VALID_MI: u32 = 1 << 2;
17pub const US_VALID_TI: u32 = 1 << 3;
18pub const US_VALID_IQ: u32 = 1 << 4;
19pub const US_VALID_AXIAL_VEL: u32 = 1 << 5;
20pub const US_VALID_HARMONIC: u32 = 1 << 6;
21pub const US_VALID_ALL: u32 = US_VALID_PR
22    | US_VALID_ISPTA
23    | US_VALID_MI
24    | US_VALID_TI
25    | US_VALID_IQ
26    | US_VALID_AXIAL_VEL
27    | US_VALID_HARMONIC;
28
29/// Explicit role of an ultrasound entry recorded in `Schema 208` key 1 (`role`).
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum UltrasoundRole {
32    RawRf,
33    BasebandIq,
34    BeamSummary,
35    TransmitCommand,
36}
37
38impl UltrasoundRole {
39    pub fn as_str(self) -> &'static str {
40        match self {
41            Self::RawRf => "raw-RF",
42            Self::BasebandIq => "baseband-IQ",
43            Self::BeamSummary => "beam-summary",
44            Self::TransmitCommand => "transmit-command",
45        }
46    }
47
48    pub fn parse(s: &str) -> Result<Self, ProfileError> {
49        match s {
50            "raw-RF" => Ok(Self::RawRf),
51            "baseband-IQ" => Ok(Self::BasebandIq),
52            "beam-summary" => Ok(Self::BeamSummary),
53            "transmit-command" => Ok(Self::TransmitCommand),
54            _ => Err(ProfileError::InvalidMetadata("unknown Schema 208 ultrasound role")),
55        }
56    }
57}
58
59/// Optional linked raw RF or baseband-IQ transducer acquisition channels (`mode 0x0105`).
60#[derive(Debug, Clone)]
61pub enum RawUltrasoundPayload<'a> {
62    RawRfF32 {
63        channels: u32,
64        sample_rate: RationalRate,
65        samples_interleaved: &'a [f32],
66    },
67    BasebandIqComplexF32 {
68        channels: u32,
69        sample_rate: RationalRate,
70        iq_interleaved: &'a [[f32; 2]],
71    },
72}
73
74/// Complete `Schema 208` acquisition, array geometry, derating, and thermal-context specification.
75#[derive(Debug, Clone)]
76pub struct UltrasoundAcquisitionSpec<'a> {
77    pub role: UltrasoundRole,
78    pub center_frequency_hz: Option<f64>,
79    pub element_positions_m: Option<&'a [[f32; 3]]>,
80    pub channel_map: Option<&'a [u32]>,
81    pub transmit_delays_s: Option<&'a [f64]>,
82    pub demodulation_phase_rad: Option<f64>,
83    pub prf: Option<RationalRate>,
84    pub derating_model_uri: Option<&'a str>,
85    pub exposure_context: Option<&'a str>,
86    pub thermal_model_uri: Option<&'a str>,
87    pub instrument_digest: Option<[u8; 32]>,
88    pub authority_receipt_digest: Option<[u8; 32]>,
89    pub target_frame: Option<FrameSpec<'a>>,
90    pub calibration: Option<CalibrationSpec<'a>>,
91}
92
93/// Canonical 64-byte Q07 `mode 0x0107` ultrasound beam summary record.
94#[derive(Debug, Clone, Copy, PartialEq)]
95pub struct UltrasoundBeamSummaryRecord {
96    pub position_m: [f32; 3],
97    pub center_frequency_hz: f32,
98    pub peak_rarefactional_pressure_pa: f32,
99    pub intensity_ispta_w_m2: f32,
100    pub mechanical_index: f32,
101    pub thermal_index: f32,
102    pub complex_envelope_iq: [f32; 2],
103    pub axial_velocity_m_s: f32,
104    pub harmonic_ratio_linear: f32,
105    pub validity_bits: u32,
106    pub acquisition_ref: u32,
107}
108
109impl UltrasoundBeamSummaryRecord {
110    pub fn validate(&self, externally_valid: bool) -> Result<(), ProfileError> {
111        for v in self.position_m {
112            if !v.is_finite() {
113                return Err(ProfileError::NonFiniteFloat);
114            }
115            require_zero_when_masked(externally_valid, v)?;
116        }
117        if !self.center_frequency_hz.is_finite() {
118            return Err(ProfileError::NonFiniteFloat);
119        }
120        if externally_valid {
121            if self.center_frequency_hz <= 0.0 {
122                return Err(ProfileError::InvalidMetadata("ultrasound center_frequency_hz must be > 0"));
123            }
124        } else if self.center_frequency_hz.to_bits() != 0 || self.validity_bits != 0 {
125            return Err(ProfileError::MaskedLaneNonZero);
126        }
127
128        let floats = [
129            self.peak_rarefactional_pressure_pa,
130            self.intensity_ispta_w_m2,
131            self.mechanical_index,
132            self.thermal_index,
133            self.complex_envelope_iq[0],
134            self.complex_envelope_iq[1],
135            self.axial_velocity_m_s,
136            self.harmonic_ratio_linear,
137        ];
138        if floats.iter().any(|v| !v.is_finite()) {
139            return Err(ProfileError::NonFiniteFloat);
140        }
141        if self.validity_bits & !US_VALID_ALL != 0 {
142            return Err(ProfileError::InvalidValidityBits);
143        }
144        if self.acquisition_ref == 0 {
145            return Err(ProfileError::InvalidMetadata("acquisition_ref must be nonzero Schema 208 ID"));
146        }
147
148        let b = self.validity_bits;
149        let check_nonneg = |bit: u32, val: f32, msg: &'static str| -> Result<(), ProfileError> {
150            let valid = externally_valid && (b & bit != 0);
151            require_zero_when_masked(valid, val)?;
152            if valid && val < 0.0 {
153                return Err(ProfileError::InvalidMetadata(msg));
154            }
155            Ok(())
156        };
157        check_nonneg(US_VALID_PR, self.peak_rarefactional_pressure_pa, "negative peak rarefactional pressure")?;
158        check_nonneg(US_VALID_ISPTA, self.intensity_ispta_w_m2, "negative ISPTA")?;
159        check_nonneg(US_VALID_MI, self.mechanical_index, "negative mechanical_index")?;
160        check_nonneg(US_VALID_TI, self.thermal_index, "negative thermal_index")?;
161        let iq_valid = externally_valid && (b & US_VALID_IQ != 0);
162        require_zero_when_masked(iq_valid, self.complex_envelope_iq[0])?;
163        require_zero_when_masked(iq_valid, self.complex_envelope_iq[1])?;
164        let vel_valid = externally_valid && (b & US_VALID_AXIAL_VEL != 0);
165        require_zero_when_masked(vel_valid, self.axial_velocity_m_s)?;
166        check_nonneg(US_VALID_HARMONIC, self.harmonic_ratio_linear, "negative harmonic_ratio_linear")?;
167        Ok(())
168    }
169
170    pub fn decode(bytes: &[u8], externally_valid: bool) -> Result<Self, ProfileError> {
171        if bytes.len() != ULTRASOUND_SUMMARY_STRIDE as usize {
172            return Err(ProfileError::InvalidPayloadLength);
173        }
174        ensure_zero_bytes(&bytes[56..64])?;
175        let rec = Self {
176            position_m: read_f32_3(bytes, 0)?,
177            center_frequency_hz: read_f32_finite(bytes, 12)?,
178            peak_rarefactional_pressure_pa: read_f32_finite(bytes, 16)?,
179            intensity_ispta_w_m2: read_f32_finite(bytes, 20)?,
180            mechanical_index: read_f32_finite(bytes, 24)?,
181            thermal_index: read_f32_finite(bytes, 28)?,
182            complex_envelope_iq: read_f32_2(bytes, 32)?,
183            axial_velocity_m_s: read_f32_finite(bytes, 40)?,
184            harmonic_ratio_linear: read_f32_finite(bytes, 44)?,
185            validity_bits: read_u32(bytes, 48)?,
186            acquisition_ref: read_u32(bytes, 52)?,
187        };
188        rec.validate(externally_valid)?;
189        Ok(rec)
190    }
191
192    pub fn encode_into(&self, out: &mut [u8], externally_valid: bool) -> Result<(), ProfileError> {
193        if out.len() != ULTRASOUND_SUMMARY_STRIDE as usize {
194            return Err(ProfileError::InvalidPayloadLength);
195        }
196        self.validate(externally_valid)?;
197        out.fill(0);
198        write_f32_slice(out, 0, &self.position_m)?;
199        write_f32_finite(out, 12, self.center_frequency_hz)?;
200        write_f32_finite(out, 16, self.peak_rarefactional_pressure_pa)?;
201        write_f32_finite(out, 20, self.intensity_ispta_w_m2)?;
202        write_f32_finite(out, 24, self.mechanical_index)?;
203        write_f32_finite(out, 28, self.thermal_index)?;
204        write_f32_slice(out, 32, &self.complex_envelope_iq)?;
205        write_f32_finite(out, 40, self.axial_velocity_m_s)?;
206        write_f32_finite(out, 44, self.harmonic_ratio_linear)?;
207        write_u32(out, 48, self.validity_bits);
208        write_u32(out, 52, self.acquisition_ref);
209        Ok(())
210    }
211}
212
213/// Zero-heap borrowed view over verified `mode 0x0107` ultrasound beam summary records.
214pub struct UltrasoundChunkView<'a> {
215    bytes: &'a [u8],
216    mask: Option<&'a [u8]>,
217}
218
219impl<'a> UltrasoundChunkView<'a> {
220    pub(crate) fn new(bytes: &'a [u8], mask: Option<&'a [u8]>) -> Self {
221        Self { bytes, mask }
222    }
223
224    pub fn len(&self) -> usize {
225        self.bytes.len() / ULTRASOUND_SUMMARY_STRIDE as usize
226    }
227
228    pub fn is_empty(&self) -> bool {
229        self.bytes.is_empty()
230    }
231
232    pub fn get(&self, index: usize) -> Result<UltrasoundBeamSummaryRecord, ProfileError> {
233        let start = index
234            .checked_mul(ULTRASOUND_SUMMARY_STRIDE as usize)
235            .ok_or(ProfileError::Overflow)?;
236        let end = start
237            .checked_add(ULTRASOUND_SUMMARY_STRIDE as usize)
238            .ok_or(ProfileError::Overflow)?;
239        let slice = self
240            .bytes
241            .get(start..end)
242            .ok_or(ProfileError::OutOfBoundsIndex("ultrasound record index"))?;
243        let ext_valid = self.mask.map_or(true, |m| m[index] != 0);
244        UltrasoundBeamSummaryRecord::decode(slice, ext_valid)
245    }
246}
247
248// ---------------------------------------------------------------------------
249// Acoustic physics helpers: FDA MI, positive-carrier IQ, Doppler, ToF delays
250// ---------------------------------------------------------------------------
251
252/// Standard derated Mechanical Index `MI = p_{r,derated}(MPa) / sqrt(f_c(MHz))`.
253pub fn mechanical_index_derated(
254    peak_rarefactional_pa: f64,
255    center_frequency_hz: f64,
256    depth_cm: f64,
257    derating_db_per_cm_mhz: f64,
258) -> Result<f64, ProfileError> {
259    if !peak_rarefactional_pa.is_finite()
260        || !center_frequency_hz.is_finite()
261        || !depth_cm.is_finite()
262        || !derating_db_per_cm_mhz.is_finite()
263    {
264        return Err(ProfileError::NonFiniteFloat);
265    }
266    if peak_rarefactional_pa < 0.0 || center_frequency_hz <= 0.0 || depth_cm < 0.0 || derating_db_per_cm_mhz < 0.0 {
267        return Err(ProfileError::InvalidMetadata("invalid MI parameters"));
268    }
269    let f_mhz = center_frequency_hz / 1.0e6;
270    let p_derated_mpa = (peak_rarefactional_pa / 1.0e6)
271        * 10.0f64.powf(-(derating_db_per_cm_mhz * depth_cm * f_mhz) / 20.0);
272    Ok(p_derated_mpa / f_mhz.sqrt())
273}
274
275/// Positive-carrier RF reconstruction from baseband IQ:
276/// `p_RF(t) = Re{ (I + iQ) * exp(+i * (2*pi*fc*t + phi0)) } = I*cos(th) - Q*sin(th)`.
277pub fn modulate_positive_carrier_rf(
278    i_val: f64,
279    q_val: f64,
280    center_frequency_hz: f64,
281    demod_phase_rad: f64,
282    time_s: f64,
283) -> f64 {
284    let theta = 2.0 * std::f64::consts::PI * center_frequency_hz * time_s + demod_phase_rad;
285    i_val * theta.cos() - q_val * theta.sin()
286}
287
288/// Coherent baseband IQ demodulation matching positive-carrier convention over `rf_samples`.
289pub fn demodulate_positive_carrier_iq(
290    rf_samples: &[f64],
291    sample_rate_hz: f64,
292    center_frequency_hz: f64,
293    demod_phase_rad: f64,
294) -> Result<[f64; 2], ProfileError> {
295    if rf_samples.is_empty() || !sample_rate_hz.is_finite() || sample_rate_hz <= 0.0 || !center_frequency_hz.is_finite() || center_frequency_hz <= 0.0 {
296        return Err(ProfileError::InvalidMetadata("invalid IQ demodulation parameters"));
297    }
298    let mut sum_i = 0.0f64;
299    let mut sum_q = 0.0f64;
300    for (n, &x) in rf_samples.iter().enumerate() {
301        if !x.is_finite() {
302            return Err(ProfileError::NonFiniteFloat);
303        }
304        let t = (n as f64) / sample_rate_hz;
305        let theta = 2.0 * std::f64::consts::PI * center_frequency_hz * t + demod_phase_rad;
306        // x(t) * 2 * exp(-i*theta) recovers (I + i*Q) when carrier is +i*theta.
307        sum_i += 2.0 * x * theta.cos();
308        sum_q += -2.0 * x * theta.sin();
309    }
310    let scale = 1.0 / (rf_samples.len() as f64);
311    Ok([sum_i * scale, sum_q * scale])
312}
313
314/// Signed Doppler axial velocity `v_axial = c * f_D / (2 * f_c)` (positive toward transducer).
315pub fn doppler_axial_velocity_m_s(
316    doppler_shift_hz: f64,
317    center_frequency_hz: f64,
318    sound_speed_m_s: f64,
319) -> Result<f64, ProfileError> {
320    if !doppler_shift_hz.is_finite() || !center_frequency_hz.is_finite() || !sound_speed_m_s.is_finite() {
321        return Err(ProfileError::NonFiniteFloat);
322    }
323    if center_frequency_hz <= 0.0 || sound_speed_m_s <= 0.0 {
324        return Err(ProfileError::InvalidMetadata("frequency and speed of sound must be > 0"));
325    }
326    Ok((sound_speed_m_s * doppler_shift_hz) / (2.0 * center_frequency_hz))
327}
328
329/// Round-trip time-of-flight delay `(||r_f - r_tx|| + ||r_f - e_k||) / c` in seconds.
330pub fn element_roundtrip_delay_s(
331    tx_origin_m: [f64; 3],
332    element_pos_m: [f64; 3],
333    focus_pos_m: [f64; 3],
334    sound_speed_m_s: f64,
335) -> Result<f64, ProfileError> {
336    if sound_speed_m_s <= 0.0
337        || tx_origin_m
338            .iter()
339            .chain(element_pos_m.iter())
340            .chain(focus_pos_m.iter())
341            .chain(std::iter::once(&sound_speed_m_s))
342            .any(|v| !v.is_finite())
343    {
344        return Err(ProfileError::InvalidMetadata("invalid beamforming ToF geometry"));
345    }
346    let dist = |a: [f64; 3], b: [f64; 3]| -> f64 {
347        let dx = a[0] - b[0];
348        let dy = a[1] - b[1];
349        let dz = a[2] - b[2];
350        (dx * dx + dy * dy + dz * dz).sqrt()
351    };
352    Ok((dist(focus_pos_m, tx_origin_m) + dist(focus_pos_m, element_pos_m)) / sound_speed_m_s)
353}