1use std::num::NonZeroU64;
2
3use serde::{Deserialize, Deserializer, Serialize};
4
5use crate::{
6 BinaryMask, ErrorCode, Frame, FrameRegion, PixelDimensions, PixelFormat, Result, Timestamp,
7 VisionError,
8};
9
10#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
12pub struct TimeRange {
13 start: Timestamp,
14 end: Timestamp,
15}
16
17impl TimeRange {
18 pub fn new(start: Timestamp, end: Timestamp) -> Result<Self> {
19 if start > end {
20 return Err(VisionError::new(
21 ErrorCode::OutOfOrder,
22 "time range start must not follow its end",
23 ));
24 }
25 Ok(Self { start, end })
26 }
27
28 pub const fn start(self) -> Timestamp {
29 self.start
30 }
31
32 pub const fn end(self) -> Timestamp {
33 self.end
34 }
35
36 pub const fn contains(self, timestamp: Timestamp) -> bool {
37 self.start.as_nanos() <= timestamp.as_nanos() && timestamp.as_nanos() <= self.end.as_nanos()
38 }
39}
40
41impl<'de> Deserialize<'de> for TimeRange {
42 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
43 where
44 D: Deserializer<'de>,
45 {
46 #[derive(Deserialize)]
47 struct Wire {
48 start: Timestamp,
49 end: Timestamp,
50 }
51 let wire = Wire::deserialize(deserializer)?;
52 Self::new(wire.start, wire.end).map_err(serde::de::Error::custom)
53 }
54}
55
56#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
57#[serde(transparent)]
58pub(crate) struct NonEmptyText(Box<str>);
59
60impl NonEmptyText {
61 pub(crate) fn new(
62 value: impl Into<String>,
63 code: ErrorCode,
64 message: &'static str,
65 ) -> Result<Self> {
66 let value = value.into();
67 if value.is_empty() {
68 return Err(VisionError::new(code, message));
69 }
70 Ok(Self(value.into_boxed_str()))
71 }
72
73 pub(crate) fn as_str(&self) -> &str {
74 &self.0
75 }
76}
77
78#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
80pub struct Marker<Id> {
81 id: Id,
82 timestamp: Timestamp,
83 kind: NonEmptyText,
84 label: NonEmptyText,
85}
86
87impl<Id> Marker<Id> {
88 pub fn new(
89 id: Id,
90 timestamp: Timestamp,
91 kind: impl Into<String>,
92 label: impl Into<String>,
93 ) -> Result<Self> {
94 Ok(Self {
95 id,
96 timestamp,
97 kind: NonEmptyText::new(
98 kind,
99 ErrorCode::InvalidParameter,
100 "marker kind must not be empty",
101 )?,
102 label: NonEmptyText::new(
103 label,
104 ErrorCode::InvalidParameter,
105 "marker label must not be empty",
106 )?,
107 })
108 }
109
110 pub fn id(&self) -> &Id {
111 &self.id
112 }
113
114 pub const fn timestamp(&self) -> Timestamp {
115 self.timestamp
116 }
117
118 pub fn kind(&self) -> &str {
119 self.kind.as_str()
120 }
121
122 pub fn label(&self) -> &str {
123 self.label.as_str()
124 }
125}
126
127impl<'de, Id: Deserialize<'de>> Deserialize<'de> for Marker<Id> {
128 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
129 where
130 D: Deserializer<'de>,
131 {
132 #[derive(Deserialize)]
133 struct Wire<Id> {
134 id: Id,
135 timestamp: Timestamp,
136 kind: String,
137 label: String,
138 }
139 let wire = Wire::deserialize(deserializer)?;
140 Self::new(wire.id, wire.timestamp, wire.kind, wire.label).map_err(serde::de::Error::custom)
141 }
142}
143
144#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
146pub struct DeclaredGap<Id> {
147 id: Id,
148 range: TimeRange,
149 reason: NonEmptyText,
150 estimated_missing_frames: Option<NonZeroU64>,
151}
152
153impl<Id> DeclaredGap<Id> {
154 pub fn new(
155 id: Id,
156 range: TimeRange,
157 reason: impl Into<String>,
158 estimated_missing_frames: Option<NonZeroU64>,
159 ) -> Result<Self> {
160 Ok(Self {
161 id,
162 range,
163 reason: NonEmptyText::new(
164 reason,
165 ErrorCode::InvalidParameter,
166 "gap reason must not be empty",
167 )?,
168 estimated_missing_frames,
169 })
170 }
171
172 pub fn id(&self) -> &Id {
173 &self.id
174 }
175
176 pub const fn range(&self) -> TimeRange {
177 self.range
178 }
179
180 pub fn reason(&self) -> &str {
181 self.reason.as_str()
182 }
183
184 pub const fn estimated_missing_frames(&self) -> Option<NonZeroU64> {
185 self.estimated_missing_frames
186 }
187}
188
189impl<'de, Id: Deserialize<'de>> Deserialize<'de> for DeclaredGap<Id> {
190 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
191 where
192 D: Deserializer<'de>,
193 {
194 #[derive(Deserialize)]
195 struct Wire<Id> {
196 id: Id,
197 range: TimeRange,
198 reason: String,
199 estimated_missing_frames: Option<NonZeroU64>,
200 }
201 let wire = Wire::deserialize(deserializer)?;
202 Self::new(
203 wire.id,
204 wire.range,
205 wire.reason,
206 wire.estimated_missing_frames,
207 )
208 .map_err(serde::de::Error::custom)
209 }
210}
211
212#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
214pub struct FrameSequence<FrameId, MarkerId, GapId, Pixels> {
215 frames: Box<[Frame<FrameId, Pixels>]>,
216 markers: Box<[Marker<MarkerId>]>,
217 gaps: Box<[DeclaredGap<GapId>]>,
218 region: Option<FrameRegion>,
219 mask: Option<BinaryMask>,
220 source_frame_ids: Box<[FrameId]>,
223 source_indices: Option<Box<[usize]>>,
226 source_range: Option<TimeRange>,
229}
230
231pub type OwnedFrameSequence<F, M, G> = FrameSequence<F, M, G, Box<[u8]>>;
232pub type BorrowedFrameSequence<'a, F, M, G> = FrameSequence<F, M, G, &'a [u8]>;
233
234#[derive(Clone, Debug)]
243pub struct SourceProvenance<F> {
244 pub frame_ids: Vec<F>,
249 pub indices: Option<Vec<usize>>,
252 pub range: Option<TimeRange>,
255}
256
257impl<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>> FrameSequence<F, M, G, P> {
258 pub fn new(
259 frames: Vec<Frame<F, P>>,
260 markers: Vec<Marker<M>>,
261 gaps: Vec<DeclaredGap<G>>,
262 region: Option<FrameRegion>,
263 mask: Option<BinaryMask>,
264 ) -> Result<Self>
265 where
266 F: Clone,
267 {
268 let source_frame_ids = frames.iter().map(|frame| frame.id().clone()).collect();
269 Self::assemble(
270 frames,
271 markers,
272 gaps,
273 region,
274 mask,
275 SourceProvenance {
276 frame_ids: source_frame_ids,
277 indices: None,
278 range: None,
279 },
280 )
281 }
282
283 pub fn with_provenance(
294 frames: Vec<Frame<F, P>>,
295 markers: Vec<Marker<M>>,
296 gaps: Vec<DeclaredGap<G>>,
297 region: Option<FrameRegion>,
298 mask: Option<BinaryMask>,
299 provenance: SourceProvenance<F>,
300 ) -> Result<Self> {
301 Self::assemble(frames, markers, gaps, region, mask, provenance)
302 }
303
304 fn assemble(
315 frames: Vec<Frame<F, P>>,
316 markers: Vec<Marker<M>>,
317 gaps: Vec<DeclaredGap<G>>,
318 region: Option<FrameRegion>,
319 mask: Option<BinaryMask>,
320 provenance: SourceProvenance<F>,
321 ) -> Result<Self> {
322 let Some(first) = frames.first() else {
323 return Err(VisionError::new(
324 ErrorCode::EmptySequence,
325 "frame sequence must not be empty",
326 ));
327 };
328 let dimensions = first.dimensions();
329 let pixel_format = first.pixel_format();
330 for (index, frame) in frames.iter().enumerate() {
331 if frames[..index].iter().any(|prior| prior.id() == frame.id()) {
332 return Err(VisionError::at(
333 ErrorCode::DuplicateIdentifier,
334 "frame identifiers must be unique",
335 index,
336 ));
337 }
338 if index > 0 && frames[index - 1].timestamp() > frame.timestamp() {
339 return Err(VisionError::at(
340 ErrorCode::OutOfOrder,
341 "frame timestamps must be nondecreasing",
342 index,
343 ));
344 }
345 if frame.dimensions() != dimensions || frame.pixel_format() != pixel_format {
346 return Err(VisionError::at(
347 ErrorCode::IncompatibleFrame,
348 "all frames must use common dimensions and pixel format",
349 index,
350 ));
351 }
352 }
353
354 let decoded_range = TimeRange::new(first.timestamp(), frames.last().unwrap().timestamp())?;
355 validate_source_provenance(
356 &frames,
357 &provenance.frame_ids,
358 provenance.indices.as_deref(),
359 provenance.range,
360 )?;
361 let effective_range = provenance.range.unwrap_or(decoded_range);
362 validate_markers(&markers, effective_range)?;
363 validate_gaps(&gaps, effective_range)?;
364
365 if region.is_some_and(|value| !value.rect().fits_within(dimensions)) {
366 return Err(VisionError::new(
367 ErrorCode::InvalidRegion,
368 "sequence region does not fit its frame dimensions",
369 ));
370 }
371 if mask
372 .as_ref()
373 .is_some_and(|value| value.dimensions() != dimensions)
374 {
375 return Err(VisionError::new(
376 ErrorCode::InvalidMask,
377 "sequence mask dimensions do not match its frames",
378 ));
379 }
380
381 Ok(Self {
382 frames: frames.into_boxed_slice(),
383 markers: markers.into_boxed_slice(),
384 gaps: gaps.into_boxed_slice(),
385 region,
386 mask,
387 source_frame_ids: provenance.frame_ids.into_boxed_slice(),
388 source_indices: provenance.indices.map(Vec::into_boxed_slice),
389 source_range: provenance.range,
390 })
391 }
392
393 pub fn with_source_provenance(
402 mut self,
403 source_frame_ids: Vec<F>,
404 source_indices: Vec<usize>,
405 source_range: TimeRange,
406 ) -> Result<Self> {
407 validate_source_provenance(
408 &self.frames,
409 &source_frame_ids,
410 Some(&source_indices),
411 Some(source_range),
412 )?;
413 validate_markers(&self.markers, source_range)?;
414 validate_gaps(&self.gaps, source_range)?;
415 self.source_frame_ids = source_frame_ids.into_boxed_slice();
416 self.source_indices = Some(source_indices.into_boxed_slice());
417 self.source_range = Some(source_range);
418 Ok(self)
419 }
420
421 pub fn frames(&self) -> &[Frame<F, P>] {
422 &self.frames
423 }
424
425 pub fn markers(&self) -> &[Marker<M>] {
426 &self.markers
427 }
428
429 pub fn gaps(&self) -> &[DeclaredGap<G>] {
430 &self.gaps
431 }
432
433 pub const fn region(&self) -> Option<FrameRegion> {
434 self.region
435 }
436
437 pub fn mask(&self) -> Option<&BinaryMask> {
438 self.mask.as_ref()
439 }
440
441 pub fn source_frame_ids(&self) -> &[F] {
442 &self.source_frame_ids
443 }
444
445 pub fn source_indices(&self) -> Option<&[usize]> {
446 self.source_indices.as_deref()
447 }
448
449 pub fn source_frame_count(&self) -> usize {
450 self.source_frame_ids.len()
451 }
452
453 pub fn range(&self) -> TimeRange {
454 self.source_range.unwrap_or(TimeRange {
455 start: self.frames[0].timestamp(),
456 end: self.frames[self.frames.len() - 1].timestamp(),
457 })
458 }
459
460 pub fn dimensions(&self) -> PixelDimensions {
461 self.frames[0].dimensions()
462 }
463
464 pub fn pixel_format(&self) -> PixelFormat {
465 self.frames[0].pixel_format()
466 }
467
468 pub fn frame_by_id(&self, id: &F) -> Option<&Frame<F, P>> {
469 self.frames.iter().find(|frame| frame.id() == id)
470 }
471}
472
473impl<F: Clone + Eq, M: Clone + Eq, G: Clone + Eq, P: AsRef<[u8]>> FrameSequence<F, M, G, P> {
474 pub fn to_owned(&self) -> OwnedFrameSequence<F, M, G> {
475 FrameSequence {
476 frames: self
477 .frames
478 .iter()
479 .map(Frame::to_owned)
480 .collect::<Vec<_>>()
481 .into_boxed_slice(),
482 markers: self.markers.clone(),
483 gaps: self.gaps.clone(),
484 region: self.region,
485 mask: self.mask.clone(),
486 source_frame_ids: self.source_frame_ids.clone(),
487 source_indices: self.source_indices.clone(),
488 source_range: self.source_range,
489 }
490 }
491}
492
493impl<'de, F, M, G, P> Deserialize<'de> for FrameSequence<F, M, G, P>
494where
495 F: Deserialize<'de> + Eq,
496 M: Deserialize<'de> + Eq,
497 G: Deserialize<'de> + Eq,
498 P: Deserialize<'de> + AsRef<[u8]>,
499{
500 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
501 where
502 D: Deserializer<'de>,
503 {
504 #[derive(Deserialize)]
511 #[serde(
512 bound(
513 deserialize = "F: Deserialize<'de>, M: Deserialize<'de>, G: Deserialize<'de>, P: Deserialize<'de> + AsRef<[u8]>"
514 ),
515 deny_unknown_fields
516 )]
517 struct Wire<F, M, G, P> {
518 frames: Vec<Frame<F, P>>,
519 markers: Vec<Marker<M>>,
520 gaps: Vec<DeclaredGap<G>>,
521 region: Option<FrameRegion>,
522 mask: Option<BinaryMask>,
523 source_frame_ids: Vec<F>,
524 source_indices: Option<Vec<usize>>,
525 source_range: Option<TimeRange>,
526 }
527 let wire = Wire::deserialize(deserializer)?;
528 Self::assemble(
529 wire.frames,
530 wire.markers,
531 wire.gaps,
532 wire.region,
533 wire.mask,
534 SourceProvenance {
535 frame_ids: wire.source_frame_ids,
536 indices: wire.source_indices,
537 range: wire.source_range,
538 },
539 )
540 .map_err(serde::de::Error::custom)
541 }
542}
543
544fn validate_source_provenance<F: Eq, P: AsRef<[u8]>>(
558 frames: &[Frame<F, P>],
559 source_frame_ids: &[F],
560 source_indices: Option<&[usize]>,
561 source_range: Option<TimeRange>,
562) -> Result<()> {
563 let (Some(indices), Some(source_range)) = (source_indices, source_range) else {
564 if source_indices.is_none() && source_range.is_none() {
565 if source_frame_ids.len() != frames.len()
566 || source_frame_ids.iter().ne(frames.iter().map(Frame::id))
567 {
568 return Err(VisionError::new(
569 ErrorCode::InvalidParameter,
570 "a sequence without source indices must retain every decoded frame as its complete source",
571 ));
572 }
573 return Ok(());
574 }
575 return Err(VisionError::new(
576 ErrorCode::InvalidParameter,
577 "source indices and source range must be declared together",
578 ));
579 };
580 if indices.len() != frames.len() {
581 return Err(VisionError::new(
582 ErrorCode::InvalidParameter,
583 "source indices must identify every decoded frame",
584 ));
585 }
586 for (position, id) in source_frame_ids.iter().enumerate() {
589 if source_frame_ids[..position].contains(id) {
590 return Err(VisionError::at(
591 ErrorCode::DuplicateIdentifier,
592 "source frame identifiers must be unique",
593 position,
594 ));
595 }
596 }
597 for (position, &index) in indices.iter().enumerate() {
600 if position > 0 && indices[position - 1] >= index {
601 return Err(VisionError::at(
602 ErrorCode::OutOfOrder,
603 "source indices must be strictly increasing",
604 position,
605 ));
606 }
607 }
608 for (position, (&index, frame)) in indices.iter().zip(frames).enumerate() {
609 if index >= source_frame_ids.len() {
610 return Err(VisionError::at(
611 ErrorCode::InvalidParameter,
612 "source index lies outside the retained source frames",
613 position,
614 ));
615 }
616 if &source_frame_ids[index] != frame.id() {
617 return Err(VisionError::at(
618 ErrorCode::InvalidParameter,
619 "decoded frame does not match its declared source frame",
620 position,
621 ));
622 }
623 }
624 let contains = |frame: &Frame<F, P>| source_range.contains(frame.timestamp());
625 if !frames.first().is_some_and(contains) || !frames.last().is_some_and(contains) {
626 return Err(VisionError::new(
627 ErrorCode::InvalidParameter,
628 "the declared source range must contain the decoded frame range",
629 ));
630 }
631 Ok(())
632}
633
634pub(crate) fn validate_markers<M: Eq>(markers: &[Marker<M>], range: TimeRange) -> Result<()> {
635 for (index, marker) in markers.iter().enumerate() {
636 if markers[..index]
637 .iter()
638 .any(|prior| prior.id() == marker.id())
639 {
640 return Err(VisionError::at(
641 ErrorCode::DuplicateIdentifier,
642 "marker identifiers must be unique",
643 index,
644 ));
645 }
646 if index > 0 && markers[index - 1].timestamp() > marker.timestamp() {
647 return Err(VisionError::at(
648 ErrorCode::OutOfOrder,
649 "marker timestamps must be nondecreasing",
650 index,
651 ));
652 }
653 if !range.contains(marker.timestamp()) {
654 return Err(VisionError::at(
655 ErrorCode::AnnotationOutOfRange,
656 "marker timestamp lies outside the frame range",
657 index,
658 ));
659 }
660 }
661 Ok(())
662}
663
664pub(crate) fn validate_gaps<G: Eq>(gaps: &[DeclaredGap<G>], range: TimeRange) -> Result<()> {
665 for (index, gap) in gaps.iter().enumerate() {
666 if gaps[..index].iter().any(|prior| prior.id() == gap.id()) {
667 return Err(VisionError::at(
668 ErrorCode::DuplicateIdentifier,
669 "gap identifiers must be unique",
670 index,
671 ));
672 }
673 if index > 0 {
674 let prior = gaps[index - 1].range();
675 if prior.start() > gap.range().start() {
676 return Err(VisionError::at(
677 ErrorCode::OutOfOrder,
678 "gap ranges must be ordered by start time",
679 index,
680 ));
681 }
682 if prior.end() > gap.range().start() {
683 return Err(VisionError::at(
684 ErrorCode::OutOfOrder,
685 "gap ranges must not overlap",
686 index,
687 ));
688 }
689 }
690 if !range.contains(gap.range().start()) || !range.contains(gap.range().end()) {
691 return Err(VisionError::at(
692 ErrorCode::AnnotationOutOfRange,
693 "gap range lies outside the frame range",
694 index,
695 ));
696 }
697 }
698 Ok(())
699}
700
701#[cfg(test)]
702mod tests {
703 use super::*;
704 use crate::{PixelFormat, PixelRect};
705
706 fn frame(id: u8, timestamp: u64) -> Frame<u8, Box<[u8]>> {
707 Frame::new(
708 id,
709 Timestamp::from_nanos(timestamp),
710 PixelDimensions::new(1, 1).unwrap(),
711 PixelFormat::Rgba8SrgbStraight,
712 vec![0, 0, 0, 255].into_boxed_slice(),
713 )
714 .unwrap()
715 }
716
717 #[test]
718 fn preserves_ties_and_rejects_ambiguous_sequence_order() {
719 let tied = FrameSequence::new(
720 vec![frame(2, 1), frame(1, 1)],
721 vec![
722 Marker::new(2, Timestamp::from_nanos(1), "a", "first").unwrap(),
723 Marker::new(1, Timestamp::from_nanos(1), "b", "second").unwrap(),
724 ],
725 Vec::<DeclaredGap<u8>>::new(),
726 None,
727 None,
728 )
729 .unwrap();
730 assert_eq!(tied.frames()[0].id(), &2);
731 assert_eq!(tied.markers()[0].id(), &2);
732 assert_eq!(
733 FrameSequence::new(
734 vec![frame(1, 2), frame(2, 1)],
735 Vec::<Marker<u8>>::new(),
736 Vec::<DeclaredGap<u8>>::new(),
737 None,
738 None,
739 )
740 .unwrap_err()
741 .code,
742 ErrorCode::OutOfOrder
743 );
744 assert_eq!(
745 FrameSequence::new(
746 vec![frame(1, 1), frame(1, 2)],
747 Vec::<Marker<u8>>::new(),
748 Vec::<DeclaredGap<u8>>::new(),
749 None,
750 None,
751 )
752 .unwrap_err()
753 .code,
754 ErrorCode::DuplicateIdentifier
755 );
756 }
757
758 #[test]
759 fn validates_annotations_gaps_and_sequence_geometry() {
760 let frames = vec![frame(1, 1), frame(2, 3)];
761 let gaps = vec![
762 DeclaredGap::new(
763 1,
764 TimeRange::new(Timestamp::from_nanos(1), Timestamp::from_nanos(2)).unwrap(),
765 "loss",
766 None,
767 )
768 .unwrap(),
769 DeclaredGap::new(
770 2,
771 TimeRange::new(Timestamp::from_nanos(2), Timestamp::from_nanos(3)).unwrap(),
772 "loss",
773 None,
774 )
775 .unwrap(),
776 ];
777 assert!(FrameSequence::new(frames, Vec::<Marker<u8>>::new(), gaps, None, None).is_ok());
778
779 let wrong_region = FrameRegion::new(
780 PixelRect::new(0, 0, 2, 1).unwrap(),
781 PixelDimensions::new(2, 1).unwrap(),
782 )
783 .unwrap();
784 assert_eq!(
785 FrameSequence::new(
786 vec![frame(1, 1)],
787 Vec::<Marker<u8>>::new(),
788 Vec::<DeclaredGap<u8>>::new(),
789 Some(wrong_region),
790 None,
791 )
792 .unwrap_err()
793 .code,
794 ErrorCode::InvalidRegion
795 );
796 }
797}