Skip to main content

qualia_core_db/audio/qac/metadata/
transform.rs

1use super::*;
2use crate::audio::qac::signal::{Error, Rate};
3#[derive(Clone, Copy, Debug, PartialEq, Eq)]
4pub enum TransformKind {
5    Complex,
6    Magnitude,
7}
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum WindowKind {
10    Rectangular,
11    HannSymmetricF32,
12}
13impl WindowKind {
14    pub const fn as_str(self) -> &'static str {
15        match self {
16            Self::Rectangular => "rectangular",
17            Self::HannSymmetricF32 => "hann-symmetric-authored-f32",
18        }
19    }
20}
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum OriginBasis {
23    EpochSampleGrid,
24    SourceEntryFirstSample,
25}
26impl OriginBasis {
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::EpochSampleGrid => "epoch-sample-grid",
30            Self::SourceEntryFirstSample => "source-entry-first-sample",
31        }
32    }
33}
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
35pub struct Transform {
36    pub kind: TransformKind,
37    pub fft_size: u32,
38    pub hop: u32,
39    pub bins: u32,
40    pub input_rate: Rate,
41    pub origin_samples: i64,
42    pub window: WindowKind,
43    pub origin_basis: OriginBasis,
44}
45fn validate_hann_f32(b: Block<'_>, fft_size: u32) -> Result<(), Error> {
46    if !fft_size.is_power_of_two() || !(2..=1024).contains(&fft_size) {
47        return Err(Error::Shape);
48    }
49    let wf = sem::field(b, 16).ok_or(Error::Profile)?;
50    if wf.flags() & 1 == 0 || wf.type_tag() != 4 || wf.element_count() != fft_size {
51        return Err(Error::Profile);
52    }
53    let bytes = wf.value();
54    let n = fft_size as usize;
55    if bytes.len() != n * 4 {
56        return Err(Error::Shape);
57    }
58    for i in 0..n {
59        let val = f32::from_le_bytes(bytes[i * 4..i * 4 + 4].try_into().unwrap());
60        let opp = f32::from_le_bytes(bytes[(n - 1 - i) * 4..(n - 1 - i) * 4 + 4].try_into().unwrap());
61        if !val.is_finite() || !opp.is_finite() {
62            return Err(Error::Nonfinite);
63        }
64        if (f64::from(val) - f64::from(opp)).abs() > 1e-6 {
65            return Err(Error::Profile);
66        }
67        let expected =
68            (0.5 * (1.0 - (std::f64::consts::TAU * (i as f64) / ((n - 1) as f64)).cos())) as f32;
69        if (f64::from(val) - f64::from(expected)).abs() > 1e-5 {
70            return Err(Error::Profile);
71        }
72    }
73    Ok(())
74}
75impl Transform {
76    pub fn window_kind(self) -> WindowKind {
77        self.window
78    }
79    pub fn origin_basis(self) -> OriginBasis {
80        self.origin_basis
81    }
82    pub fn from_block(b: Block<'_>) -> Result<Self, Error> {
83        if b.schema_type() != 201 || b.revision() != 1 {
84            return Err(Error::Profile);
85        }
86        use crate::q42::field_semantics::DomainRegistry;
87        sem::validate_fields(b, SignalRegistry.rules(201, 1).ok_or(Error::Profile)?)?;
88        let kind = match text(b, 1)? {
89            "STFT-complex" => TransformKind::Complex,
90            "STFT-magnitude" => TransformKind::Magnitude,
91            _ => return Err(Error::Unsupported),
92        };
93        let fft_size = u32v(b, 2)?;
94        let hop = u32v(b, 3)?;
95        let bins = u32v(b, 13)?;
96        if fft_size == 0 || hop == 0 || bins != fft_size || u32v(b, 7)? != 0 {
97            return Err(Error::Shape);
98        }
99        let window = match text(b, 4)? {
100            "rectangular" => {
101                if sem::field(b, 16).is_some() {
102                    return Err(Error::Unsupported);
103                }
104                WindowKind::Rectangular
105            }
106            "hann-symmetric-authored-f32" => {
107                validate_hann_f32(b, fft_size)?;
108                WindowKind::HannSymmetricF32
109            }
110            _ => return Err(Error::Unsupported),
111        };
112        if text(b, 6)? != "forward-unscaled-inverse-1/N"
113            || text(b, 9)? != "forward-negative-exponent"
114            || text(b, 11)? != "none"
115        {
116            return Err(Error::Unsupported);
117        }
118        if sem::field(b, 5).is_some() || sem::field(b, 8).is_some() {
119            return Err(Error::Unsupported);
120        }
121        let origin_samples = u64v(b, 10)? as i64;
122        let origin_basis = match sem::field(b, 17) {
123            None => OriginBasis::EpochSampleGrid,
124            Some(f) => {
125                if f.flags() & 1 == 0 {
126                    return Err(Error::Profile);
127                }
128                if text(b, 17)? != "source-entry-first-sample" {
129                    return Err(Error::Unsupported);
130                }
131                if origin_samples != 0 {
132                    return Err(Error::Clock);
133                }
134                OriginBasis::SourceEntryFirstSample
135            }
136        };
137        text(b, 12)?;
138        Ok(Self {
139            kind,
140            fft_size,
141            hop,
142            bins,
143            input_rate: Rate::new(u64v(b, 14)?, u64v(b, 15)?)?,
144            origin_samples,
145            window,
146            origin_basis,
147        })
148    }
149}
150
151/// Signed mathematical FFT offset in Hz, not an inferred physical RF carrier.
152#[derive(Clone, Copy, Debug, PartialEq, Eq)]
153pub struct FrequencyOffset {
154    pub numerator: i128,
155    pub denominator: i128,
156}
157impl Transform {
158    /// Preserve in-order full bins. For even N, Nyquist is the negative representative.
159    pub fn frequency_offset(self, bin: u32) -> Result<FrequencyOffset, Error> {
160        Rate::new(self.input_rate.numerator, self.input_rate.denominator)?;
161        if self.fft_size == 0 || self.bins != self.fft_size {
162            return Err(Error::Shape);
163        }
164        if bin >= self.bins {
165            return Err(Error::Index);
166        }
167        let signed = if bin <= (self.fft_size - 1) / 2 {
168            i128::from(bin)
169        } else {
170            i128::from(bin) - i128::from(self.fft_size)
171        };
172        let numerator = signed
173            .checked_mul(self.input_rate.numerator.into())
174            .ok_or(Error::Overflow)?;
175        let denominator = i128::from(self.fft_size)
176            .checked_mul(self.input_rate.denominator.into())
177            .ok_or(Error::Overflow)?;
178        let mut a = numerator.unsigned_abs();
179        let mut b = denominator as u128;
180        while b != 0 {
181            let r = a % b;
182            a = b;
183            b = r;
184        }
185        let gcd = a as i128;
186        Ok(FrequencyOffset {
187            numerator: numerator / gcd,
188            denominator: denominator / gcd,
189        })
190    }
191}