Skip to main content

temporal_vision/
frame.rs

1use serde::{Deserialize, Deserializer, Serialize};
2
3use crate::{ErrorCode, Result, VisionError};
4
5/// Nanoseconds in one caller-declared sequence clock.
6#[derive(
7    Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize, schemars::JsonSchema,
8)]
9#[serde(transparent)]
10pub struct Timestamp(u64);
11
12impl Timestamp {
13    pub const ZERO: Self = Self(0);
14
15    pub const fn from_nanos(value: u64) -> Self {
16        Self(value)
17    }
18
19    pub const fn as_nanos(self) -> u64 {
20        self.0
21    }
22}
23
24/// Non-zero source-frame pixel dimensions.
25#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, schemars::JsonSchema)]
26pub struct PixelDimensions {
27    width: u32,
28    height: u32,
29}
30
31impl PixelDimensions {
32    pub fn new(width: u32, height: u32) -> Result<Self> {
33        if width == 0 || height == 0 {
34            return Err(VisionError::new(
35                ErrorCode::InvalidDimensions,
36                "pixel dimensions must be non-zero",
37            ));
38        }
39        let dimensions = Self { width, height };
40        dimensions.rgba8_byte_len()?;
41        Ok(dimensions)
42    }
43
44    pub const fn width(self) -> u32 {
45        self.width
46    }
47
48    pub const fn height(self) -> u32 {
49        self.height
50    }
51
52    pub fn pixel_count(self) -> Result<usize> {
53        let count = u64::from(self.width)
54            .checked_mul(u64::from(self.height))
55            .ok_or_else(|| {
56                VisionError::new(
57                    ErrorCode::InvalidDimensions,
58                    "pixel dimensions exceed the supported address space",
59                )
60            })?;
61        usize::try_from(count).map_err(|_| {
62            VisionError::new(
63                ErrorCode::InvalidDimensions,
64                "pixel dimensions exceed the supported address space",
65            )
66        })
67    }
68
69    pub fn rgba8_byte_len(self) -> Result<usize> {
70        self.pixel_count()?.checked_mul(4).ok_or_else(|| {
71            VisionError::new(
72                ErrorCode::InvalidDimensions,
73                "RGBA8 payload length exceeds the supported address space",
74            )
75        })
76    }
77}
78
79impl<'de> Deserialize<'de> for PixelDimensions {
80    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
81    where
82        D: Deserializer<'de>,
83    {
84        #[derive(Deserialize)]
85        struct Wire {
86            width: u32,
87            height: u32,
88        }
89        let wire = Wire::deserialize(deserializer)?;
90        Self::new(wire.width, wire.height).map_err(serde::de::Error::custom)
91    }
92}
93
94stable_registry! {
95    /// Decoded pixel representation accepted by this crate.
96    pub enum PixelFormat {
97        Rgba8SrgbStraight => "rgba8_srgb_straight",
98    }
99}
100
101/// A validated decoded frame using caller-owned identity and pixel storage.
102#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
103pub struct Frame<Id, Pixels> {
104    id: Id,
105    timestamp: Timestamp,
106    dimensions: PixelDimensions,
107    pixel_format: PixelFormat,
108    pixels: Pixels,
109}
110
111pub type OwnedFrame<Id> = Frame<Id, Box<[u8]>>;
112pub type BorrowedFrame<'a, Id> = Frame<Id, &'a [u8]>;
113
114impl<Id, Pixels: AsRef<[u8]>> Frame<Id, Pixels> {
115    pub fn new(
116        id: Id,
117        timestamp: Timestamp,
118        dimensions: PixelDimensions,
119        pixel_format: PixelFormat,
120        pixels: Pixels,
121    ) -> Result<Self> {
122        if pixels.as_ref().len() != dimensions.rgba8_byte_len()? {
123            return Err(VisionError::new(
124                ErrorCode::PixelLengthMismatch,
125                "pixel payload length does not match frame dimensions and format",
126            ));
127        }
128        Ok(Self {
129            id,
130            timestamp,
131            dimensions,
132            pixel_format,
133            pixels,
134        })
135    }
136
137    pub fn id(&self) -> &Id {
138        &self.id
139    }
140
141    pub const fn timestamp(&self) -> Timestamp {
142        self.timestamp
143    }
144
145    pub const fn dimensions(&self) -> PixelDimensions {
146        self.dimensions
147    }
148
149    pub const fn pixel_format(&self) -> PixelFormat {
150        self.pixel_format
151    }
152
153    pub fn pixels(&self) -> &[u8] {
154        self.pixels.as_ref()
155    }
156
157    pub fn as_borrowed(&self) -> BorrowedFrame<'_, &Id> {
158        // The source frame already passed the same payload validation.
159        Frame {
160            id: &self.id,
161            timestamp: self.timestamp,
162            dimensions: self.dimensions,
163            pixel_format: self.pixel_format,
164            pixels: self.pixels.as_ref(),
165        }
166    }
167
168    pub fn into_parts(self) -> (Id, Timestamp, PixelDimensions, PixelFormat, Pixels) {
169        (
170            self.id,
171            self.timestamp,
172            self.dimensions,
173            self.pixel_format,
174            self.pixels,
175        )
176    }
177}
178
179impl<Id: Clone, Pixels: AsRef<[u8]>> Frame<Id, Pixels> {
180    pub fn to_owned(&self) -> OwnedFrame<Id> {
181        Frame {
182            id: self.id.clone(),
183            timestamp: self.timestamp,
184            dimensions: self.dimensions,
185            pixel_format: self.pixel_format,
186            pixels: self.pixels.as_ref().into(),
187        }
188    }
189}
190
191impl<'de, Id, Pixels> Deserialize<'de> for Frame<Id, Pixels>
192where
193    Id: Deserialize<'de>,
194    Pixels: Deserialize<'de> + AsRef<[u8]>,
195{
196    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
197    where
198        D: Deserializer<'de>,
199    {
200        #[derive(Deserialize)]
201        struct Wire<Id, Pixels> {
202            id: Id,
203            timestamp: Timestamp,
204            dimensions: PixelDimensions,
205            pixel_format: PixelFormat,
206            pixels: Pixels,
207        }
208        let wire = Wire::deserialize(deserializer)?;
209        Self::new(
210            wire.id,
211            wire.timestamp,
212            wire.dimensions,
213            wire.pixel_format,
214            wire.pixels,
215        )
216        .map_err(serde::de::Error::custom)
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223
224    #[test]
225    fn validates_frame_payload_and_deserialization() {
226        let dimensions = PixelDimensions::new(2, 2).unwrap();
227        assert_eq!(dimensions.rgba8_byte_len().unwrap(), 16);
228        assert_eq!(
229            Frame::new(
230                "frame",
231                Timestamp::ZERO,
232                dimensions,
233                PixelFormat::Rgba8SrgbStraight,
234                &[0_u8; 15][..],
235            )
236            .unwrap_err()
237            .code,
238            ErrorCode::PixelLengthMismatch
239        );
240        assert!(serde_json::from_str::<PixelDimensions>(r#"{"width":0,"height":1}"#).is_err());
241    }
242
243    #[test]
244    fn pixel_format_registry_is_stable() {
245        for format in PixelFormat::ALL {
246            let json = serde_json::to_string(format).unwrap();
247            assert_eq!(serde_json::from_str::<PixelFormat>(&json).unwrap(), *format);
248            assert_eq!(format.to_string(), format.as_str());
249        }
250    }
251}