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 #[serde(skip)]
221 source_frame_ids: Box<[FrameId]>,
222 #[serde(skip)]
223 source_indices: Option<Box<[usize]>>,
224 #[serde(skip)]
225 source_range: Option<TimeRange>,
226}
227
228pub type OwnedFrameSequence<F, M, G> = FrameSequence<F, M, G, Box<[u8]>>;
229pub type BorrowedFrameSequence<'a, F, M, G> = FrameSequence<F, M, G, &'a [u8]>;
230
231impl<F: Eq, M: Eq, G: Eq, P: AsRef<[u8]>> FrameSequence<F, M, G, P> {
232 pub fn new(
233 frames: Vec<Frame<F, P>>,
234 markers: Vec<Marker<M>>,
235 gaps: Vec<DeclaredGap<G>>,
236 region: Option<FrameRegion>,
237 mask: Option<BinaryMask>,
238 ) -> Result<Self>
239 where
240 F: Clone,
241 {
242 let Some(first) = frames.first() else {
243 return Err(VisionError::new(
244 ErrorCode::EmptySequence,
245 "frame sequence must not be empty",
246 ));
247 };
248 let dimensions = first.dimensions();
249 let pixel_format = first.pixel_format();
250 for (index, frame) in frames.iter().enumerate() {
251 if frames[..index].iter().any(|prior| prior.id() == frame.id()) {
252 return Err(VisionError::at(
253 ErrorCode::DuplicateIdentifier,
254 "frame identifiers must be unique",
255 index,
256 ));
257 }
258 if index > 0 && frames[index - 1].timestamp() > frame.timestamp() {
259 return Err(VisionError::at(
260 ErrorCode::OutOfOrder,
261 "frame timestamps must be nondecreasing",
262 index,
263 ));
264 }
265 if frame.dimensions() != dimensions || frame.pixel_format() != pixel_format {
266 return Err(VisionError::at(
267 ErrorCode::IncompatibleFrame,
268 "all frames must use common dimensions and pixel format",
269 index,
270 ));
271 }
272 }
273
274 let range = TimeRange::new(first.timestamp(), frames.last().unwrap().timestamp())?;
275 validate_markers(&markers, range)?;
276 validate_gaps(&gaps, range)?;
277
278 if region.is_some_and(|value| !value.rect().fits_within(dimensions)) {
279 return Err(VisionError::new(
280 ErrorCode::InvalidRegion,
281 "sequence region does not fit its frame dimensions",
282 ));
283 }
284 if mask
285 .as_ref()
286 .is_some_and(|value| value.dimensions() != dimensions)
287 {
288 return Err(VisionError::new(
289 ErrorCode::InvalidMask,
290 "sequence mask dimensions do not match its frames",
291 ));
292 }
293
294 let source_frame_ids = frames.iter().map(|frame| frame.id().clone()).collect();
295 Ok(Self {
296 frames: frames.into_boxed_slice(),
297 markers: markers.into_boxed_slice(),
298 gaps: gaps.into_boxed_slice(),
299 region,
300 mask,
301 source_frame_ids,
302 source_indices: None,
303 source_range: None,
304 })
305 }
306
307 pub fn with_source_provenance(
311 mut self,
312 source_frame_ids: Vec<F>,
313 source_indices: Vec<usize>,
314 source_range: TimeRange,
315 ) -> Result<Self> {
316 if source_frame_ids.len() < self.frames.len()
317 || source_indices.len() != self.frames.len()
318 || source_indices.windows(2).any(|pair| pair[0] >= pair[1])
319 || self
320 .frames
321 .iter()
322 .zip(&source_indices)
323 .any(|(frame, index)| {
324 *index >= source_frame_ids.len() || source_frame_ids[*index] != *frame.id()
325 })
326 || source_frame_ids.windows(2).any(|pair| pair[0] == pair[1])
327 || !source_range.contains(self.frames[0].timestamp())
328 || !source_range.contains(self.frames[self.frames.len() - 1].timestamp())
329 {
330 return Err(VisionError::new(
331 ErrorCode::InvalidParameter,
332 "source provenance does not match the bounded frame sequence",
333 ));
334 }
335 self.source_frame_ids = source_frame_ids.into_boxed_slice();
336 self.source_indices = Some(source_indices.into_boxed_slice());
337 self.source_range = Some(source_range);
338 Ok(self)
339 }
340
341 pub fn frames(&self) -> &[Frame<F, P>] {
342 &self.frames
343 }
344
345 pub fn markers(&self) -> &[Marker<M>] {
346 &self.markers
347 }
348
349 pub fn gaps(&self) -> &[DeclaredGap<G>] {
350 &self.gaps
351 }
352
353 pub const fn region(&self) -> Option<FrameRegion> {
354 self.region
355 }
356
357 pub fn mask(&self) -> Option<&BinaryMask> {
358 self.mask.as_ref()
359 }
360
361 pub fn source_frame_ids(&self) -> &[F] {
362 &self.source_frame_ids
363 }
364
365 pub fn source_indices(&self) -> Option<&[usize]> {
366 self.source_indices.as_deref()
367 }
368
369 pub fn source_frame_count(&self) -> usize {
370 self.source_frame_ids.len()
371 }
372
373 pub fn range(&self) -> TimeRange {
374 self.source_range.unwrap_or(TimeRange {
375 start: self.frames[0].timestamp(),
376 end: self.frames[self.frames.len() - 1].timestamp(),
377 })
378 }
379
380 pub fn dimensions(&self) -> PixelDimensions {
381 self.frames[0].dimensions()
382 }
383
384 pub fn pixel_format(&self) -> PixelFormat {
385 self.frames[0].pixel_format()
386 }
387
388 pub fn frame_by_id(&self, id: &F) -> Option<&Frame<F, P>> {
389 self.frames.iter().find(|frame| frame.id() == id)
390 }
391}
392
393impl<F: Clone + Eq, M: Clone + Eq, G: Clone + Eq, P: AsRef<[u8]>> FrameSequence<F, M, G, P> {
394 pub fn to_owned(&self) -> OwnedFrameSequence<F, M, G> {
395 FrameSequence {
396 frames: self
397 .frames
398 .iter()
399 .map(Frame::to_owned)
400 .collect::<Vec<_>>()
401 .into_boxed_slice(),
402 markers: self.markers.clone(),
403 gaps: self.gaps.clone(),
404 region: self.region,
405 mask: self.mask.clone(),
406 source_frame_ids: self.source_frame_ids.clone(),
407 source_indices: self.source_indices.clone(),
408 source_range: self.source_range,
409 }
410 }
411}
412
413impl<'de, F, M, G, P> Deserialize<'de> for FrameSequence<F, M, G, P>
414where
415 F: Deserialize<'de> + Clone + Eq,
416 M: Deserialize<'de> + Eq,
417 G: Deserialize<'de> + Eq,
418 P: Deserialize<'de> + AsRef<[u8]>,
419{
420 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
421 where
422 D: Deserializer<'de>,
423 {
424 #[derive(Deserialize)]
425 #[serde(bound(
426 deserialize = "F: Deserialize<'de>, M: Deserialize<'de>, G: Deserialize<'de>, P: Deserialize<'de> + AsRef<[u8]>"
427 ))]
428 struct Wire<F, M, G, P> {
429 frames: Vec<Frame<F, P>>,
430 markers: Vec<Marker<M>>,
431 gaps: Vec<DeclaredGap<G>>,
432 region: Option<FrameRegion>,
433 mask: Option<BinaryMask>,
434 }
435 let wire = Wire::deserialize(deserializer)?;
436 Self::new(wire.frames, wire.markers, wire.gaps, wire.region, wire.mask)
437 .map_err(serde::de::Error::custom)
438 }
439}
440
441pub(crate) fn validate_markers<M: Eq>(markers: &[Marker<M>], range: TimeRange) -> Result<()> {
442 for (index, marker) in markers.iter().enumerate() {
443 if markers[..index]
444 .iter()
445 .any(|prior| prior.id() == marker.id())
446 {
447 return Err(VisionError::at(
448 ErrorCode::DuplicateIdentifier,
449 "marker identifiers must be unique",
450 index,
451 ));
452 }
453 if index > 0 && markers[index - 1].timestamp() > marker.timestamp() {
454 return Err(VisionError::at(
455 ErrorCode::OutOfOrder,
456 "marker timestamps must be nondecreasing",
457 index,
458 ));
459 }
460 if !range.contains(marker.timestamp()) {
461 return Err(VisionError::at(
462 ErrorCode::AnnotationOutOfRange,
463 "marker timestamp lies outside the frame range",
464 index,
465 ));
466 }
467 }
468 Ok(())
469}
470
471pub(crate) fn validate_gaps<G: Eq>(gaps: &[DeclaredGap<G>], range: TimeRange) -> Result<()> {
472 for (index, gap) in gaps.iter().enumerate() {
473 if gaps[..index].iter().any(|prior| prior.id() == gap.id()) {
474 return Err(VisionError::at(
475 ErrorCode::DuplicateIdentifier,
476 "gap identifiers must be unique",
477 index,
478 ));
479 }
480 if index > 0 {
481 let prior = gaps[index - 1].range();
482 if prior.start() > gap.range().start() {
483 return Err(VisionError::at(
484 ErrorCode::OutOfOrder,
485 "gap ranges must be ordered by start time",
486 index,
487 ));
488 }
489 if prior.end() > gap.range().start() {
490 return Err(VisionError::at(
491 ErrorCode::OutOfOrder,
492 "gap ranges must not overlap",
493 index,
494 ));
495 }
496 }
497 if !range.contains(gap.range().start()) || !range.contains(gap.range().end()) {
498 return Err(VisionError::at(
499 ErrorCode::AnnotationOutOfRange,
500 "gap range lies outside the frame range",
501 index,
502 ));
503 }
504 }
505 Ok(())
506}
507
508#[cfg(test)]
509mod tests {
510 use super::*;
511 use crate::{PixelFormat, PixelRect};
512
513 fn frame(id: u8, timestamp: u64) -> Frame<u8, Box<[u8]>> {
514 Frame::new(
515 id,
516 Timestamp::from_nanos(timestamp),
517 PixelDimensions::new(1, 1).unwrap(),
518 PixelFormat::Rgba8SrgbStraight,
519 vec![0, 0, 0, 255].into_boxed_slice(),
520 )
521 .unwrap()
522 }
523
524 #[test]
525 fn preserves_ties_and_rejects_ambiguous_sequence_order() {
526 let tied = FrameSequence::new(
527 vec![frame(2, 1), frame(1, 1)],
528 vec![
529 Marker::new(2, Timestamp::from_nanos(1), "a", "first").unwrap(),
530 Marker::new(1, Timestamp::from_nanos(1), "b", "second").unwrap(),
531 ],
532 Vec::<DeclaredGap<u8>>::new(),
533 None,
534 None,
535 )
536 .unwrap();
537 assert_eq!(tied.frames()[0].id(), &2);
538 assert_eq!(tied.markers()[0].id(), &2);
539 assert_eq!(
540 FrameSequence::new(
541 vec![frame(1, 2), frame(2, 1)],
542 Vec::<Marker<u8>>::new(),
543 Vec::<DeclaredGap<u8>>::new(),
544 None,
545 None,
546 )
547 .unwrap_err()
548 .code,
549 ErrorCode::OutOfOrder
550 );
551 assert_eq!(
552 FrameSequence::new(
553 vec![frame(1, 1), frame(1, 2)],
554 Vec::<Marker<u8>>::new(),
555 Vec::<DeclaredGap<u8>>::new(),
556 None,
557 None,
558 )
559 .unwrap_err()
560 .code,
561 ErrorCode::DuplicateIdentifier
562 );
563 }
564
565 #[test]
566 fn validates_annotations_gaps_and_sequence_geometry() {
567 let frames = vec![frame(1, 1), frame(2, 3)];
568 let gaps = vec![
569 DeclaredGap::new(
570 1,
571 TimeRange::new(Timestamp::from_nanos(1), Timestamp::from_nanos(2)).unwrap(),
572 "loss",
573 None,
574 )
575 .unwrap(),
576 DeclaredGap::new(
577 2,
578 TimeRange::new(Timestamp::from_nanos(2), Timestamp::from_nanos(3)).unwrap(),
579 "loss",
580 None,
581 )
582 .unwrap(),
583 ];
584 assert!(FrameSequence::new(frames, Vec::<Marker<u8>>::new(), gaps, None, None).is_ok());
585
586 let wrong_region = FrameRegion::new(
587 PixelRect::new(0, 0, 2, 1).unwrap(),
588 PixelDimensions::new(2, 1).unwrap(),
589 )
590 .unwrap();
591 assert_eq!(
592 FrameSequence::new(
593 vec![frame(1, 1)],
594 Vec::<Marker<u8>>::new(),
595 Vec::<DeclaredGap<u8>>::new(),
596 Some(wrong_region),
597 None,
598 )
599 .unwrap_err()
600 .code,
601 ErrorCode::InvalidRegion
602 );
603 }
604}