Skip to main content

qualia_core_db/audio/qac/signal/writer/
mod.rs

1//! Current-format original PCM producer. No defaults, normalization or invented
2//! calibration, pressure relationship, coordinate frame or measured provenance.
3use super::{Error, Limits, Scalar, Timing};
4use crate::q42::{field_envelope as env, field_semantics as sem};
5mod metadata;
6mod samples;
7pub use samples::PcmSamples;
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub enum PcmQuantity {
10    DigitalSample,
11    RawSampleCount,
12    Pressure,
13}
14impl PcmQuantity {
15    fn names(self) -> (&'static str, &'static str) {
16        match self {
17            Self::DigitalSample => ("digital_sample", "1"),
18            Self::RawSampleCount => ("raw_sample_count", "1"),
19            Self::Pressure => ("pressure", "Pa"),
20        }
21    }
22}
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum SignalRelation {
25    DigitalUnrelatedToPressure,
26    RawCounts,
27    PhysicalBaseUnits,
28}
29impl SignalRelation {
30    fn name(self) -> &'static str {
31        match self {
32            Self::DigitalUnrelatedToPressure => "digital-unrelated-to-pressure",
33            Self::RawCounts => "raw-counts",
34            Self::PhysicalBaseUnits => "physical-base-units",
35        }
36    }
37}
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39#[repr(u32)]
40pub enum ProvenanceRole {
41    Measured = 0,
42    Model = 1,
43    Derived = 2,
44    Command = 3,
45    OpaquePreserved = 4,
46}
47/// Supplied assertions only; recording role/purpose grants no execution authority.
48#[derive(Clone, Copy, Debug)]
49pub struct Provenance<'a> {
50    pub role: ProvenanceRole,
51    pub algorithm: Option<&'a str>,
52    pub algorithm_version: Option<&'a str>,
53    pub instrument_uri: Option<&'a str>,
54    pub lineage: Option<&'a str>,
55}
56#[derive(Clone, Copy, Debug)]
57pub struct PcmDocument<'a> {
58    pub samples: PcmSamples<'a>,
59    pub timing: Timing,
60    pub stream_id: u32,
61    pub channels: u32,
62    pub channel_order: &'a str,
63    pub purpose: &'a str,
64    pub quantity: PcmQuantity,
65    pub relation: SignalRelation,
66    pub units_per_stored_sample: f64,
67    pub stored_offset: f64,
68    pub provenance: Provenance<'a>,
69    pub original: Option<&'a [u8]>,
70}
71/// Disposable caller staging. No buffer here is a published result on error.
72pub struct WriteBuffers<'a> {
73    pub metadata: &'a mut [u8],
74    pub payload: &'a mut [u8],
75    pub file: &'a mut [u8],
76}
77#[derive(Clone, Copy, Debug, Default)]
78pub struct WriteOptions {
79    pub envelope: env::Limits,
80    pub shared: sem::Limits,
81    pub signal: Limits,
82}
83impl PcmDocument<'_> {
84    fn preflight(&self, options: WriteOptions) -> Result<(usize, u64, u32), Error> {
85        let n = self.samples.encoded_len()?;
86        let scalar = self.samples.scalar();
87        let stride = self
88            .channels
89            .checked_mul(scalar.bytes())
90            .ok_or(Error::Overflow)?;
91        if stride == 0 || n == 0 || n % stride as usize != 0 || self.stream_id == 0 {
92            return Err(Error::Shape);
93        }
94        let records = n as u64 / u64::from(stride);
95        let original = self.original.map_or(0, |b| b.len() as u64);
96        if self.original.is_some_and(|b| b.is_empty()) {
97            return Err(Error::Shape);
98        }
99        let bytes = (n as u64).checked_add(original).ok_or(Error::Overflow)?;
100        let samples = (n as u64 / u64::from(scalar.bytes()))
101            .checked_add(original)
102            .ok_or(Error::Overflow)?;
103        if options.signal.work < bytes.checked_mul(2).ok_or(Error::Overflow)? {
104            return Err(Error::Limit);
105        }
106        if bytes > options.signal.payload_bytes
107            || samples > options.signal.samples
108            || bytes > options.envelope.aggregate_decoded_bytes
109            || n as u64 > options.envelope.chunk_bytes
110            || original > options.envelope.chunk_bytes
111            || options.signal.entries < if self.original.is_some() { 2 } else { 1 }
112        {
113            return Err(Error::Limit);
114        }
115        if !self.units_per_stored_sample.is_finite()
116            || self.units_per_stored_sample <= 0.0
117            || !self.stored_offset.is_finite()
118        {
119            return Err(Error::Profile);
120        }
121        match (self.quantity, self.relation) {
122            (PcmQuantity::DigitalSample, SignalRelation::DigitalUnrelatedToPressure) => {}
123            (PcmQuantity::RawSampleCount, SignalRelation::RawCounts) => {
124                if !matches!(scalar, Scalar::I16 | Scalar::I24 | Scalar::I32)
125                    || self.units_per_stored_sample != 1.0
126                    || self.stored_offset != 0.0
127                {
128                    return Err(Error::Unit);
129                }
130            }
131            (PcmQuantity::Pressure, SignalRelation::PhysicalBaseUnits) => {
132                if self.units_per_stored_sample != 1.0 || self.stored_offset != 0.0 {
133                    return Err(Error::Unit);
134                }
135            }
136            _ => return Err(Error::Unit),
137        }
138        self.timing.time_at(records - 1)?;
139        Ok((n, records, stride))
140    }
141    /// Metadata, payload and file staging are caller-owned. On every failure the
142    /// entire final output is unchanged; source slices are never modified. Original
143    /// bytes become a bound opaque source entry, not a replacement for PCM samples.
144    pub fn encode_into(
145        &self,
146        buffers: WriteBuffers<'_>,
147        scratch: &mut sem::Scratch<'_>,
148        output: &mut [u8],
149        options: WriteOptions,
150    ) -> Result<usize, Error> {
151        let (n, records, stride) = self.preflight(options)?;
152        let payload_n = self.samples.encode_into(buffers.payload)?;
153        debug_assert_eq!(n, payload_n);
154        let meta_n = metadata::encode(self, records, buffers.metadata, options.envelope)?;
155        let empty = env::EntryInput {
156            mode: 0x104,
157            revision: 1,
158            flags: 0,
159            stream_id: 0,
160            frame_id: 0,
161            start_tick: 0,
162            time_count: 0,
163            spatial_key: 0,
164            record_count: 1,
165            stride: 1,
166            codec: 0,
167            descriptor_id: 8,
168            payload: &[],
169        };
170        let mut entries = [empty; 2];
171        let mut count = 0;
172        if let Some(original) = self.original {
173            entries[0] = env::EntryInput {
174                record_count: original.len() as u64,
175                payload: original,
176                ..empty
177            };
178            count = 1;
179        }
180        entries[count] = env::EntryInput {
181            mode: 0x100,
182            revision: 1,
183            flags: 2,
184            stream_id: self.stream_id,
185            frame_id: 0,
186            start_tick: self.timing.start_tick,
187            time_count: records,
188            spatial_key: 0,
189            record_count: records,
190            stride,
191            codec: 0,
192            descriptor_id: 5,
193            payload: &buffers.payload[..n],
194        };
195        count += 1;
196        let input = env::EnvelopeInput {
197            family: env::Family::QacV1Candidate,
198            flags: 0,
199            metadata: &buffers.metadata[..meta_n],
200            entries: &entries[..count],
201        };
202        super::encode(
203            input,
204            options.envelope,
205            options.shared,
206            options.signal,
207            scratch,
208            buffers.file,
209            output,
210        )
211    }
212}
213#[cfg(test)]
214mod tests;