1use serde::{Deserialize, Serialize};
4
5pub const MAX_FRAME_METADATA_BYTES: usize = 64 * 1024;
7pub const MAX_FRAME_METADATA_ITEMS: usize = 128;
9pub const MAX_FRAME_METADATA_TEXT: usize = 1024;
11
12#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
15pub struct FrameChunk {
16 pub id: String,
18 #[cfg_attr(feature = "ts", ts(type = "number"))]
20 pub bytes: u64,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
25#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
26pub struct FrameFeature {
27 pub name: String,
29 pub value: Option<String>,
31 pub error: Option<String>,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
37#[cfg_attr(feature = "ts", derive(ts_rs::TS))]
38pub struct FrameMetadata {
39 pub block_id: String,
41 pub ts_dev: Option<String>,
43 pub ts_host_ns: Option<String>,
46 pub complete: bool,
48 pub chunks: Vec<FrameChunk>,
50 pub features: Vec<FrameFeature>,
52 pub chunk_error: Option<String>,
54 pub truncated: bool,
56}
57
58impl FrameMetadata {
59 pub fn with_features<E: std::fmt::Display>(
62 mut self,
63 features: impl IntoIterator<Item = (String, Result<String, E>)>,
64 ) -> Self {
65 for (index, (name, value)) in features.into_iter().enumerate() {
66 if index == MAX_FRAME_METADATA_ITEMS {
67 self.truncated = true;
68 break;
69 }
70 let name = clipped(name, &mut self.truncated);
71 let (value, error) = match value {
72 Ok(value) => (Some(clipped(value, &mut self.truncated)), None),
73 Err(error) => (None, Some(clipped(error.to_string(), &mut self.truncated))),
74 };
75 self.features.push(FrameFeature { name, value, error });
76 }
77 self.bound();
78 self
79 }
80
81 pub fn encode(&self) -> Result<Vec<u8>, serde_json::Error> {
85 let mut value = self.clone();
86 value.bound();
87 value
88 .validate()
89 .map_err(<serde_json::Error as serde::ser::Error>::custom)?;
90 loop {
91 let bytes = serde_json::to_vec(&value)?;
92 if bytes.len() <= MAX_FRAME_METADATA_BYTES {
93 return Ok(bytes);
94 }
95 value.truncated = true;
96 if !value.features.is_empty() {
99 value.features.truncate(value.features.len() / 2);
100 continue;
101 }
102 if !value.chunks.is_empty() {
103 value.chunks.truncate(value.chunks.len() / 2);
104 continue;
105 }
106 return Err(<serde_json::Error as serde::ser::Error>::custom(
107 "fixed frame metadata exceeds the packet limit",
108 ));
109 }
110 }
111
112 pub fn decode(bytes: &[u8]) -> Result<Self, String> {
115 if bytes.len() > MAX_FRAME_METADATA_BYTES {
116 return Err("frame metadata exceeds 64 KiB".into());
117 }
118 let value: Self = serde_json::from_slice(bytes).map_err(|e| e.to_string())?;
119 value.validate()?;
120 Ok(value)
121 }
122
123 fn validate(&self) -> Result<(), String> {
124 let text_ok = |s: &str| s.chars().count() <= MAX_FRAME_METADATA_TEXT;
125 let decimal_u64 = |s: &str| {
126 !s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()) && s.parse::<u64>().is_ok()
127 };
128 let signed_ns = |s: &str| {
129 let digits = s.strip_prefix('-').unwrap_or(s);
130 !digits.is_empty()
131 && digits.bytes().all(|b| b.is_ascii_digit())
132 && s.parse::<i128>().is_ok()
133 };
134 if !decimal_u64(&self.block_id)
135 || self.ts_dev.as_ref().is_some_and(|s| !decimal_u64(s))
136 || self.ts_host_ns.as_ref().is_some_and(|s| !signed_ns(s))
137 {
138 return Err("invalid decimal frame identifier or timestamp".into());
139 }
140 if self.chunks.len() > MAX_FRAME_METADATA_ITEMS
141 || self.features.len() > MAX_FRAME_METADATA_ITEMS
142 || self.chunk_error.as_ref().is_some_and(|s| !text_ok(s))
143 || self
144 .chunks
145 .iter()
146 .any(|c| !decimal_u64(&c.id) || c.bytes > 9_007_199_254_740_991)
147 || self.features.iter().any(|f| {
148 !text_ok(&f.name)
149 || f.value.as_ref().is_some_and(|s| !text_ok(s))
150 || f.error.as_ref().is_some_and(|s| !text_ok(s))
151 || f.value.is_some() == f.error.is_some()
152 })
153 {
154 return Err("frame metadata exceeds item/text limits or has an invalid feature".into());
155 }
156 Ok(())
157 }
158
159 fn bound(&mut self) {
160 if self.chunks.len() > MAX_FRAME_METADATA_ITEMS {
161 self.chunks.truncate(MAX_FRAME_METADATA_ITEMS);
162 self.truncated = true;
163 }
164 if self.features.len() > MAX_FRAME_METADATA_ITEMS {
165 self.features.truncate(MAX_FRAME_METADATA_ITEMS);
166 self.truncated = true;
167 }
168 for feature in &mut self.features {
169 feature.name = clipped(std::mem::take(&mut feature.name), &mut self.truncated);
170 feature.value = feature
171 .value
172 .take()
173 .map(|s| clipped(s, &mut self.truncated));
174 feature.error = feature
175 .error
176 .take()
177 .map(|s| clipped(s, &mut self.truncated));
178 }
179 self.chunk_error = self
180 .chunk_error
181 .take()
182 .map(|s| clipped(s, &mut self.truncated));
183 }
184}
185
186fn clipped(mut text: String, truncated: &mut bool) -> String {
187 if let Some((offset, _)) = text.char_indices().nth(MAX_FRAME_METADATA_TEXT) {
188 text.truncate(offset);
189 *truncated = true;
190 }
191 text
192}
193
194#[cfg(feature = "genicam")]
195impl From<&viva_genicam::Frame> for FrameMetadata {
196 fn from(frame: &viva_genicam::Frame) -> Self {
197 let ts_host_ns = frame
198 .ts_host
199 .map(|t| match t.duration_since(std::time::UNIX_EPOCH) {
200 Ok(d) => d.as_nanos().to_string(),
201 Err(e) => format!("-{}", e.duration().as_nanos()),
202 });
203 let mut metadata = Self {
204 block_id: frame.block_id.to_string(),
205 ts_dev: frame.ts_dev.map(|t| t.to_string()),
206 ts_host_ns,
207 complete: frame.is_complete(),
208 chunks: frame.chunks.as_ref().map_or_else(Vec::new, |chunks| {
209 chunks
210 .iter()
211 .take(MAX_FRAME_METADATA_ITEMS)
212 .map(|(id, data)| FrameChunk {
213 id: id.to_string(),
214 bytes: data.len() as u64,
215 })
216 .collect()
217 }),
218 features: Vec::new(),
219 chunk_error: None,
220 truncated: frame
221 .chunks
222 .as_ref()
223 .is_some_and(|c| c.len() > MAX_FRAME_METADATA_ITEMS),
224 };
225 let kind = frame.payload_type & 0x3FFF;
226 let carries_chunks = frame.payload_type & 0x4000 != 0 || kind == 4 || kind == 5;
227 if carries_chunks && frame.chunks.is_none() {
228 metadata.chunk_error = Some(
229 if frame.is_complete() {
230 "The frame's chunk layout could not be decoded"
231 } else {
232 "Chunk data is unavailable for an incomplete frame"
233 }
234 .into(),
235 );
236 }
237 metadata
238 }
239}
240
241#[cfg(test)]
242mod tests {
243 use super::*;
244
245 fn metadata() -> FrameMetadata {
246 FrameMetadata {
247 block_id: u64::MAX.to_string(),
248 ts_dev: Some(u64::MAX.to_string()),
249 ts_host_ns: Some("-1".into()),
250 complete: true,
251 chunks: vec![FrameChunk {
252 id: "1".into(),
253 bytes: 8,
254 }],
255 features: Vec::new(),
256 chunk_error: None,
257 truncated: false,
258 }
259 }
260
261 #[test]
262 fn exact_identifiers_nulls_and_per_feature_errors_survive_json() {
263 let meta = metadata().with_features([
264 ("ChunkTimestamp".into(), Ok("18446744073709551615".into())),
265 ("ChunkGain".into(), Err("chunk too short")),
266 ]);
267 let bytes = meta.encode().unwrap();
268 let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
269 assert_eq!(json["block_id"], "18446744073709551615");
270 assert_eq!(json["ts_host_ns"], "-1");
271 assert!(json["features"][0]["error"].is_null());
272 assert_eq!(json["features"][1]["error"], "chunk too short");
273 assert_eq!(FrameMetadata::decode(&bytes).unwrap(), meta);
274 }
275
276 #[test]
277 fn metadata_is_bounded_without_losing_the_image_or_corrupting_unicode() {
278 let mut meta = metadata().with_features(
279 (0..200).map(|n| (format!("Feature{n}"), Ok::<_, String>("🦀\n".repeat(2048)))),
280 );
281 meta.chunks = (0..200)
282 .map(|n| FrameChunk {
283 id: n.to_string(),
284 bytes: 8,
285 })
286 .collect();
287 let bytes = meta.encode().unwrap();
288 assert!(bytes.len() <= MAX_FRAME_METADATA_BYTES);
289 let bounded = FrameMetadata::decode(&bytes).unwrap();
290 assert!(bounded.truncated);
291 assert!(bounded.features.len() < MAX_FRAME_METADATA_ITEMS);
292 assert!(bounded.chunks.len() <= MAX_FRAME_METADATA_ITEMS);
293 assert!(
294 bounded
295 .features
296 .iter()
297 .all(|f| f.value.as_ref().unwrap().chars().count() <= MAX_FRAME_METADATA_TEXT)
298 );
299 }
300
301 #[test]
302 fn untrusted_metadata_rejects_bad_decimals_counts_and_feature_shapes() {
303 assert!(FrameMetadata::decode(&vec![b' '; MAX_FRAME_METADATA_BYTES + 1]).is_err());
304 assert!(FrameMetadata::decode(b"{}").is_err());
305 let mut meta = metadata();
306 meta.block_id = "18446744073709551616".into();
307 assert!(FrameMetadata::decode(&serde_json::to_vec(&meta).unwrap()).is_err());
308 meta = metadata();
309 meta.features = vec![FrameFeature {
310 name: "x".into(),
311 value: Some("1".into()),
312 error: Some("bad".into()),
313 }];
314 assert!(FrameMetadata::decode(&serde_json::to_vec(&meta).unwrap()).is_err());
315 meta.features = vec![
316 FrameFeature {
317 name: "x".into(),
318 value: Some("1".into()),
319 error: None
320 };
321 129
322 ];
323 assert!(FrameMetadata::decode(&serde_json::to_vec(&meta).unwrap()).is_err());
324 }
325
326 #[cfg(feature = "genicam")]
327 #[test]
328 fn frame_mapper_keeps_missing_clocks_and_chunk_errors_explicit() {
329 use viva_genicam::{Frame, FrameStatus};
330 let mut frame = Frame::new(Vec::new().into(), 1, 1, viva_pfnc::PixelFormat::Mono8);
331 frame.block_id = u64::MAX;
332 let plain = FrameMetadata::from(&frame);
333 assert_eq!(plain.block_id, u64::MAX.to_string());
334 assert_eq!(plain.ts_dev, None);
335 assert_eq!(plain.ts_host_ns, None);
336 assert!(plain.complete);
337 assert_eq!(plain.chunk_error, None);
338 frame.payload_type = 0x4001;
339 assert!(
340 FrameMetadata::from(&frame)
341 .chunk_error
342 .unwrap()
343 .contains("could not be decoded")
344 );
345 frame.status = FrameStatus::Incomplete { missing_packets: 1 };
346 assert!(!FrameMetadata::from(&frame).complete);
347 assert!(
348 FrameMetadata::from(&frame)
349 .chunk_error
350 .unwrap()
351 .contains("incomplete")
352 );
353 }
354}