1use std::{collections::BTreeMap, fmt, str::FromStr};
2
3use serde::{Deserialize, Deserializer, Serialize, Serializer};
4
5use crate::{
6 BinaryMask, ComparisonOutcome, DeclaredGap, ErrorCode, FrameRegion, FrameSequence, Marker,
7 PixelDimensions, Result, SelectionReason, StoryboardSelection, TimeRange, VisionError,
8 sequence::{NonEmptyText, validate_gaps, validate_markers},
9};
10
11stable_registry! {
12 pub enum ArtifactKind {
14 BeforeDuringAfter => "before_during_after",
15 Storyboard => "storyboard",
16 DifferenceMap => "difference_map",
17 RegionFilmstrip => "region_filmstrip",
18 MotionHistory => "motion_history",
19 }
20}
21
22#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24pub struct GeneratorDescriptor {
25 pub name: &'static str,
26 pub version: &'static str,
27}
28
29pub const fn generator_descriptor(kind: ArtifactKind) -> GeneratorDescriptor {
31 match kind {
32 ArtifactKind::Storyboard | ArtifactKind::BeforeDuringAfter => GeneratorDescriptor {
33 name: "temporal-storyboard",
34 version: "1.1.0",
35 },
36 ArtifactKind::DifferenceMap => GeneratorDescriptor {
37 name: "temporal-difference-map",
38 version: "v1",
39 },
40 ArtifactKind::RegionFilmstrip => GeneratorDescriptor {
41 name: "region-filmstrip",
42 version: "1.0.0",
43 },
44 ArtifactKind::MotionHistory => GeneratorDescriptor {
45 name: "motion-history",
46 version: "1.0.0",
47 },
48 }
49}
50
51stable_registry! {
52 pub enum EvidenceClass {
54 SourceFrame => "source_frame",
55 SourceDerived => "source_derived",
56 Inferred => "inferred",
57 }
58}
59
60stable_registry! {
61 pub enum NormalizationKind {
63 ColorSpaceConversion => "color_space_conversion",
64 AlphaCompositing => "alpha_compositing",
65 IntegerScaling => "integer_scaling",
66 FixedCrop => "fixed_crop",
67 Denoising => "denoising",
68 Thresholding => "thresholding",
69 }
70}
71
72#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
74pub struct AlgorithmDescriptor {
75 name: NonEmptyText,
76 version: NonEmptyText,
77}
78
79impl AlgorithmDescriptor {
80 pub fn new(name: impl Into<String>, version: impl Into<String>) -> Result<Self> {
81 Ok(Self {
82 name: NonEmptyText::new(
83 name,
84 ErrorCode::InvalidParameter,
85 "algorithm name must not be empty",
86 )?,
87 version: NonEmptyText::new(
88 version,
89 ErrorCode::InvalidParameter,
90 "algorithm version must not be empty",
91 )?,
92 })
93 }
94
95 pub fn name(&self) -> &str {
96 self.name.as_str()
97 }
98
99 pub fn version(&self) -> &str {
100 self.version.as_str()
101 }
102}
103
104impl<'de> Deserialize<'de> for AlgorithmDescriptor {
105 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
106 where
107 D: Deserializer<'de>,
108 {
109 #[derive(Deserialize)]
110 struct Wire {
111 name: String,
112 version: String,
113 }
114 let wire = Wire::deserialize(deserializer)?;
115 Self::new(wire.name, wire.version).map_err(serde::de::Error::custom)
116 }
117}
118
119#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
121#[serde(transparent)]
122pub struct FiniteNumber(f64);
123
124impl FiniteNumber {
125 pub fn new(value: f64) -> Result<Self> {
126 if !value.is_finite() {
127 return Err(VisionError::new(
128 ErrorCode::InvalidParameter,
129 "numeric parameters must be finite",
130 ));
131 }
132 Ok(Self(if value == 0.0 { 0.0 } else { value }))
133 }
134
135 pub const fn get(self) -> f64 {
136 self.0
137 }
138}
139
140impl<'de> Deserialize<'de> for FiniteNumber {
141 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
142 where
143 D: Deserializer<'de>,
144 {
145 Self::new(f64::deserialize(deserializer)?).map_err(serde::de::Error::custom)
146 }
147}
148
149#[derive(Clone, Debug, PartialEq, Serialize)]
151#[serde(tag = "type", content = "value", rename_all = "snake_case")]
152pub enum ParameterValue {
153 Bool(bool),
154 Signed(i64),
155 Unsigned(u64),
156 Number(FiniteNumber),
157 Text(Box<str>),
158 List(Vec<ParameterValue>),
159 Object(BTreeMap<Box<str>, ParameterValue>),
160}
161
162impl ParameterValue {
163 fn validate(&self) -> Result<()> {
164 match self {
165 Self::List(values) => values.iter().try_for_each(Self::validate),
166 Self::Object(values) => {
167 for (key, value) in values {
168 if key.is_empty() {
169 return Err(VisionError::new(
170 ErrorCode::InvalidParameter,
171 "parameter object keys must not be empty",
172 ));
173 }
174 value.validate()?;
175 }
176 Ok(())
177 }
178 _ => Ok(()),
179 }
180 }
181}
182
183impl<'de> Deserialize<'de> for ParameterValue {
184 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
185 where
186 D: Deserializer<'de>,
187 {
188 #[derive(Deserialize)]
189 #[serde(tag = "type", content = "value", rename_all = "snake_case")]
190 enum Wire {
191 Bool(bool),
192 Signed(i64),
193 Unsigned(u64),
194 Number(FiniteNumber),
195 Text(Box<str>),
196 List(Vec<Wire>),
197 Object(BTreeMap<Box<str>, Wire>),
198 }
199
200 fn convert(value: Wire) -> ParameterValue {
201 match value {
202 Wire::Bool(value) => ParameterValue::Bool(value),
203 Wire::Signed(value) => ParameterValue::Signed(value),
204 Wire::Unsigned(value) => ParameterValue::Unsigned(value),
205 Wire::Number(value) => ParameterValue::Number(value),
206 Wire::Text(value) => ParameterValue::Text(value),
207 Wire::List(values) => {
208 ParameterValue::List(values.into_iter().map(convert).collect())
209 }
210 Wire::Object(values) => ParameterValue::Object(
211 values
212 .into_iter()
213 .map(|(key, value)| (key, convert(value)))
214 .collect(),
215 ),
216 }
217 }
218
219 let value = convert(Wire::deserialize(deserializer)?);
220 value.validate().map_err(serde::de::Error::custom)?;
221 Ok(value)
222 }
223}
224
225#[derive(Clone, Debug, Default, PartialEq, Serialize)]
227#[serde(transparent)]
228pub struct Parameters(BTreeMap<Box<str>, ParameterValue>);
229
230impl Parameters {
231 pub fn new(values: BTreeMap<Box<str>, ParameterValue>) -> Result<Self> {
232 for (key, value) in &values {
233 if key.is_empty() {
234 return Err(VisionError::new(
235 ErrorCode::InvalidParameter,
236 "parameter names must not be empty",
237 ));
238 }
239 value.validate()?;
240 }
241 Ok(Self(values))
242 }
243
244 pub fn empty() -> Self {
245 Self::default()
246 }
247
248 pub fn get(&self, name: &str) -> Option<&ParameterValue> {
249 self.0.get(name)
250 }
251
252 pub fn iter(&self) -> impl ExactSizeIterator<Item = (&str, &ParameterValue)> {
253 self.0.iter().map(|(name, value)| (name.as_ref(), value))
254 }
255
256 pub(crate) fn insert(&mut self, name: &'static str, value: ParameterValue) -> Result<()> {
257 if name.is_empty() {
258 return Err(VisionError::new(
259 ErrorCode::InvalidParameter,
260 "parameter names must not be empty",
261 ));
262 }
263 value.validate()?;
264 self.0.insert(name.into(), value);
265 Ok(())
266 }
267}
268
269pub(crate) const ANALYSIS_SAMPLING_MODE: &str = "uniform_bounded";
272pub(crate) const ANALYSIS_SAMPLING_SPACING: &str = "uniform";
273const ANALYSIS_SAMPLING_FIELDS: [&str; 5] = [
276 "analyzed_frame_count",
277 "analyzed_source_indices",
278 "mode",
279 "source_frame_count",
280 "spacing",
281];
282
283pub(crate) fn analysis_sampling_parameters<F, M, G, P>(
284 source: &FrameSequence<F, M, G, P>,
285) -> Result<Option<ParameterValue>>
286where
287 F: Eq,
288 M: Eq,
289 G: Eq,
290 P: AsRef<[u8]>,
291{
292 let Some(indices) = source.source_indices() else {
293 return Ok(None);
294 };
295 if indices.len() >= source.source_frame_count() {
299 return Ok(None);
300 }
301 let source_frame_count = u64::try_from(source.source_frame_count()).map_err(|_| {
302 VisionError::new(
303 ErrorCode::InvalidManifest,
304 "analysis sampling source frame count exceeds the manifest format",
305 )
306 })?;
307 let analyzed_frame_count = u64::try_from(indices.len()).map_err(|_| {
308 VisionError::new(
309 ErrorCode::InvalidManifest,
310 "analysis sampling frame count exceeds the manifest format",
311 )
312 })?;
313 let analyzed_source_indices = indices
314 .iter()
315 .map(|index| {
316 u64::try_from(*index)
317 .map(ParameterValue::Unsigned)
318 .map_err(|_| {
319 VisionError::new(
320 ErrorCode::InvalidManifest,
321 "analysis sampling source index exceeds the manifest format",
322 )
323 })
324 })
325 .collect::<Result<Vec<_>>>()?;
326 Ok(Some(ParameterValue::Object(
327 [
328 (
329 "source_frame_count".into(),
330 ParameterValue::Unsigned(source_frame_count),
331 ),
332 (
333 "analyzed_frame_count".into(),
334 ParameterValue::Unsigned(analyzed_frame_count),
335 ),
336 (
337 "analyzed_source_indices".into(),
338 ParameterValue::List(analyzed_source_indices),
339 ),
340 (
341 "mode".into(),
342 ParameterValue::Text(ANALYSIS_SAMPLING_MODE.into()),
343 ),
344 (
345 "spacing".into(),
346 ParameterValue::Text(ANALYSIS_SAMPLING_SPACING.into()),
347 ),
348 ]
349 .into_iter()
350 .collect(),
351 )))
352}
353
354impl<'de> Deserialize<'de> for Parameters {
355 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
356 where
357 D: Deserializer<'de>,
358 {
359 Self::new(BTreeMap::deserialize(deserializer)?).map_err(serde::de::Error::custom)
360 }
361}
362
363#[derive(Clone, Debug, PartialEq, Serialize)]
365pub struct NormalizationStep {
366 kind: NormalizationKind,
367 algorithm_version: NonEmptyText,
368 parameters: Parameters,
369}
370
371impl NormalizationStep {
372 pub fn new(
373 kind: NormalizationKind,
374 algorithm_version: impl Into<String>,
375 parameters: Parameters,
376 ) -> Result<Self> {
377 Ok(Self {
378 kind,
379 algorithm_version: NonEmptyText::new(
380 algorithm_version,
381 ErrorCode::InvalidParameter,
382 "normalization algorithm version must not be empty",
383 )?,
384 parameters,
385 })
386 }
387
388 pub const fn kind(&self) -> NormalizationKind {
389 self.kind
390 }
391
392 pub fn algorithm_version(&self) -> &str {
393 self.algorithm_version.as_str()
394 }
395
396 pub const fn parameters(&self) -> &Parameters {
397 &self.parameters
398 }
399}
400
401impl<'de> Deserialize<'de> for NormalizationStep {
402 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
403 where
404 D: Deserializer<'de>,
405 {
406 #[derive(Deserialize)]
407 struct Wire {
408 kind: NormalizationKind,
409 algorithm_version: String,
410 parameters: Parameters,
411 }
412 let wire = Wire::deserialize(deserializer)?;
413 Self::new(wire.kind, wire.algorithm_version, wire.parameters)
414 .map_err(serde::de::Error::custom)
415 }
416}
417
418#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
420pub struct OutputHash([u8; 32]);
421
422impl OutputHash {
423 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
424 Self(bytes)
425 }
426
427 pub const fn as_bytes(&self) -> &[u8; 32] {
428 &self.0
429 }
430}
431
432impl fmt::Display for OutputHash {
433 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
434 for byte in self.0 {
435 write!(formatter, "{byte:02x}")?;
436 }
437 Ok(())
438 }
439}
440
441impl FromStr for OutputHash {
442 type Err = VisionError;
443
444 fn from_str(value: &str) -> Result<Self> {
445 if value.len() != 64
446 || value
447 .bytes()
448 .any(|byte| !byte.is_ascii_digit() && !(b'a'..=b'f').contains(&byte))
449 {
450 return Err(VisionError::new(
451 ErrorCode::InvalidOutputHash,
452 "output hash must be exactly 64 lowercase hexadecimal characters",
453 ));
454 }
455 let mut bytes = [0_u8; 32];
456 for (index, pair) in value.as_bytes().chunks_exact(2).enumerate() {
457 bytes[index] = (hex_nibble(pair[0]) << 4) | hex_nibble(pair[1]);
458 }
459 Ok(Self(bytes))
460 }
461}
462
463const fn hex_nibble(value: u8) -> u8 {
464 match value {
465 b'0'..=b'9' => value - b'0',
466 b'a'..=b'f' => value - b'a' + 10,
467 _ => 0,
468 }
469}
470
471impl Serialize for OutputHash {
472 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
473 where
474 S: Serializer,
475 {
476 serializer.collect_str(self)
477 }
478}
479
480impl<'de> Deserialize<'de> for OutputHash {
481 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
482 where
483 D: Deserializer<'de>,
484 {
485 <&str>::deserialize(deserializer)?
486 .parse()
487 .map_err(serde::de::Error::custom)
488 }
489}
490
491#[derive(Clone, Copy, Debug, Eq, PartialEq)]
504pub enum SequenceConsumption {
505 EveryDecodedFrame,
511 SelectedFramesOnly,
516}
517
518#[derive(Clone, Debug, PartialEq, Serialize)]
531pub struct ArtifactManifest<ArtifactId, FrameId, MarkerId, GapId> {
532 artifact_id: ArtifactId,
533 artifact_kind: ArtifactKind,
534 evidence_class: EvidenceClass,
535 algorithm: Box<AlgorithmDescriptor>,
536 source_frame_ids: Box<[FrameId]>,
537 analyzed_frame_ids: Box<[FrameId]>,
538 selected_frame_ids: Box<[FrameId]>,
539 storyboard_selection: Option<Box<StoryboardSelection<FrameId>>>,
540 source_frame_count: u64,
541 analyzed_frame_count: u64,
542 omitted_frame_count: u64,
543 range: TimeRange,
544 markers: Box<[Marker<MarkerId>]>,
545 gaps: Box<[DeclaredGap<GapId>]>,
546 region: Option<FrameRegion>,
547 mask: Option<Box<BinaryMask>>,
550 normalization: Box<[NormalizationStep]>,
551 parameters: Parameters,
552 output_dimensions: PixelDimensions,
553 output_hash: OutputHash,
554}
555
556impl<A, F: Clone + Eq, M: Clone + Eq, G: Clone + Eq> ArtifactManifest<A, F, M, G> {
557 #[allow(clippy::too_many_arguments)]
558 pub fn from_sequence<P: AsRef<[u8]>>(
559 artifact_id: A,
560 artifact_kind: ArtifactKind,
561 evidence_class: EvidenceClass,
562 algorithm: AlgorithmDescriptor,
563 sequence: &FrameSequence<F, M, G, P>,
564 selected_frame_ids: Vec<F>,
565 normalization: Vec<NormalizationStep>,
566 parameters: Parameters,
567 output_dimensions: PixelDimensions,
568 output_hash: OutputHash,
569 ) -> Result<Self> {
570 Self::from_sequence_with_trace_and_domain(
571 artifact_id,
572 artifact_kind,
573 evidence_class,
574 algorithm,
575 sequence,
576 sequence.region(),
577 sequence.mask().cloned(),
578 selected_frame_ids,
579 None,
580 SequenceConsumption::EveryDecodedFrame,
581 normalization,
582 parameters,
583 output_dimensions,
584 output_hash,
585 )
586 }
587
588 #[allow(clippy::too_many_arguments)]
589 pub fn from_storyboard_sequence<P: AsRef<[u8]>>(
590 artifact_id: A,
591 artifact_kind: ArtifactKind,
592 evidence_class: EvidenceClass,
593 algorithm: AlgorithmDescriptor,
594 sequence: &FrameSequence<F, M, G, P>,
595 selected_frame_ids: Vec<F>,
596 storyboard_selection: StoryboardSelection<F>,
597 normalization: Vec<NormalizationStep>,
598 parameters: Parameters,
599 output_dimensions: PixelDimensions,
600 output_hash: OutputHash,
601 ) -> Result<Self> {
602 Self::from_sequence_with_trace_and_domain(
603 artifact_id,
604 artifact_kind,
605 evidence_class,
606 algorithm,
607 sequence,
608 sequence.region(),
609 sequence.mask().cloned(),
610 selected_frame_ids,
611 Some(Box::new(storyboard_selection)),
612 SequenceConsumption::EveryDecodedFrame,
613 normalization,
614 parameters,
615 output_dimensions,
616 output_hash,
617 )
618 }
619
620 #[allow(clippy::too_many_arguments)]
621 pub(crate) fn from_sequence_with_domain<P: AsRef<[u8]>>(
622 artifact_id: A,
623 artifact_kind: ArtifactKind,
624 evidence_class: EvidenceClass,
625 algorithm: AlgorithmDescriptor,
626 sequence: &FrameSequence<F, M, G, P>,
627 region: Option<FrameRegion>,
628 mask: Option<BinaryMask>,
629 selected_frame_ids: Vec<F>,
630 consumption: SequenceConsumption,
631 normalization: Vec<NormalizationStep>,
632 parameters: Parameters,
633 output_dimensions: PixelDimensions,
634 output_hash: OutputHash,
635 ) -> Result<Self> {
636 Self::from_sequence_with_trace_and_domain(
637 artifact_id,
638 artifact_kind,
639 evidence_class,
640 algorithm,
641 sequence,
642 region,
643 mask,
644 selected_frame_ids,
645 None,
646 consumption,
647 normalization,
648 parameters,
649 output_dimensions,
650 output_hash,
651 )
652 }
653
654 #[allow(clippy::too_many_arguments)]
655 fn from_sequence_with_trace_and_domain<P: AsRef<[u8]>>(
656 artifact_id: A,
657 artifact_kind: ArtifactKind,
658 evidence_class: EvidenceClass,
659 algorithm: AlgorithmDescriptor,
660 sequence: &FrameSequence<F, M, G, P>,
661 region: Option<FrameRegion>,
662 mask: Option<BinaryMask>,
663 selected_frame_ids: Vec<F>,
664 storyboard_selection: Option<Box<StoryboardSelection<F>>>,
665 consumption: SequenceConsumption,
666 normalization: Vec<NormalizationStep>,
667 parameters: Parameters,
668 output_dimensions: PixelDimensions,
669 output_hash: OutputHash,
670 ) -> Result<Self> {
671 let source_frame_ids: Box<[F]> = sequence.source_frame_ids().to_vec().into_boxed_slice();
672 let analyzed_frame_ids: Box<[F]> = sequence
677 .frames()
678 .iter()
679 .map(|frame| frame.id().clone())
680 .filter(|id| match consumption {
681 SequenceConsumption::EveryDecodedFrame => true,
682 SequenceConsumption::SelectedFramesOnly => selected_frame_ids.contains(id),
683 })
684 .collect::<Vec<_>>()
685 .into_boxed_slice();
686 if analyzed_frame_ids.len() < selected_frame_ids.len() {
687 return Err(VisionError::new(
688 ErrorCode::InvalidManifest,
689 "manifest selected frames are not all present in the decoded sequence",
690 ));
691 }
692 let source_frame_count = u64::try_from(source_frame_ids.len()).map_err(|_| {
693 VisionError::new(
694 ErrorCode::InvalidManifest,
695 "source frame count exceeds the manifest representation",
696 )
697 })?;
698 let analyzed_frame_count = u64::try_from(analyzed_frame_ids.len()).map_err(|_| {
699 VisionError::new(
700 ErrorCode::InvalidManifest,
701 "analyzed frame count exceeds the manifest representation",
702 )
703 })?;
704 let omitted_frame_count = source_frame_count
705 .checked_sub(analyzed_frame_count)
706 .ok_or_else(|| {
707 VisionError::new(
708 ErrorCode::InvalidManifest,
709 "analyzed frame count exceeds source frame count",
710 )
711 })?;
712
713 let storyboard_selection = storyboard_selection
714 .map(|selection| {
715 let selection = *selection;
716 sequence
717 .source_indices()
718 .map_or(Ok(Box::new(selection.clone())), |indices| {
719 selection.remap_source_indices(indices).map(Box::new)
720 })
721 })
722 .transpose()?;
723 let manifest = Self {
724 artifact_id,
725 artifact_kind,
726 evidence_class,
727 algorithm: Box::new(algorithm),
728 source_frame_ids,
729 analyzed_frame_ids,
730 selected_frame_ids: selected_frame_ids.into_boxed_slice(),
731 storyboard_selection,
732 source_frame_count,
733 analyzed_frame_count,
734 omitted_frame_count,
735 range: sequence.range(),
736 markers: sequence.markers().to_vec().into_boxed_slice(),
737 gaps: sequence.gaps().to_vec().into_boxed_slice(),
738 region,
739 mask: mask.map(Box::new),
740 normalization: normalization.into_boxed_slice(),
741 parameters,
742 output_dimensions,
743 output_hash,
744 };
745 manifest.validate()?;
746 Ok(manifest)
747 }
748
749 fn validate(&self) -> Result<()> {
750 if self.source_frame_ids.is_empty() {
751 return Err(VisionError::new(
752 ErrorCode::InvalidManifest,
753 "manifest source frames must not be empty",
754 ));
755 }
756 validate_unique(
757 &self.source_frame_ids,
758 "source frame identifiers must be unique",
759 )?;
760 if self.analyzed_frame_ids.is_empty() {
761 return Err(VisionError::new(
762 ErrorCode::InvalidManifest,
763 "manifest analyzed frames must not be empty",
764 ));
765 }
766 validate_ordered_subsequence(
767 &self.source_frame_ids,
768 &self.analyzed_frame_ids,
769 "analyzed frame identifiers must be unique",
770 "analyzed frames must be an ordered subsequence of source frames",
771 )?;
772 validate_ordered_subsequence(
773 &self.analyzed_frame_ids,
774 &self.selected_frame_ids,
775 "selected frame identifiers must be unique",
776 "selected frames must be an ordered subsequence of analyzed frames",
777 )?;
778 self.validate_storyboard_trace()?;
779 let source_count = u64::try_from(self.source_frame_ids.len()).map_err(|_| {
780 VisionError::new(
781 ErrorCode::InvalidManifest,
782 "source frame count is too large",
783 )
784 })?;
785 let analyzed_count = u64::try_from(self.analyzed_frame_ids.len()).map_err(|_| {
786 VisionError::new(
787 ErrorCode::InvalidManifest,
788 "analyzed frame count is too large",
789 )
790 })?;
791 if self.source_frame_count != source_count
792 || self.analyzed_frame_count != analyzed_count
793 || self.omitted_frame_count != source_count - analyzed_count
794 {
795 return Err(VisionError::new(
796 ErrorCode::InvalidManifest,
797 "manifest frame counts contradict its identifiers",
798 ));
799 }
800 self.validate_analysis_sampling_disclosure()?;
801 validate_markers(&self.markers, self.range).map_err(as_manifest_error)?;
802 validate_gaps(&self.gaps, self.range).map_err(as_manifest_error)?;
803 if let (Some(region), Some(mask)) = (self.region, self.mask.as_ref())
804 && !region.rect().fits_within(mask.dimensions())
805 {
806 return Err(VisionError::new(
807 ErrorCode::InvalidManifest,
808 "manifest region does not fit its source mask dimensions",
809 ));
810 }
811 Ok(())
812 }
813
814 fn validate_analysis_sampling_disclosure(&self) -> Result<()> {
819 let decimated = self.analyzed_frame_count < self.source_frame_count;
820 let Some(value) = self.parameters.get("analysis_sampling") else {
821 if decimated
822 && matches!(
823 self.artifact_kind,
824 ArtifactKind::DifferenceMap | ArtifactKind::MotionHistory
825 )
826 {
827 return Err(VisionError::new(
828 ErrorCode::InvalidManifest,
829 "a decimated analysis manifest must disclose its analysis sampling",
830 ));
831 }
832 return Ok(());
833 };
834 let ParameterValue::Object(values) = value else {
835 return Err(VisionError::new(
836 ErrorCode::InvalidManifest,
837 "analysis sampling disclosure must be an object",
838 ));
839 };
840 for (name, expected) in [
841 ("source_frame_count", self.source_frame_count),
842 ("analyzed_frame_count", self.analyzed_frame_count),
843 ] {
844 if values.get(name) != Some(&ParameterValue::Unsigned(expected)) {
845 return Err(VisionError::new(
846 ErrorCode::InvalidManifest,
847 "analysis sampling disclosure contradicts the manifest frame counts",
848 ));
849 }
850 }
851 if !decimated {
852 return Err(VisionError::new(
853 ErrorCode::InvalidManifest,
854 "an undecimated manifest must not claim an analysis sampling mode",
855 ));
856 }
857 for (name, expected) in [
863 ("mode", ANALYSIS_SAMPLING_MODE),
864 ("spacing", ANALYSIS_SAMPLING_SPACING),
865 ] {
866 let ParameterValue::Text(text) = values.get(name).ok_or_else(|| {
867 VisionError::new(
868 ErrorCode::InvalidManifest,
869 "analysis sampling disclosure is missing a required field",
870 )
871 })?
872 else {
873 return Err(VisionError::new(
874 ErrorCode::InvalidManifest,
875 "analysis sampling mode and spacing must be text",
876 ));
877 };
878 if text.as_ref() != expected {
879 return Err(VisionError::new(
880 ErrorCode::InvalidManifest,
881 "analysis sampling disclosure names a sampling scheme this crate does not produce",
882 ));
883 }
884 }
885 let Some(ParameterValue::List(indices)) = values.get("analyzed_source_indices") else {
886 return Err(VisionError::new(
887 ErrorCode::InvalidManifest,
888 "analysis sampling disclosure must list its analyzed source indices",
889 ));
890 };
891 if indices.len() as u64 != self.analyzed_frame_count {
892 return Err(VisionError::new(
893 ErrorCode::InvalidManifest,
894 "analysis sampling disclosure contradicts the manifest frame counts",
895 ));
896 }
897 let mut previous: Option<u64> = None;
898 for (position, index) in indices.iter().enumerate() {
899 let ParameterValue::Unsigned(index) = index else {
900 return Err(VisionError::new(
901 ErrorCode::InvalidManifest,
902 "analysis sampling source indices must be unsigned",
903 ));
904 };
905 if *index >= self.source_frame_count {
906 return Err(VisionError::new(
907 ErrorCode::InvalidManifest,
908 "analysis sampling source index lies outside the manifest source frames",
909 ));
910 }
911 if previous.is_some_and(|previous| previous >= *index) {
915 return Err(VisionError::new(
916 ErrorCode::InvalidManifest,
917 "analysis sampling source indices must be strictly increasing",
918 ));
919 }
920 previous = Some(*index);
921 let resolved = usize::try_from(*index)
928 .ok()
929 .and_then(|index| self.source_frame_ids.get(index));
930 if resolved != self.analyzed_frame_ids.get(position) {
931 return Err(VisionError::new(
932 ErrorCode::InvalidManifest,
933 "analysis sampling source index does not identify the analyzed frame",
934 ));
935 }
936 }
937 for name in values.keys() {
940 if !ANALYSIS_SAMPLING_FIELDS.contains(&name.as_ref()) {
941 return Err(VisionError::new(
942 ErrorCode::InvalidManifest,
943 "analysis sampling disclosure carries an unrecognised field",
944 ));
945 }
946 }
947 Ok(())
948 }
949
950 fn validate_storyboard_trace(&self) -> Result<()> {
951 let storyboard_kind = matches!(
952 self.artifact_kind,
953 ArtifactKind::Storyboard | ArtifactKind::BeforeDuringAfter
954 );
955 let Some(selection) = self.storyboard_selection.as_ref() else {
956 if storyboard_kind {
957 return Err(VisionError::new(
958 ErrorCode::InvalidManifest,
959 "storyboard manifests require their selection trace",
960 ));
961 }
962 return Ok(());
963 };
964 if !storyboard_kind {
965 return Err(VisionError::new(
966 ErrorCode::InvalidManifest,
967 "only storyboard artifacts may carry a storyboard selection trace",
968 ));
969 }
970 selection.validate_local().map_err(as_manifest_error)?;
971 let source_len = self.source_frame_ids.len();
972 if selection.after_index() >= source_len
973 || selection.continuity_segment_count() > source_len
974 {
975 return Err(VisionError::new(
976 ErrorCode::InvalidManifest,
977 "storyboard selection roles exceed the manifest source frames",
978 ));
979 }
980 for selected in selection.selected_frames() {
981 if selected.frame_index() >= source_len
982 || self.source_frame_ids[selected.frame_index()] != *selected.frame_id()
983 || !self.range.contains(selected.timestamp())
984 {
985 return Err(VisionError::new(
986 ErrorCode::InvalidManifest,
987 "storyboard selected trace disagrees with manifest source identity or time",
988 ));
989 }
990 }
991 if selection
992 .omitted_anchors()
993 .iter()
994 .any(|anchor| anchor.frame_index() >= source_len)
995 {
996 return Err(VisionError::new(
997 ErrorCode::InvalidManifest,
998 "storyboard omitted anchors exceed the manifest source frames",
999 ));
1000 }
1001 let expected_selected: Vec<&F> = match self.artifact_kind {
1002 ArtifactKind::Storyboard => selection
1003 .selected_frames()
1004 .iter()
1005 .map(|frame| frame.frame_id())
1006 .collect(),
1007 ArtifactKind::BeforeDuringAfter => {
1008 let mut indices = vec![
1009 selection.before_index(),
1010 selection.during_index(),
1011 selection.after_index(),
1012 ];
1013 indices.sort_unstable();
1014 indices.dedup();
1015 indices
1016 .into_iter()
1017 .map(|index| &self.source_frame_ids[index])
1018 .collect()
1019 }
1020 _ => unreachable!("non-storyboard traces were rejected"),
1021 };
1022 if expected_selected
1023 .iter()
1024 .copied()
1025 .ne(self.selected_frame_ids.iter())
1026 {
1027 return Err(VisionError::new(
1028 ErrorCode::InvalidManifest,
1029 "storyboard trace does not match manifest selected frame roles",
1030 ));
1031 }
1032
1033 let validate_moment = |moment: &crate::VisualChangeMoment<F>| -> Result<()> {
1034 let comparison = moment.comparison();
1035 if comparison.earlier_frame_index() >= source_len
1036 || comparison.later_frame_index() >= source_len
1037 || self.source_frame_ids[moment.frame_index()] != *moment.frame_id()
1038 || !self.range.contains(moment.timestamp())
1039 {
1040 return Err(VisionError::new(
1041 ErrorCode::InvalidManifest,
1042 "storyboard visual moment disagrees with manifest source identity or time",
1043 ));
1044 }
1045 let earlier_nanos = moment
1046 .timestamp()
1047 .as_nanos()
1048 .checked_sub(comparison.elapsed_nanos())
1049 .ok_or_else(|| {
1050 VisionError::new(
1051 ErrorCode::InvalidManifest,
1052 "storyboard visual moment elapsed time precedes the manifest range",
1053 )
1054 })?;
1055 let comparison_range = TimeRange::new(
1056 crate::Timestamp::from_nanos(earlier_nanos),
1057 moment.timestamp(),
1058 )?;
1059 if !self.range.contains(comparison_range.start())
1060 || self.gaps.iter().any(|gap| {
1061 gap.range().start() <= comparison_range.end()
1062 && gap.range().end() >= comparison_range.start()
1063 })
1064 || !matches!(comparison.outcome(), ComparisonOutcome::Measured(_))
1065 {
1066 return Err(VisionError::new(
1067 ErrorCode::InvalidManifest,
1068 "storyboard visual moments must not cross declared gaps",
1069 ));
1070 }
1071 if let Some(selected) = selection
1072 .selected_frames()
1073 .iter()
1074 .find(|selected| selected.frame_index() == moment.frame_index())
1075 && selected.timestamp() != moment.timestamp()
1076 {
1077 return Err(VisionError::new(
1078 ErrorCode::InvalidManifest,
1079 "storyboard visual moment timestamp disagrees with its selected frame",
1080 ));
1081 }
1082 Ok(())
1083 };
1084 let summary = selection.visual_summary();
1085 for moment in [
1086 summary.first_change(),
1087 summary.peak_baseline_change(),
1088 summary.peak_adjacent_changed_area(),
1089 ]
1090 .into_iter()
1091 .flatten()
1092 {
1093 validate_moment(moment)?;
1094 }
1095 for (moment, reason) in [
1096 (summary.first_change(), SelectionReason::FirstChange),
1097 (
1098 summary.peak_baseline_change(),
1099 SelectionReason::PeakBaselineChange,
1100 ),
1101 ] {
1102 if let Some(moment) = moment {
1103 let represented = selection.selected_frames().iter().any(|frame| {
1104 frame.frame_index() == moment.frame_index() && frame.reasons().contains(&reason)
1105 }) || selection.omitted_anchors().iter().any(|anchor| {
1106 anchor.frame_index() == moment.frame_index() && anchor.reason() == reason
1107 });
1108 if !represented {
1109 return Err(VisionError::new(
1110 ErrorCode::InvalidManifest,
1111 "storyboard visual moment is missing its selection reason",
1112 ));
1113 }
1114 }
1115 }
1116 Ok(())
1117 }
1118
1119 pub const fn artifact_id(&self) -> &A {
1120 &self.artifact_id
1121 }
1122 pub const fn artifact_kind(&self) -> ArtifactKind {
1123 self.artifact_kind
1124 }
1125 pub const fn evidence_class(&self) -> EvidenceClass {
1126 self.evidence_class
1127 }
1128 pub const fn algorithm(&self) -> &AlgorithmDescriptor {
1129 &self.algorithm
1130 }
1131 pub fn source_frame_ids(&self) -> &[F] {
1132 &self.source_frame_ids
1133 }
1134 pub fn analyzed_frame_ids(&self) -> &[F] {
1136 &self.analyzed_frame_ids
1137 }
1138 pub fn selected_frame_ids(&self) -> &[F] {
1139 &self.selected_frame_ids
1140 }
1141 pub fn storyboard_selection(&self) -> Option<&StoryboardSelection<F>> {
1142 self.storyboard_selection.as_deref()
1143 }
1144 pub const fn source_frame_count(&self) -> u64 {
1145 self.source_frame_count
1146 }
1147 pub const fn analyzed_frame_count(&self) -> u64 {
1148 self.analyzed_frame_count
1149 }
1150 pub const fn omitted_frame_count(&self) -> u64 {
1152 self.omitted_frame_count
1153 }
1154 pub const fn range(&self) -> TimeRange {
1155 self.range
1156 }
1157 pub fn markers(&self) -> &[Marker<M>] {
1158 &self.markers
1159 }
1160 pub fn gaps(&self) -> &[DeclaredGap<G>] {
1161 &self.gaps
1162 }
1163 pub const fn region(&self) -> Option<FrameRegion> {
1164 self.region
1165 }
1166 pub fn mask(&self) -> Option<&BinaryMask> {
1167 self.mask.as_deref()
1168 }
1169 pub fn normalization(&self) -> &[NormalizationStep] {
1170 &self.normalization
1171 }
1172 pub const fn parameters(&self) -> &Parameters {
1173 &self.parameters
1174 }
1175 pub const fn output_dimensions(&self) -> PixelDimensions {
1176 self.output_dimensions
1177 }
1178 pub const fn output_hash(&self) -> OutputHash {
1179 self.output_hash
1180 }
1181}
1182
1183impl<'de, A, F, M, G> Deserialize<'de> for ArtifactManifest<A, F, M, G>
1184where
1185 A: Deserialize<'de>,
1186 F: Deserialize<'de> + Clone + Eq,
1187 M: Deserialize<'de> + Clone + Eq,
1188 G: Deserialize<'de> + Clone + Eq,
1189{
1190 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1191 where
1192 D: Deserializer<'de>,
1193 {
1194 #[derive(Deserialize)]
1195 #[serde(
1196 bound(
1197 deserialize = "A: Deserialize<'de>, F: Deserialize<'de> + Eq, M: Deserialize<'de>, G: Deserialize<'de>"
1198 ),
1199 deny_unknown_fields
1200 )]
1201 struct Wire<A, F, M, G> {
1202 artifact_id: A,
1203 artifact_kind: ArtifactKind,
1204 evidence_class: EvidenceClass,
1205 algorithm: AlgorithmDescriptor,
1206 source_frame_ids: Box<[F]>,
1207 analyzed_frame_ids: Box<[F]>,
1208 selected_frame_ids: Box<[F]>,
1209 storyboard_selection: Option<Box<StoryboardSelection<F>>>,
1210 source_frame_count: u64,
1211 analyzed_frame_count: u64,
1212 omitted_frame_count: u64,
1213 range: TimeRange,
1214 markers: Box<[Marker<M>]>,
1215 gaps: Box<[DeclaredGap<G>]>,
1216 region: Option<FrameRegion>,
1217 mask: Option<Box<BinaryMask>>,
1218 normalization: Box<[NormalizationStep]>,
1219 parameters: Parameters,
1220 output_dimensions: PixelDimensions,
1221 output_hash: OutputHash,
1222 }
1223 let wire = Wire::deserialize(deserializer)?;
1224 let manifest = Self {
1225 artifact_id: wire.artifact_id,
1226 artifact_kind: wire.artifact_kind,
1227 evidence_class: wire.evidence_class,
1228 algorithm: Box::new(wire.algorithm),
1229 source_frame_ids: wire.source_frame_ids,
1230 analyzed_frame_ids: wire.analyzed_frame_ids,
1231 selected_frame_ids: wire.selected_frame_ids,
1232 storyboard_selection: wire.storyboard_selection,
1233 source_frame_count: wire.source_frame_count,
1234 analyzed_frame_count: wire.analyzed_frame_count,
1235 omitted_frame_count: wire.omitted_frame_count,
1236 range: wire.range,
1237 markers: wire.markers,
1238 gaps: wire.gaps,
1239 region: wire.region,
1240 mask: wire.mask,
1241 normalization: wire.normalization,
1242 parameters: wire.parameters,
1243 output_dimensions: wire.output_dimensions,
1244 output_hash: wire.output_hash,
1245 };
1246 manifest.validate().map_err(serde::de::Error::custom)?;
1247 Ok(manifest)
1248 }
1249}
1250
1251fn validate_unique<T: Eq>(values: &[T], message: &'static str) -> Result<()> {
1252 for (index, value) in values.iter().enumerate() {
1253 if values[..index].contains(value) {
1254 return Err(VisionError::at(ErrorCode::InvalidManifest, message, index));
1255 }
1256 }
1257 Ok(())
1258}
1259
1260fn validate_ordered_subsequence<F: Eq>(
1261 source: &[F],
1262 subset: &[F],
1263 unique_message: &'static str,
1264 subsequence_message: &'static str,
1265) -> Result<()> {
1266 validate_unique(subset, unique_message)?;
1267 let mut source_index = 0;
1268 for (index, subset_id) in subset.iter().enumerate() {
1269 let Some(offset) = source[source_index..]
1270 .iter()
1271 .position(|source_id| source_id == subset_id)
1272 else {
1273 return Err(VisionError::at(
1274 ErrorCode::InvalidManifest,
1275 subsequence_message,
1276 index,
1277 ));
1278 };
1279 source_index += offset + 1;
1280 }
1281 Ok(())
1282}
1283
1284fn as_manifest_error(error: VisionError) -> VisionError {
1285 VisionError {
1286 code: ErrorCode::InvalidManifest,
1287 message: error.message,
1288 index: error.index,
1289 }
1290}
1291
1292#[cfg(test)]
1293mod tests {
1294 use super::*;
1295
1296 #[test]
1297 fn registries_have_one_stable_wire_table() {
1298 fn check<T>(values: &[T], name: impl Fn(T) -> &'static str)
1299 where
1300 T: Copy + fmt::Display + Serialize + for<'de> Deserialize<'de> + Eq + fmt::Debug,
1301 {
1302 for value in values {
1303 let json = serde_json::to_string(value).unwrap();
1304 assert_eq!(json, format!("\"{}\"", name(*value)));
1305 assert_eq!(serde_json::from_str::<T>(&json).unwrap(), *value);
1306 assert_eq!(value.to_string(), name(*value));
1307 }
1308 }
1309 check(ArtifactKind::ALL, ArtifactKind::as_str);
1310 check(EvidenceClass::ALL, EvidenceClass::as_str);
1311 check(NormalizationKind::ALL, NormalizationKind::as_str);
1312 }
1313
1314 #[test]
1315 fn parameters_are_finite_canonical_and_recursive() {
1316 assert!(FiniteNumber::new(f64::NAN).is_err());
1317 assert_eq!(
1318 FiniteNumber::new(-0.0).unwrap().get().to_bits(),
1319 0.0_f64.to_bits()
1320 );
1321 assert!(
1322 serde_json::from_str::<ParameterValue>(
1323 r#"{"type":"object","value":{"":{"type":"bool","value":true}}}"#
1324 )
1325 .is_err()
1326 );
1327 }
1328
1329 #[test]
1330 fn output_hash_requires_canonical_sha256_hex() {
1331 let hash = OutputHash::from_bytes([0xab; 32]);
1332 let encoded = hash.to_string();
1333 assert_eq!(encoded.len(), 64);
1334 assert_eq!(encoded.parse::<OutputHash>().unwrap(), hash);
1335 assert!(encoded.to_uppercase().parse::<OutputHash>().is_err());
1336 assert!("ab".parse::<OutputHash>().is_err());
1337 }
1338}