Skip to main content

viva_pfnc/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2//! Pixel Format Naming Convention (PFNC) tables, sizes and conversions.
3//!
4//! [`PixelFormat`] names the formats a camera reports, with the 32-bit codes
5//! of EMVA's *GenICam Pixel Format Names and Values* table, and answers how
6//! many bits and bytes they occupy. [`convert`] turns their bytes into
7//! samples, grey or RGB. This crate is the one place pixel layouts live: the
8//! library's `Frame::to_rgb8`, its image writer and Viva Studio's viewer all
9//! call [`convert`].
10//!
11//! The crate does no I/O and has no required dependencies, and it compiles
12//! for `wasm32-unknown-unknown`.
13
14use core::fmt;
15
16pub mod convert;
17
18/// Declare the enumeration and its tables from one list, so a name, a code
19/// and the text a format prints as cannot drift apart.
20macro_rules! pixel_formats {
21    ($(
22        $(#[$meta:meta])*
23        $variant:ident = $code:literal, $name:literal $(| $alias:literal)*;
24    )*) => {
25        /// Enumeration of the pixel formats supported by the helper routines.
26        ///
27        /// Codes are those of EMVA's *GenICam Pixel Format Names and Values*
28        /// (7 October 2025), the table PFNC 2.4 Appendix C refers to.
29        #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30        #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
31        #[non_exhaustive]
32        #[repr(u32)]
33        // Y'CbCr variants keep their PFNC spelling (`YUV422_8_UYVY`): the
34        // component order after the underscore is part of the name.
35        #[allow(non_camel_case_types)]
36        pub enum PixelFormat {
37            $(
38                $(#[$meta])*
39                #[doc = concat!("PFNC `", stringify!($variant), "`, code `", stringify!($code), "`.")]
40                $variant = $code,
41            )*
42            /// Unknown PFNC code reported by the device.
43            Unknown(u32),
44        }
45
46        impl PixelFormat {
47            /// Convert a raw PFNC code into a [`PixelFormat`] enumeration.
48            pub const fn from_code(code: u32) -> PixelFormat {
49                match code {
50                    $($code => PixelFormat::$variant,)*
51                    other => PixelFormat::Unknown(other),
52                }
53            }
54
55            /// Return the PFNC code associated with the pixel format.
56            pub const fn code(self) -> u32 {
57                match self {
58                    $(PixelFormat::$variant => $code,)*
59                    PixelFormat::Unknown(code) => code,
60                }
61            }
62
63            /// Convert a pixel format name to a [`PixelFormat`].
64            ///
65            /// Accepts the PFNC name and the older spellings cameras still
66            /// report for the same code — `YUV422Packed` for `YUV422_8_UYVY`,
67            /// `RGB8` for `RGB8Packed`. Returns `PixelFormat::Unknown(0)` for
68            /// unrecognised names.
69            pub fn from_name(name: &str) -> PixelFormat {
70                match name {
71                    $($name $(| $alias)* => PixelFormat::$variant,)*
72                    _ => PixelFormat::Unknown(0),
73                }
74            }
75
76            /// The format's PFNC name, as it prints (`"Mono8"`,
77            /// `"RGB8Packed"`); `None` for an unknown code.
78            pub const fn name(self) -> Option<&'static str> {
79                match self {
80                    $(PixelFormat::$variant => Some($name),)*
81                    PixelFormat::Unknown(_) => None,
82                }
83            }
84
85            /// Every named format, for tests that must cover them all.
86            #[cfg(test)]
87            const ALL: &'static [PixelFormat] = &[$(PixelFormat::$variant,)*];
88        }
89    };
90}
91
92pixel_formats! {
93    Mono8 = 0x0108_0001, "Mono8";
94    Mono10 = 0x0110_0003, "Mono10";
95    Mono12 = 0x0110_0005, "Mono12";
96    Mono14 = 0x0110_0025, "Mono14";
97    Mono16 = 0x0110_0007, "Mono16";
98    /// 10-bit monochrome, PFNC lsb packed: four pixels in five bytes, filled
99    /// from bit 0 of byte 0 (PFNC 2.4 §6.3.1, Figure 6-9).
100    Mono10p = 0x010A_0046, "Mono10p";
101    /// 12-bit monochrome, PFNC lsb packed: two pixels in three bytes, filled
102    /// from bit 0 of byte 0 (PFNC 2.4 §6.3.1).
103    Mono12p = 0x010C_0047, "Mono12p";
104    /// 10-bit monochrome in the GigE Vision 2.0 layout: two pixels in three
105    /// bytes, the eight most significant bits of each in bytes 0 and 2, the
106    /// two least significant bits in bits 1-0 and 5-4 of byte 1.
107    Mono10Packed = 0x010C_0004, "Mono10Packed";
108    /// 12-bit monochrome in the GigE Vision 2.0 layout: two pixels in three
109    /// bytes, the eight most significant bits of each in bytes 0 and 2, the
110    /// four least significant bits in the low and high nibble of byte 1. Not
111    /// the bit order of [`PixelFormat::Mono12p`].
112    ///
113    /// EMVA's values table assigns the code to GigE Vision 2.0, whose text is
114    /// not public; the layout is the one Teledyne FLIR documents for its
115    /// cameras ("Understanding Pixel Formats"), as for
116    /// [`PixelFormat::Mono10Packed`].
117    Mono12Packed = 0x010C_0006, "Mono12Packed";
118    Confidence8 = 0x0108_00C6, "Confidence8";
119    Coord3DC16 = 0x0110_00B8, "Coord3D_C16";
120    Coord3DC32f = 0x0120_00BF, "Coord3D_C32f";
121    Coord3DAC16 = 0x0220_00BB, "Coord3D_AC16";
122    Coord3DAC32f = 0x0240_00C2, "Coord3D_AC32f";
123    Coord3DABC32f = 0x0260_00C0, "Coord3D_ABC32f";
124    BayerGR8 = 0x0108_0008, "BayerGR8";
125    BayerRG8 = 0x0108_0009, "BayerRG8";
126    BayerGB8 = 0x0108_000A, "BayerGB8";
127    BayerBG8 = 0x0108_000B, "BayerBG8";
128    BayerGR10 = 0x0110_000C, "BayerGR10";
129    BayerRG10 = 0x0110_000D, "BayerRG10";
130    BayerGB10 = 0x0110_000E, "BayerGB10";
131    BayerBG10 = 0x0110_000F, "BayerBG10";
132    BayerGR12 = 0x0110_0010, "BayerGR12";
133    BayerRG12 = 0x0110_0011, "BayerRG12";
134    BayerGB12 = 0x0110_0012, "BayerGB12";
135    BayerBG12 = 0x0110_0013, "BayerBG12";
136    BayerGR16 = 0x0110_002E, "BayerGR16";
137    BayerRG16 = 0x0110_002F, "BayerRG16";
138    BayerGB16 = 0x0110_0030, "BayerGB16";
139    BayerBG16 = 0x0110_0031, "BayerBG16";
140    /// A Bayer mosaic packed as [`PixelFormat::Mono10p`] is.
141    BayerGR10p = 0x010A_0056, "BayerGR10p";
142    /// A Bayer mosaic packed as [`PixelFormat::Mono10p`] is.
143    BayerRG10p = 0x010A_0058, "BayerRG10p";
144    /// A Bayer mosaic packed as [`PixelFormat::Mono10p`] is.
145    BayerGB10p = 0x010A_0054, "BayerGB10p";
146    /// A Bayer mosaic packed as [`PixelFormat::Mono10p`] is.
147    BayerBG10p = 0x010A_0052, "BayerBG10p";
148    /// A Bayer mosaic packed as [`PixelFormat::Mono12p`] is.
149    BayerGR12p = 0x010C_0057, "BayerGR12p";
150    /// A Bayer mosaic packed as [`PixelFormat::Mono12p`] is.
151    BayerRG12p = 0x010C_0059, "BayerRG12p";
152    /// A Bayer mosaic packed as [`PixelFormat::Mono12p`] is.
153    BayerGB12p = 0x010C_0055, "BayerGB12p";
154    /// A Bayer mosaic packed as [`PixelFormat::Mono12p`] is.
155    BayerBG12p = 0x010C_0053, "BayerBG12p";
156    /// A Bayer mosaic packed as [`PixelFormat::Mono10Packed`] is.
157    BayerGR10Packed = 0x010C_0026, "BayerGR10Packed";
158    /// A Bayer mosaic packed as [`PixelFormat::Mono10Packed`] is.
159    BayerRG10Packed = 0x010C_0027, "BayerRG10Packed";
160    /// A Bayer mosaic packed as [`PixelFormat::Mono10Packed`] is.
161    BayerGB10Packed = 0x010C_0028, "BayerGB10Packed";
162    /// A Bayer mosaic packed as [`PixelFormat::Mono10Packed`] is.
163    BayerBG10Packed = 0x010C_0029, "BayerBG10Packed";
164    /// A Bayer mosaic packed as [`PixelFormat::Mono12Packed`] is.
165    BayerGR12Packed = 0x010C_002A, "BayerGR12Packed";
166    /// A Bayer mosaic packed as [`PixelFormat::Mono12Packed`] is.
167    BayerRG12Packed = 0x010C_002B, "BayerRG12Packed";
168    /// A Bayer mosaic packed as [`PixelFormat::Mono12Packed`] is.
169    BayerGB12Packed = 0x010C_002C, "BayerGB12Packed";
170    /// A Bayer mosaic packed as [`PixelFormat::Mono12Packed`] is.
171    BayerBG12Packed = 0x010C_002D, "BayerBG12Packed";
172    RGB8Packed = 0x0218_0014, "RGB8Packed" | "RGB8";
173    BGR8Packed = 0x0218_0015, "BGR8Packed" | "BGR8";
174    /// RGB with a fourth, manufacturer-defined alpha byte.
175    RGBa8 = 0x0220_0016, "RGBa8" | "RGBA8Packed";
176    /// BGR with a fourth, manufacturer-defined alpha byte.
177    BGRa8 = 0x0220_0017, "BGRa8" | "BGRA8Packed";
178    /// Y'CbCr 4:1:1, six bytes for four pixels in the order U Y Y V Y Y.
179    YUV411_8_UYYVYY = 0x020C_001E, "YUV411_8_UYYVYY" | "YUV411Packed";
180    /// Y'CbCr 4:2:2, four bytes for two pixels in the order U Y V Y.
181    YUV422_8_UYVY = 0x0210_001F, "YUV422_8_UYVY" | "YUV422Packed";
182    /// Y'CbCr 4:2:2, four bytes for two pixels in the order Y U Y V — the
183    /// PFNC default for 4:2:2 (PFNC 2.4 §3.1.3).
184    YUV422_8 = 0x0210_0032, "YUV422_8" | "YUV422_YUYV_Packed";
185    /// Full-range Y'CbCr 4:2:2 in the order Y Cb Y Cr.
186    YCbCr422_8 = 0x0210_003B, "YCbCr422_8";
187    /// Full-range Y'CbCr 4:2:2 in the order Cb Y Cr Y.
188    YCbCr422_8_CbYCrY = 0x0210_0043, "YCbCr422_8_CbYCrY";
189    /// Y'CbCr 4:4:4 in the order U Y V.
190    YUV8_UYV = 0x0218_0020, "YUV8_UYV" | "YUV444Packed";
191    /// Full-range Y'CbCr 4:4:4 in the order Cb Y Cr.
192    YCbCr8_CbYCr = 0x0218_003A, "YCbCr8_CbYCr";
193    /// Full-range Y'CbCr 4:4:4 in the order Y Cb Cr.
194    YCbCr8 = 0x0218_005B, "YCbCr8";
195    /// Prophesee EVT 3.0 event stream, as a Lucid Triton2 EVS sends it
196    /// ([#139](https://github.com/VitalyVorobyev/viva-genicam/pull/139)).
197    ///
198    /// **Vendor-defined, not PFNC**: bit 31 of the code is set, which is how
199    /// PFNC marks a format outside its own table — hence the `VendorLucid`
200    /// prefix, so a Lucid extension cannot read as a standard format name.
201    /// The stream carries events,
202    /// not pixels, so [`PixelFormat::bytes_per_pixel`] answers the size of one
203    /// event *word* (16 bits) — the depth the code's own bits 23-16 declare,
204    /// and the same answer [`PixelFormat::Unknown`] would derive for it. A
205    /// block's length is not `width * height` times that.
206    VendorLucidEvsEvt30 = 0x8110_0E30, "EVT3_0";
207    /// Prophesee EVT 2.1 event stream, 64-bit event words. Vendor-defined; see
208    /// [`PixelFormat::VendorLucidEvsEvt30`].
209    VendorLucidEvsEvt21 = 0x8140_0E21, "EVT2_1";
210}
211
212impl PixelFormat {
213    /// Number of bytes used to encode a single pixel.
214    ///
215    /// Derived from bits 23-16 of the PFNC code, which carry the pixel's bit
216    /// depth, so a format this enumeration does not name is sized too. `None`
217    /// means the pixel genuinely has no whole-byte size — a packed format —
218    /// not that we failed to look it up; [`PixelFormat::bits_per_pixel`] and
219    /// [`PixelFormat::image_bytes`] answer for those.
220    pub const fn bytes_per_pixel(self) -> Option<usize> {
221        PixelFormat::bytes_from_code(self.code())
222    }
223
224    /// Bytes per pixel read straight out of a PFNC code.
225    ///
226    /// Bits 23-16 of every PFNC value are the pixel's bit depth, so a format
227    /// this enumeration has no variant for still has a usable size. That is the
228    /// difference between a receiver sizing a `Coord3D_ABC32f` frame at twelve
229    /// bytes per pixel and sizing it at one: callers overwhelmingly write
230    /// `bytes_per_pixel().unwrap_or(1)`, and a `None` there is not a neutral
231    /// answer, it is a wrong one.
232    ///
233    /// Returns `None` when the depth is not a whole number of bytes, because
234    /// then no `usize` is correct. **Packed formats are the reason this check
235    /// exists**: `Mono12Packed`, `Mono10Packed`, `YUV411Packed`,
236    /// `BayerGR12Packed` and `BayerRG12Packed` all declare 12 bits, and they
237    /// are common in the vendor corpus — `Mono12Packed` alone is offered by 28
238    /// of its 38 documents. Rounding 12 bits up to 2 bytes overstates a frame
239    /// by a third, which a length check downstream reads as a *short payload* —
240    /// a confidently wrong size is worse than an absent one.
241    const fn bytes_from_code(code: u32) -> Option<usize> {
242        let bits = (code >> 16) & 0xFF;
243        if bits == 0 || !bits.is_multiple_of(8) {
244            return None;
245        }
246        Some((bits / 8) as usize)
247    }
248
249    /// Bits one pixel occupies, from bits 23-16 of the PFNC code: 12 for
250    /// `Mono12p` and `Mono12Packed`, 16 for `Mono12` (two bytes, four of them
251    /// padding) and for 4:2:2 Y'CbCr (an average over each pair of pixels).
252    ///
253    /// `None` only for a code that declares no size, such as `Unknown(0)`.
254    pub const fn bits_per_pixel(self) -> Option<u32> {
255        match (self.code() >> 16) & 0xFF {
256            0 => None,
257            bits => Some(bits),
258        }
259    }
260
261    /// Bytes holding `width` pixels that start a packing group, the group
262    /// completed when `width` ends inside one.
263    ///
264    /// PFNC 2.4 §6.7 completes a group the image or line ends inside with
265    /// zero-valued components, so `Mono12p` holds 3 bytes for one pixel as
266    /// for two. This is the length of one line under §6.7's *line padding*.
267    /// `None` when [`PixelFormat::image_bytes`] is.
268    pub const fn line_bytes(self, width: u32) -> Option<usize> {
269        self.bytes_for(width as usize)
270    }
271
272    /// Bytes holding a `width` × `height` image whose pixels run on from one
273    /// line to the next without padding (PFNC 2.4 §6.7, *image padding*), the
274    /// last packing group completed with zero-valued pixels.
275    ///
276    /// Equal to `line_bytes(width) * height` whenever `width` is a multiple of
277    /// the packing group: four pixels for 10p, two for 12p, `10Packed`,
278    /// `12Packed` and 4:2:2, four for 4:1:1. `None` for an event stream, whose
279    /// leader fields are not image geometry, for a code that declares no size,
280    /// and for a size that overflows `usize`.
281    ///
282    /// A camera may send a bit-packed image without completing that group;
283    /// [`convert`]'s *Geometry* section says what the converters accept.
284    pub const fn image_bytes(self, width: u32, height: u32) -> Option<usize> {
285        let Some(pixels) = (width as usize).checked_mul(height as usize) else {
286            return None;
287        };
288        self.bytes_for(pixels)
289    }
290
291    /// The smallest run of `(pixels, bytes)` that starts on a byte boundary.
292    ///
293    /// Subsampled Y'CbCr carries its chroma once per group (PFNC 2.4 §3.1.3,
294    /// §3.1.4). Otherwise the group is as many pixels as fill whole bytes
295    /// with no padding bit (§6.3.1 for `p`): four for 10 bits, two for 12;
296    /// the GigE Vision `10Packed`/`12Packed` formats declare 12 bits and put
297    /// two pixels in three bytes, which is the same group.
298    const fn group(self) -> Option<(usize, usize)> {
299        match self {
300            PixelFormat::YUV422_8
301            | PixelFormat::YUV422_8_UYVY
302            | PixelFormat::YCbCr422_8
303            | PixelFormat::YCbCr422_8_CbYCrY => return Some((2, 4)),
304            PixelFormat::YUV411_8_UYYVYY => return Some((4, 6)),
305            PixelFormat::VendorLucidEvsEvt30 | PixelFormat::VendorLucidEvsEvt21 => return None,
306            _ => {}
307        }
308        let Some(bits) = self.bits_per_pixel() else {
309            return None;
310        };
311        // gcd(bits, 8): the largest power of two dividing both.
312        let common = 1u32 << bits.trailing_zeros();
313        let common = if common > 8 { 8 } else { common };
314        Some(((8 / common) as usize, (bits / common) as usize))
315    }
316
317    /// Bytes for `pixels` pixels starting on a group boundary, the last group
318    /// completed.
319    const fn bytes_for(self, pixels: usize) -> Option<usize> {
320        let Some((group_pixels, group_bytes)) = self.group() else {
321            return None;
322        };
323        pixels.div_ceil(group_pixels).checked_mul(group_bytes)
324    }
325
326    /// Whether the pixel format represents a Bayer mosaic.
327    pub const fn is_bayer(self) -> bool {
328        self.cfa_pattern().is_some()
329    }
330
331    /// Whether the pixel format is single-component monochrome (`Mono*`).
332    pub const fn is_mono(self) -> bool {
333        matches!(
334            self,
335            PixelFormat::Mono8
336                | PixelFormat::Mono10
337                | PixelFormat::Mono12
338                | PixelFormat::Mono14
339                | PixelFormat::Mono16
340                | PixelFormat::Mono10p
341                | PixelFormat::Mono12p
342                | PixelFormat::Mono10Packed
343                | PixelFormat::Mono12Packed
344        )
345    }
346
347    /// Return the Color Filter Array pattern and canonical offsets.
348    ///
349    /// The tuple encodes `(pattern, x_offset, y_offset)` where the offsets
350    /// describe how the sensor mosaic aligns to the canonical `"RGGB"`
351    /// ordering: the pixel at `(x, y)` has the colour `"RGGB"` has at
352    /// `(x + x_offset, y + y_offset)`. The first two letters of a Bayer name
353    /// are its top row (PFNC 2.4 §3.1.7): `BayerGR` is G R over B G.
354    pub const fn cfa_pattern(self) -> Option<(&'static str, u8, u8)> {
355        use PixelFormat as P;
356        match self {
357            P::BayerRG8
358            | P::BayerRG10
359            | P::BayerRG12
360            | P::BayerRG16
361            | P::BayerRG10p
362            | P::BayerRG12p
363            | P::BayerRG10Packed
364            | P::BayerRG12Packed => Some(("RGGB", 0, 0)),
365            P::BayerGR8
366            | P::BayerGR10
367            | P::BayerGR12
368            | P::BayerGR16
369            | P::BayerGR10p
370            | P::BayerGR12p
371            | P::BayerGR10Packed
372            | P::BayerGR12Packed => Some(("RGGB", 1, 0)),
373            P::BayerGB8
374            | P::BayerGB10
375            | P::BayerGB12
376            | P::BayerGB16
377            | P::BayerGB10p
378            | P::BayerGB12p
379            | P::BayerGB10Packed
380            | P::BayerGB12Packed => Some(("RGGB", 0, 1)),
381            P::BayerBG8
382            | P::BayerBG10
383            | P::BayerBG12
384            | P::BayerBG16
385            | P::BayerBG10p
386            | P::BayerBG12p
387            | P::BayerBG10Packed
388            | P::BayerBG12Packed => Some(("RGGB", 1, 1)),
389            _ => None,
390        }
391    }
392}
393
394impl fmt::Display for PixelFormat {
395    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
396        match self.name() {
397            Some(name) => f.write_str(name),
398            None => write!(f, "Unknown(0x{:08X})", self.code()),
399        }
400    }
401}
402
403#[cfg(test)]
404mod tests {
405    use super::PixelFormat;
406
407    #[test]
408    fn roundtrip_known_codes() {
409        for &fmt in PixelFormat::ALL {
410            assert_eq!(PixelFormat::from_code(fmt.code()), fmt);
411            assert_eq!(PixelFormat::from_name(&fmt.to_string()), fmt);
412        }
413    }
414
415    #[test]
416    fn unknown_code_roundtrip() {
417        let code = 0xDEAD_BEEF;
418        let fmt = PixelFormat::from_code(code);
419        assert!(matches!(fmt, PixelFormat::Unknown(value) if value == code));
420        assert_eq!(fmt.code(), code);
421    }
422
423    #[test]
424    fn bytes_per_pixel_matches_expectations() {
425        assert_eq!(PixelFormat::Mono8.bytes_per_pixel(), Some(1));
426        assert_eq!(PixelFormat::Mono10.bytes_per_pixel(), Some(2));
427        assert_eq!(PixelFormat::Mono16.bytes_per_pixel(), Some(2));
428        assert_eq!(PixelFormat::Confidence8.bytes_per_pixel(), Some(1));
429        assert_eq!(PixelFormat::Coord3DC32f.bytes_per_pixel(), Some(4));
430        assert_eq!(PixelFormat::Coord3DAC16.bytes_per_pixel(), Some(4));
431        assert_eq!(PixelFormat::Coord3DAC32f.bytes_per_pixel(), Some(8));
432        assert_eq!(PixelFormat::Coord3DABC32f.bytes_per_pixel(), Some(12));
433        assert_eq!(PixelFormat::RGB8Packed.bytes_per_pixel(), Some(3));
434        assert_eq!(PixelFormat::BayerRG8.bytes_per_pixel(), Some(1));
435        assert_eq!(PixelFormat::BayerRG16.bytes_per_pixel(), Some(2));
436        assert_eq!(PixelFormat::BayerGR16.bytes_per_pixel(), Some(2));
437        assert_eq!(PixelFormat::VendorLucidEvsEvt30.bytes_per_pixel(), Some(2));
438        assert_eq!(PixelFormat::VendorLucidEvsEvt21.bytes_per_pixel(), Some(8));
439        assert_eq!(PixelFormat::Unknown(0).bytes_per_pixel(), None);
440    }
441
442    #[test]
443    fn event_format_names_roundtrip() {
444        for (name, format) in [
445            ("EVT3_0", PixelFormat::VendorLucidEvsEvt30),
446            ("EVT2_1", PixelFormat::VendorLucidEvsEvt21),
447        ] {
448            assert_eq!(PixelFormat::from_name(name), format);
449            assert_eq!(format.to_string(), name);
450        }
451    }
452
453    /// Every named format must agree with the size encoded in its own code,
454    /// which is what makes the `Unknown` derivation trustworthy.
455    #[test]
456    fn named_formats_agree_with_their_own_pfnc_code() {
457        for &fmt in PixelFormat::ALL {
458            // Keep the size nibble, replace the unique ID with one no format
459            // uses, so `from_code` yields `Unknown` and the size has to be
460            // derived rather than looked up.
461            let disguised = PixelFormat::from_code((fmt.code() & 0xFFFF_0000) | 0xFFFF);
462            assert!(
463                matches!(disguised, PixelFormat::Unknown(_)),
464                "{fmt}: the disguise resolved to a named format"
465            );
466            assert_eq!(
467                fmt.bytes_per_pixel(),
468                disguised.bytes_per_pixel(),
469                "{fmt}: the hardcoded size disagrees with bits 23-16 of its own code"
470            );
471        }
472    }
473
474    /// A format we have no variant for still gets a size, so callers stop
475    /// falling back to one byte per pixel.
476    #[test]
477    fn unknown_formats_are_sized_from_their_code() {
478        // Real PFNC codes we deliberately do not enumerate.
479        // RGB8_Planar: 24 bits. RGB16: 48 bits. Coord3D_ABC32: 96 bits.
480        assert_eq!(
481            PixelFormat::from_code(0x0218_0021).bytes_per_pixel(),
482            Some(3)
483        );
484        assert_eq!(
485            PixelFormat::from_code(0x0230_0033).bytes_per_pixel(),
486            Some(6)
487        );
488        assert_eq!(
489            PixelFormat::from_code(0x0260_00C1).bytes_per_pixel(),
490            Some(12)
491        );
492    }
493
494    /// Packed formats have a fractional byte size, and no `usize` is right.
495    ///
496    /// These five all appear in the vendor XML corpus — `Mono12Packed` in
497    /// 28 of its 38 documents. Rounding 12 bits up to 2 bytes would
498    /// overstate a frame by a third and make a length check downstream reject
499    /// it as short.
500    #[test]
501    fn packed_formats_report_no_whole_byte_size() {
502        for (name, code) in [
503            ("Mono10Packed", 0x010C_0004_u32),
504            ("Mono12Packed", 0x010C_0006),
505            ("YUV411Packed", 0x020C_001E),
506            ("BayerGB12Packed", 0x010C_002C),
507            ("BayerBG12Packed", 0x010C_002D),
508        ] {
509            assert_eq!(
510                PixelFormat::from_code(code).bytes_per_pixel(),
511                None,
512                "{name} declares 12 bits per pixel and must not be rounded"
513            );
514        }
515    }
516
517    #[test]
518    fn scancontrol_names_resolve_to_known_formats() {
519        let formats = [
520            ("Mono10", PixelFormat::Mono10),
521            ("Confidence8", PixelFormat::Confidence8),
522            ("Coord3D_C32f", PixelFormat::Coord3DC32f),
523            ("Coord3D_AC16", PixelFormat::Coord3DAC16),
524            ("Coord3D_AC32f", PixelFormat::Coord3DAC32f),
525            ("Coord3D_ABC32f", PixelFormat::Coord3DABC32f),
526        ];
527
528        for (name, format) in formats {
529            assert_eq!(PixelFormat::from_name(name), format);
530            assert_eq!(format.to_string(), name);
531        }
532    }
533
534    /// Every name and code below is copied from EMVA's "GenICam Pixel Format
535    /// Names and Values" (7 October 2025), the table PFNC 2.4 Appendix C
536    /// points to. A name must map to its code and the code back to the name.
537    #[test]
538    fn names_and_codes_match_the_emva_values_table() {
539        for (name, code) in [
540            ("Mono10p", 0x010A_0046_u32),
541            ("Mono12p", 0x010C_0047),
542            ("Mono10Packed", 0x010C_0004),
543            ("Mono12Packed", 0x010C_0006),
544            ("BayerGR10", 0x0110_000C),
545            ("BayerRG10", 0x0110_000D),
546            ("BayerGB10", 0x0110_000E),
547            ("BayerBG10", 0x0110_000F),
548            ("BayerGR12", 0x0110_0010),
549            ("BayerRG12", 0x0110_0011),
550            ("BayerGB12", 0x0110_0012),
551            ("BayerBG12", 0x0110_0013),
552            ("BayerGR16", 0x0110_002E),
553            ("BayerRG16", 0x0110_002F),
554            ("BayerGB16", 0x0110_0030),
555            ("BayerBG16", 0x0110_0031),
556            ("BayerGR10Packed", 0x010C_0026),
557            ("BayerRG10Packed", 0x010C_0027),
558            ("BayerGB10Packed", 0x010C_0028),
559            ("BayerBG10Packed", 0x010C_0029),
560            ("BayerGR12Packed", 0x010C_002A),
561            ("BayerRG12Packed", 0x010C_002B),
562            ("BayerGB12Packed", 0x010C_002C),
563            ("BayerBG12Packed", 0x010C_002D),
564            ("BayerBG10p", 0x010A_0052),
565            ("BayerBG12p", 0x010C_0053),
566            ("BayerGB10p", 0x010A_0054),
567            ("BayerGB12p", 0x010C_0055),
568            ("BayerGR10p", 0x010A_0056),
569            ("BayerGR12p", 0x010C_0057),
570            ("BayerRG10p", 0x010A_0058),
571            ("BayerRG12p", 0x010C_0059),
572            ("RGBa8", 0x0220_0016),
573            ("BGRa8", 0x0220_0017),
574            ("YUV411_8_UYYVYY", 0x020C_001E),
575            ("YUV422_8_UYVY", 0x0210_001F),
576            ("YUV422_8", 0x0210_0032),
577            ("YCbCr422_8", 0x0210_003B),
578            ("YCbCr422_8_CbYCrY", 0x0210_0043),
579            ("YUV8_UYV", 0x0218_0020),
580            ("YCbCr8_CbYCr", 0x0218_003A),
581            ("YCbCr8", 0x0218_005B),
582            ("Coord3D_C16", 0x0110_00B8),
583        ] {
584            assert_eq!(PixelFormat::from_name(name).code(), code, "{name}");
585            assert_eq!(
586                PixelFormat::from_code(code).to_string(),
587                name,
588                "{code:#010X}"
589            );
590        }
591    }
592
593    /// The Bayer 16-bit variants carried the codes of BayerGB10, BayerBG10,
594    /// BayerGR12 and BayerRG12, so a BayerGB10 camera was read as BayerGR16:
595    /// the wrong mosaic, drawn six bits too dark.
596    #[test]
597    fn bayer16_codes_are_not_the_bayer10_and_12_codes() {
598        assert_eq!(PixelFormat::BayerGR16.code(), 0x0110_002E);
599        assert_eq!(PixelFormat::BayerRG16.code(), 0x0110_002F);
600        assert_eq!(PixelFormat::BayerGB16.code(), 0x0110_0030);
601        assert_eq!(PixelFormat::BayerBG16.code(), 0x0110_0031);
602        assert_eq!(PixelFormat::from_code(0x0110_000E).to_string(), "BayerGB10");
603        assert_eq!(PixelFormat::from_code(0x0110_0011).to_string(), "BayerRG12");
604    }
605
606    /// The names cameras actually use for the same codes: the GigE Vision 1.x
607    /// spellings SFNC kept, found in the vendor XML corpus (`YUV422Packed` in
608    /// 23 of 38 documents, `RGB8Packed` in 23).
609    #[test]
610    fn legacy_names_resolve_to_the_pfnc_codes() {
611        for (name, code) in [
612            ("YUV422Packed", 0x0210_001F_u32),
613            ("YUV422_YUYV_Packed", 0x0210_0032),
614            ("YUV411Packed", 0x020C_001E),
615            ("YUV444Packed", 0x0218_0020),
616            ("RGBA8Packed", 0x0220_0016),
617            ("BGRA8Packed", 0x0220_0017),
618            ("RGB8Packed", 0x0218_0014),
619            ("BGR8Packed", 0x0218_0015),
620        ] {
621            assert_eq!(PixelFormat::from_name(name).code(), code, "{name}");
622        }
623    }
624
625    /// PFNC 2.4 §3.1.7, Figures 3-7 to 3-14: the two letters after `Bayer`
626    /// are the top row of the 2×2 tile, whatever the depth or packing.
627    #[test]
628    fn cfa_offsets_align_to_rggb() {
629        use PixelFormat as P;
630        for (formats, offsets) in [
631            (
632                [P::BayerRG8, P::BayerRG10, P::BayerRG12, P::BayerRG16],
633                ("RGGB", 0, 0),
634            ),
635            (
636                [P::BayerGR8, P::BayerGR10, P::BayerGR12, P::BayerGR16],
637                ("RGGB", 1, 0),
638            ),
639            (
640                [P::BayerGB8, P::BayerGB10, P::BayerGB12, P::BayerGB16],
641                ("RGGB", 0, 1),
642            ),
643            (
644                [P::BayerBG8, P::BayerBG10, P::BayerBG12, P::BayerBG16],
645                ("RGGB", 1, 1),
646            ),
647            (
648                [
649                    P::BayerRG10p,
650                    P::BayerRG12p,
651                    P::BayerRG10Packed,
652                    P::BayerRG12Packed,
653                ],
654                ("RGGB", 0, 0),
655            ),
656            (
657                [
658                    P::BayerGR10p,
659                    P::BayerGR12p,
660                    P::BayerGR10Packed,
661                    P::BayerGR12Packed,
662                ],
663                ("RGGB", 1, 0),
664            ),
665            (
666                [
667                    P::BayerGB10p,
668                    P::BayerGB12p,
669                    P::BayerGB10Packed,
670                    P::BayerGB12Packed,
671                ],
672                ("RGGB", 0, 1),
673            ),
674            (
675                [
676                    P::BayerBG10p,
677                    P::BayerBG12p,
678                    P::BayerBG10Packed,
679                    P::BayerBG12Packed,
680                ],
681                ("RGGB", 1, 1),
682            ),
683        ] {
684            for format in formats {
685                assert_eq!(format.cfa_pattern(), Some(offsets), "{format}");
686                assert!(format.is_bayer() && !format.is_mono(), "{format}");
687            }
688        }
689        assert_eq!(P::Mono8.cfa_pattern(), None);
690        assert_eq!(P::Mono12Packed.cfa_pattern(), None);
691        // Every named Bayer format has a pattern.
692        for &format in P::ALL {
693            assert_eq!(
694                format.is_bayer(),
695                format.to_string().starts_with("Bayer"),
696                "{format}"
697            );
698        }
699    }
700
701    /// Bits 23-16 of the code (PFNC values table): the container a packed
702    /// format fills, 16 for a 12-bit pixel padded to two bytes.
703    #[test]
704    fn bits_per_pixel_is_the_size_field_of_the_code() {
705        use PixelFormat as P;
706        for (format, bits) in [
707            (P::Mono8, 8),
708            (P::Mono10p, 10),
709            (P::Mono12p, 12),
710            (P::Mono10Packed, 12),
711            (P::Mono12Packed, 12),
712            (P::Mono12, 16),
713            (P::BayerRG12Packed, 12),
714            (P::YUV411_8_UYYVYY, 12),
715            (P::YUV422_8, 16),
716            (P::RGB8Packed, 24),
717            (P::RGBa8, 32),
718        ] {
719            assert_eq!(format.bits_per_pixel(), Some(bits), "{format}");
720        }
721        assert_eq!(P::Unknown(0).bits_per_pixel(), None);
722        assert_eq!(P::from_code(0x0110_FFFF).bits_per_pixel(), Some(16));
723    }
724
725    /// A line of `width` pixels, its last packing group completed with zero
726    /// components (PFNC 2.4 §6.7). Groups: §6.3.1 packs "as many components
727    /// such that no padding bit is required" — 4 for 10p, 2 for 12p; GigE
728    /// Vision's 10/12Packed put 2 pixels in 3 bytes; 4:2:2 carries 2 pixels
729    /// per Cb/Cr pair (§3.1.3), 4:1:1 four (§3.1.4).
730    #[test]
731    fn line_bytes_complete_the_last_packing_group() {
732        use PixelFormat as P;
733        for (format, width, bytes) in [
734            (P::Mono8, 7, 7),
735            (P::Mono12, 3, 6),
736            (P::RGB8Packed, 2, 6),
737            (P::Mono10p, 4, 5),
738            (P::Mono10p, 8, 10),
739            (P::Mono10p, 1, 5),
740            (P::Mono10p, 5, 10),
741            (P::Mono12p, 2, 3),
742            (P::Mono12p, 3, 6),
743            (P::Mono12Packed, 640, 960),
744            (P::Mono12Packed, 1, 3),
745            (P::Mono10Packed, 2, 3),
746            (P::BayerGR10p, 4, 5),
747            (P::YUV422_8_UYVY, 2, 4),
748            (P::YUV422_8, 3, 8),
749            (P::YUV411_8_UYYVYY, 4, 6),
750            (P::YUV411_8_UYYVYY, 5, 12),
751            (P::YUV8_UYV, 3, 9),
752        ] {
753            assert_eq!(format.line_bytes(width), Some(bytes), "{format} × {width}");
754        }
755    }
756
757    /// The image as one run of pixels (PFNC 2.4 §6.7, image padding): only the
758    /// last group is completed, not every line's.
759    #[test]
760    fn image_bytes_complete_only_the_last_group() {
761        use PixelFormat as P;
762        for (format, width, height, bytes) in [
763            (P::Mono8, 640, 480, 307_200),
764            (P::Mono16, 640, 480, 614_400),
765            (P::Mono12Packed, 640, 480, 460_800),
766            (P::Mono12p, 640, 480, 460_800),
767            (P::Mono10p, 640, 480, 384_000),
768            (P::Mono10p, 2, 2, 5),
769            (P::Mono10p, 3, 3, 15),
770            (P::Mono12p, 3, 1, 6),
771            (P::YUV422_8, 640, 480, 614_400),
772            (P::YUV422_8, 3, 1, 8),
773            (P::Coord3DABC32f, 1280, 1, 15_360),
774        ] {
775            assert_eq!(
776                format.image_bytes(width, height),
777                Some(bytes),
778                "{format} {width}×{height}"
779            );
780        }
781        // Event blocks have no image geometry.
782        assert_eq!(P::VendorLucidEvsEvt30.image_bytes(1, 64_000), None);
783        assert_eq!(P::VendorLucidEvsEvt21.image_bytes(1, 64_000), None);
784        assert_eq!(P::Unknown(0).image_bytes(4, 4), None);
785        // An unknown code is sized from its own size field.
786        assert_eq!(P::from_code(0x010C_FFFF).image_bytes(2, 1), Some(3));
787    }
788
789    #[test]
790    fn image_bytes_refuse_to_overflow() {
791        assert_eq!(
792            PixelFormat::Coord3DABC32f.image_bytes(u32::MAX, u32::MAX),
793            None
794        );
795    }
796}