1use crate::q42::field_envelope::{
4 BlockInput, EntryInput, EnvelopeInput, Family, FieldInput, FieldValue, Limits, MetadataInput,
5};
6
7use super::envelope::AdmittedEnvelope;
8use super::types::*;
9
10#[derive(Debug, Clone)]
11pub enum OwnedValue {
12 U32(Vec<u32>),
13 U64(Vec<u64>),
14 I64(Vec<i64>),
15 F32(Vec<f32>),
16 F64(Vec<f64>),
17 Utf8(String),
18 Bytes(Vec<u8>),
19 MetadataRefs(Vec<u32>),
20 EntryRefs(Vec<u32>),
21}
22
23impl OwnedValue {
24 fn as_field_value(&self) -> FieldValue<'_> {
25 match self {
26 Self::U32(v) => FieldValue::U32(v),
27 Self::U64(v) => FieldValue::U64(v),
28 Self::I64(v) => FieldValue::I64(v),
29 Self::F32(v) => FieldValue::F32(v),
30 Self::F64(v) => FieldValue::F64(v),
31 Self::Utf8(s) => FieldValue::Utf8(s),
32 Self::Bytes(b) => FieldValue::Bytes(b),
33 Self::MetadataRefs(r) => FieldValue::MetadataRefs(r),
34 Self::EntryRefs(r) => FieldValue::EntryRefs(r),
35 }
36 }
37}
38
39#[derive(Debug, Clone)]
40pub struct OwnedField {
41 pub key: u16,
42 pub critical: bool,
43 pub value: OwnedValue,
44}
45
46impl OwnedField {
47 pub fn crit(key: u16, value: OwnedValue) -> Self {
48 Self {
49 key,
50 critical: true,
51 value,
52 }
53 }
54
55 pub fn opt(key: u16, value: OwnedValue) -> Self {
56 Self {
57 key,
58 critical: false,
59 value,
60 }
61 }
62}
63
64#[derive(Debug, Clone)]
65pub struct OwnedBlock {
66 pub id: u32,
67 pub schema_type: u16,
68 pub revision: u16,
69 pub critical: bool,
70 pub fields: Vec<OwnedField>,
71}
72
73#[derive(Debug, Clone)]
75pub struct DescriptorSpec<'a> {
76 pub clock_id: Option<u32>,
77 pub frame_id: Option<u32>,
78 pub provenance_id: u32,
79 pub medium_id: Option<u32>,
80 pub transform_id: Option<u32>,
81 pub calibration_id: Option<u32>,
82 pub quantity: &'a str,
83 pub units: &'a str,
84 pub channels: Option<u32>,
85 pub layout: Option<&'a str>,
86 pub scalar: Option<AuxScalar>,
87 pub model_uri: &'a str,
88 pub sample_rate: Option<RationalRate>,
89 pub valid_record_count: Option<u64>,
90 pub validity_mask_entry: Option<u32>,
91 pub source_entries: &'a [u32],
92 pub extension_metadata: &'a [u32],
93}
94
95#[derive(Debug, Clone)]
97pub struct ModelGridSpec<'a> {
98 pub model_uri: &'a str,
99 pub model_version: &'a str,
100 pub discretization: Option<&'a str>,
101 pub component_offsets_xyz: &'a [f64],
102 pub component_time_offset_num: &'a [i64],
103 pub component_time_offset_den: &'a [u64],
104 pub timestep: Option<RationalRate>,
105 pub tolerance_abs: Option<f64>,
106 pub tolerance_rel: Option<f64>,
107 pub tensor_shape: &'a [u64],
108 pub component_names: &'a str,
109}
110
111#[derive(Debug, Default, Clone)]
113pub struct MetadataBuilder {
114 pub blocks: Vec<OwnedBlock>,
115}
116
117impl MetadataBuilder {
118 pub fn new() -> Self {
119 Self { blocks: Vec::new() }
120 }
121
122 pub fn push_block(&mut self, mut block: OwnedBlock) -> Result<u32, ProfileError> {
123 block.fields.sort_by_key(|f| f.key);
124 for w in block.fields.windows(2) {
125 if w[0].key >= w[1].key || w[0].key == 0 {
126 return Err(ProfileError::InvalidOrdering);
127 }
128 }
129 if block.id == 0 {
130 return Err(ProfileError::InvalidOrdering);
131 }
132 let id = block.id;
133 self.blocks.push(block);
134 self.blocks.sort_by_key(|b| b.id);
135 for w in self.blocks.windows(2) {
136 if w[0].id >= w[1].id {
137 return Err(ProfileError::InvalidOrdering);
138 }
139 }
140 Ok(id)
141 }
142
143 pub fn push_clock(&mut self, id: u32, spec: &ClockSpec) -> Result<u32, ProfileError> {
144 spec.validate()?;
145 self.push_block(OwnedBlock {
146 id,
147 schema_type: 1,
148 revision: 1,
149 critical: true,
150 fields: vec![
151 OwnedField::crit(1, OwnedValue::U32(vec![spec.scale])),
152 OwnedField::crit(2, OwnedValue::I64(vec![spec.epoch_seconds])),
153 OwnedField::crit(3, OwnedValue::U32(vec![spec.epoch_nanoseconds])),
154 OwnedField::crit(4, OwnedValue::U64(vec![spec.ticks_per_second.num])),
155 OwnedField::crit(5, OwnedValue::U64(vec![spec.ticks_per_second.den])),
156 ],
157 })
158 }
159
160 pub fn push_frame(&mut self, id: u32, spec: &FrameSpec<'_>) -> Result<u32, ProfileError> {
161 validate_identifier_str(spec.convention, "frame.convention")?;
162 let mut fields = vec![
163 OwnedField::crit(1, OwnedValue::U32(vec![spec.kind])),
164 OwnedField::crit(3, OwnedValue::F64(spec.origin_m.to_vec())),
165 OwnedField::crit(
166 4,
167 OwnedValue::F64(vec![
168 spec.rotation.x,
169 spec.rotation.y,
170 spec.rotation.z,
171 spec.rotation.w,
172 ]),
173 ),
174 OwnedField::crit(8, OwnedValue::Utf8(spec.convention.to_owned())),
175 ];
176 if let Some(p) = spec.parent_block_id {
177 fields.push(OwnedField::crit(2, OwnedValue::MetadataRefs(vec![p])));
178 }
179 if let Some(sp) = spec.grid_spacing_m {
180 fields.push(OwnedField::crit(5, OwnedValue::F64(sp.to_vec())));
181 }
182 if let Some(dim) = spec.grid_dimensions {
183 fields.push(OwnedField::crit(6, OwnedValue::U32(dim.to_vec())));
184 }
185 if let Some(ord) = spec.index_order {
186 fields.push(OwnedField::opt(7, OwnedValue::U32(vec![ord])));
187 }
188 if let Some(crs) = spec.crs_definition {
189 fields.push(OwnedField::opt(9, OwnedValue::Bytes(crs.to_vec())));
190 }
191 self.push_block(OwnedBlock {
192 id,
193 schema_type: 2,
194 revision: 1,
195 critical: true,
196 fields,
197 })
198 }
199
200 pub fn push_instant(&mut self, id: u32, spec: &InstantSpec) -> Result<u32, ProfileError> {
201 let checked = InstantSpec::new(
202 spec.clock_block_id,
203 spec.tick,
204 spec.subtick_num,
205 spec.subtick_den,
206 )?;
207 self.push_block(OwnedBlock {
208 id,
209 schema_type: 5,
210 revision: 1,
211 critical: true,
212 fields: vec![
213 OwnedField::crit(1, OwnedValue::MetadataRefs(vec![checked.clock_block_id])),
214 OwnedField::crit(2, OwnedValue::I64(vec![checked.tick])),
215 OwnedField::crit(3, OwnedValue::U64(vec![checked.subtick_num])),
216 OwnedField::crit(4, OwnedValue::U64(vec![checked.subtick_den])),
217 ],
218 })
219 }
220
221 pub fn push_provenance(&mut self, id: u32, spec: &ProvenanceSpec<'_>) -> Result<u32, ProfileError> {
222 let mut fields = vec![OwnedField::crit(1, OwnedValue::U32(vec![spec.role]))];
223 if !spec.source_digests.is_empty() {
224 let mut cat = Vec::with_capacity(spec.source_digests.len() * 32);
225 for d in spec.source_digests {
226 cat.extend_from_slice(d);
227 }
228 fields.push(OwnedField::crit(2, OwnedValue::Bytes(cat)));
229 }
230 if let Some(alg) = spec.algorithm {
231 fields.push(OwnedField::opt(3, OwnedValue::Utf8(alg.to_owned())));
232 }
233 if let Some(ver) = spec.algorithm_version {
234 fields.push(OwnedField::opt(4, OwnedValue::Utf8(ver.to_owned())));
235 }
236 if let Some(uri) = spec.instrument_uri {
237 fields.push(OwnedField::opt(5, OwnedValue::Utf8(uri.to_owned())));
238 }
239 if let Some(auth) = spec.authority_receipt_digest {
240 fields.push(OwnedField::opt(6, OwnedValue::Bytes(auth.to_vec())));
241 }
242 if let Some(lin) = spec.lineage {
243 fields.push(OwnedField::opt(7, OwnedValue::Utf8(lin.to_owned())));
244 }
245 self.push_block(OwnedBlock {
246 id,
247 schema_type: 4,
248 revision: 1,
249 critical: true,
250 fields,
251 })
252 }
253
254 pub fn push_calibration(&mut self, id: u32, spec: &CalibrationSpec<'_>) -> Result<u32, ProfileError> {
255 spec.validate()?;
256 let mut fields = vec![
257 OwnedField::crit(1, OwnedValue::Utf8(spec.input_quantity.to_owned())),
258 OwnedField::crit(2, OwnedValue::Utf8(spec.output_units.to_owned())),
259 OwnedField::crit(3, OwnedValue::F64(vec![spec.scale])),
260 OwnedField::crit(4, OwnedValue::F64(vec![spec.offset])),
261 ];
262 if let Some(p0) = spec.reference_pressure_pa {
263 fields.push(OwnedField::opt(5, OwnedValue::F64(vec![p0])));
264 }
265 if let Some(resp) = spec.response_entry {
266 fields.push(OwnedField::opt(6, OwnedValue::EntryRefs(vec![resp])));
267 }
268 if let Some(unc) = spec.uncertainty_entry {
269 fields.push(OwnedField::opt(7, OwnedValue::EntryRefs(vec![unc])));
270 }
271 if let Some(d) = spec.calibration_digest {
272 fields.push(OwnedField::opt(8, OwnedValue::Bytes(d.to_vec())));
273 }
274 if let Some(vf) = spec.valid_from {
275 fields.push(OwnedField::opt(9, OwnedValue::MetadataRefs(vec![vf])));
276 }
277 if let Some(vu) = spec.valid_until {
278 fields.push(OwnedField::opt(10, OwnedValue::MetadataRefs(vec![vu])));
279 }
280 self.push_block(OwnedBlock {
281 id,
282 schema_type: 202,
283 revision: 1,
284 critical: true,
285 fields,
286 })
287 }
288
289 pub fn push_descriptor(&mut self, id: u32, spec: &DescriptorSpec<'_>) -> Result<u32, ProfileError> {
290 let mut fields = Vec::with_capacity(18);
291 if let Some(clk) = spec.clock_id {
292 fields.push(OwnedField::crit(1, OwnedValue::MetadataRefs(vec![clk])));
293 }
294 if let Some(fr) = spec.frame_id {
295 fields.push(OwnedField::crit(2, OwnedValue::MetadataRefs(vec![fr])));
296 }
297 fields.push(OwnedField::crit(3, OwnedValue::MetadataRefs(vec![spec.provenance_id])));
298 if let Some(med) = spec.medium_id {
299 fields.push(OwnedField::crit(4, OwnedValue::MetadataRefs(vec![med])));
300 }
301 if let Some(tr) = spec.transform_id {
302 fields.push(OwnedField::crit(5, OwnedValue::MetadataRefs(vec![tr])));
303 }
304 if let Some(cal) = spec.calibration_id {
305 fields.push(OwnedField::opt(6, OwnedValue::MetadataRefs(vec![cal])));
306 }
307 fields.push(OwnedField::crit(7, OwnedValue::Utf8(spec.quantity.to_owned())));
308 fields.push(OwnedField::crit(8, OwnedValue::Utf8(spec.units.to_owned())));
309 if let Some(ch) = spec.channels {
310 fields.push(OwnedField::crit(9, OwnedValue::U32(vec![ch])));
311 }
312 if let Some(lay) = spec.layout {
313 fields.push(OwnedField::crit(10, OwnedValue::Utf8(lay.to_owned())));
314 }
315 if let Some(sc) = spec.scalar {
316 fields.push(OwnedField::crit(11, OwnedValue::U32(vec![sc as u32])));
317 }
318 fields.push(OwnedField::crit(12, OwnedValue::Utf8(spec.model_uri.to_owned())));
319 if let Some(sr) = spec.sample_rate {
320 fields.push(OwnedField::crit(13, OwnedValue::U64(vec![sr.num])));
321 fields.push(OwnedField::crit(14, OwnedValue::U64(vec![sr.den])));
322 }
323 if let Some(vrc) = spec.valid_record_count {
324 fields.push(OwnedField::crit(15, OwnedValue::U64(vec![vrc])));
325 }
326 if let Some(vm) = spec.validity_mask_entry {
327 fields.push(OwnedField::crit(16, OwnedValue::EntryRefs(vec![vm])));
328 }
329 if !spec.source_entries.is_empty() {
330 fields.push(OwnedField::opt(17, OwnedValue::EntryRefs(spec.source_entries.to_vec())));
331 }
332 if !spec.extension_metadata.is_empty() {
333 fields.push(OwnedField::crit(18, OwnedValue::MetadataRefs(spec.extension_metadata.to_vec())));
334 }
335 self.push_block(OwnedBlock {
336 id,
337 schema_type: 3,
338 revision: 1,
339 critical: true,
340 fields,
341 })
342 }
343
344 pub fn push_model_grid(&mut self, id: u32, spec: &ModelGridSpec<'_>) -> Result<u32, ProfileError> {
345 let mut fields = vec![
346 OwnedField::crit(1, OwnedValue::Utf8(spec.model_uri.to_owned())),
347 OwnedField::crit(2, OwnedValue::Utf8(spec.model_version.to_owned())),
348 OwnedField::crit(14, OwnedValue::U64(spec.tensor_shape.to_vec())),
349 OwnedField::crit(15, OwnedValue::Utf8(spec.component_names.to_owned())),
350 ];
351 if let Some(disc) = spec.discretization {
352 fields.push(OwnedField::opt(3, OwnedValue::Utf8(disc.to_owned())));
353 }
354 if !spec.component_offsets_xyz.is_empty() {
355 fields.push(OwnedField::opt(4, OwnedValue::F64(spec.component_offsets_xyz.to_vec())));
356 }
357 if !spec.component_time_offset_num.is_empty() {
358 fields.push(OwnedField::opt(5, OwnedValue::I64(spec.component_time_offset_num.to_vec())));
359 }
360 if let Some(ts) = spec.timestep {
361 fields.push(OwnedField::opt(10, OwnedValue::U64(vec![ts.num])));
362 fields.push(OwnedField::opt(11, OwnedValue::U64(vec![ts.den])));
363 }
364 if let Some(ta) = spec.tolerance_abs {
365 fields.push(OwnedField::opt(12, OwnedValue::F64(vec![ta])));
366 }
367 if let Some(tr) = spec.tolerance_rel {
368 fields.push(OwnedField::opt(13, OwnedValue::F64(vec![tr])));
369 }
370 if !spec.component_time_offset_den.is_empty() {
371 fields.push(OwnedField::opt(16, OwnedValue::U64(spec.component_time_offset_den.to_vec())));
372 }
373 self.push_block(OwnedBlock {
374 id,
375 schema_type: 205,
376 revision: 1,
377 critical: true,
378 fields,
379 })
380 }
381
382 pub fn encode(&self, limits: Limits) -> Result<Vec<u8>, ProfileError> {
383 let field_inputs_per_block: Vec<Vec<FieldInput<'_>>> = self
384 .blocks
385 .iter()
386 .map(|b| {
387 b.fields
388 .iter()
389 .map(|f| FieldInput {
390 key: f.key,
391 flags: u8::from(f.critical),
392 value: f.value.as_field_value(),
393 })
394 .collect()
395 })
396 .collect();
397 let block_inputs: Vec<BlockInput<'_>> = self
398 .blocks
399 .iter()
400 .zip(&field_inputs_per_block)
401 .map(|(b, fields)| BlockInput {
402 id: b.id,
403 schema_type: b.schema_type,
404 revision: b.revision,
405 flags: u32::from(b.critical),
406 fields,
407 })
408 .collect();
409 let input = MetadataInput {
410 blocks: &block_inputs,
411 };
412 let len = input.encoded_len(limits)?;
413 let mut buf = vec![0u8; len];
414 let written = input.encode_into(&mut buf, limits)?.len();
415 buf.truncate(written);
416 Ok(buf)
417 }
418}
419
420#[derive(Debug, Clone)]
422pub struct OwnedEntry {
423 pub mode: u16,
424 pub flags: u32,
425 pub stream_id: u32,
426 pub frame_id: u32,
427 pub start_tick: i64,
428 pub time_count: u64,
429 pub spatial_key: u64,
430 pub record_count: u64,
431 pub stride: u32,
432 pub descriptor_id: u32,
433 pub payload: Vec<u8>,
434}
435
436pub fn push_validity_mask_entry(
438 meta: &mut MetadataBuilder,
439 descriptor_id: u32,
440 prov_id: u32,
441 stream_id: u32,
442 start_tick: i64,
443 time_count: u64,
444 mask: &[u8],
445) -> Result<OwnedEntry, ProfileError> {
446 if mask.is_empty() || mask.iter().any(|&b| b > 1) {
447 return Err(ProfileError::InvalidValidityBits);
448 }
449 let flags = if time_count > 0 { 3 } else { 1 };
450 let (clock_id, sample_rate) = if time_count > 0 {
451 (Some(1), Some(RationalRate::new(1, 1)?))
452 } else {
453 (None, None)
454 };
455 meta.push_descriptor(
456 descriptor_id,
457 &DescriptorSpec {
458 clock_id,
459 frame_id: None,
460 provenance_id: prov_id,
461 medium_id: None,
462 transform_id: None,
463 calibration_id: None,
464 quantity: "validity-mask",
465 units: "1",
466 channels: Some(1),
467 layout: Some("byte"),
468 scalar: Some(AuxScalar::U8),
469 model_uri: "urn:qac:validity-mask:v1",
470 sample_rate,
471 valid_record_count: None,
472 validity_mask_entry: None,
473 source_entries: &[],
474 extension_metadata: &[],
475 },
476 )?;
477 Ok(OwnedEntry {
478 mode: MODE_VALIDITY_MASK,
479 flags,
480 stream_id,
481 frame_id: 0,
482 start_tick: if time_count > 0 { start_tick } else { 0 },
483 time_count,
484 spatial_key: 0,
485 record_count: mask.len() as u64,
486 stride: 1,
487 descriptor_id,
488 payload: mask.to_vec(),
489 })
490}
491
492pub fn assemble_qac_v1(
494 meta: &MetadataBuilder,
495 entries: &[OwnedEntry],
496 limits: ProfileLimits,
497) -> Result<Vec<u8>, ProfileError> {
498 for w in entries.windows(2) {
499 let ka = (
500 w[0].stream_id,
501 w[0].start_tick,
502 w[0].spatial_key,
503 w[0].mode,
504 w[0].descriptor_id,
505 );
506 let kb = (
507 w[1].stream_id,
508 w[1].start_tick,
509 w[1].spatial_key,
510 w[1].mode,
511 w[1].descriptor_id,
512 );
513 if ka >= kb {
514 return Err(ProfileError::InvalidOrdering);
515 }
516 }
517 let meta_bytes = meta.encode(limits.envelope)?;
518 let entry_inputs: Vec<EntryInput<'_>> = entries
519 .iter()
520 .map(|e| EntryInput {
521 mode: e.mode,
522 revision: 1,
523 flags: e.flags,
524 stream_id: e.stream_id,
525 frame_id: e.frame_id,
526 start_tick: e.start_tick,
527 time_count: e.time_count,
528 spatial_key: e.spatial_key,
529 record_count: e.record_count,
530 stride: e.stride,
531 codec: 0,
532 descriptor_id: e.descriptor_id,
533 payload: &e.payload,
534 })
535 .collect();
536 let env_input = EnvelopeInput {
537 family: Family::QacV1Candidate,
538 flags: 0,
539 metadata: &meta_bytes,
540 entries: &entry_inputs,
541 };
542 let len = env_input.encoded_len(limits.envelope)?;
543 let mut out = vec![0u8; len];
544 let written = env_input.encode_into(&mut out, limits.envelope)?.len();
545 out.truncate(written);
546 let _ = AdmittedEnvelope::open_alloc(&out, limits)?;
547 Ok(out)
548}