Skip to main content

viva_pfnc/
convert.rs

1//! Turning a frame's bytes into samples: unpack, normalise, demosaic,
2//! colour-convert.
3//!
4//! The one implementation of pixel conversion in the project: the library's
5//! `Frame::to_rgb8` and image writer, and Viva Studio's viewer, all call it.
6//! No I/O, no dependencies; it compiles for `wasm32-unknown-unknown`.
7//!
8//! # What each step does
9//!
10//! - **Unpack** ([`unpack_u16`]) reads a single-component format — `Mono*`
11//!   or `Bayer*` — into one `u16` per pixel holding the camera's value:
12//!   lsb-unpacked formats from their little-endian bytes (PFNC 2.4 §6.1.1),
13//!   `10p`/`12p` as an lsb-first bit stream (§6.3.1), and the GigE Vision 2.0
14//!   `10Packed`/`12Packed` formats from their two-pixels-in-three-bytes layout
15//!   (see [`PixelFormat::Mono12Packed`]).
16//! - **Normalise to 8 bits** keeps a sample's top eight bits: `v >> (bits − 8)`.
17//! - **Demosaic** is bilinear: each missing colour is the truncated integer
18//!   mean of the two or four nearest samples of that colour, and a neighbour
19//!   outside the image is replaced by the nearest sample inside it
20//!   (clamp-to-edge), so the outermost row and column mix in the wrong colour.
21//!   It is the kernel Viva Studio's viewer used before this module, a preview
22//!   quality demosaic, not an ISP. To 8 bits, the mosaic is normalised first
23//!   and then demosaiced; at full depth it is demosaiced at its own depth.
24//! - **Y'CbCr to RGB** uses the full-range equations of PFNC 2.4 §8.2.1,
25//!   rounded and clamped to 0-255. PFNC calls the legacy `YUV` formats
26//!   Y'CbCr with U and V offset by 128 (Table 3-1) and gives them no
27//!   equations of their own, so they get the same ones. A 4:2:2 or 4:1:1
28//!   pixel uses the Cb/Cr of its group.
29//! - **RGB family**: `BGR` is reordered and an alpha byte dropped.
30//!
31//! ```
32//! use viva_pfnc::PixelFormat;
33//! use viva_pfnc::convert::{self, Converter};
34//!
35//! // Two 12-bit pixels, 0xABC and 0x123, in the GigE Vision layout.
36//! let bytes = [0xAB, 0x3C, 0x12];
37//! let samples = convert::unpack_u16(PixelFormat::Mono12Packed, 2, 1, None, &bytes)?;
38//! assert_eq!(samples, [0xABC, 0x123]);
39//!
40//! // For display: the top eight bits, through buffers kept between frames.
41//! let mut converter = Converter::new();
42//! let grey = converter.gray8(PixelFormat::Mono12Packed, 2, 1, None, &bytes)?;
43//! assert_eq!(grey, [0xAB, 0x12]);
44//! # Ok::<(), convert::ConvertError>(())
45//! ```
46//!
47//! # Geometry
48//!
49//! Without a row stride, pixels are read as one continuous run from the
50//! first line to the last — PFNC 2.4 §6.7's *image padding*. A bit-packed
51//! payload must hold the bytes up to its last pixel's: ⌈pixels × bits / 8⌉
52//! for an lsb-packed one (`…p`), and for GigE Vision's `…Packed`, two pixels
53//! in three bytes whatever their bits, every whole group and a lone last
54//! pixel's first two bytes. Any other must hold at least
55//! [`PixelFormat::image_bytes`]; bytes past that are ignored. §6.7 completes
56//! the packing group the image ends inside, but an Allied Vision Manta
57//! G-125B does not: at 1291 × 963 in `Mono12Packed`, an odd pixel count, it
58//! sends ⌈pixels × 12 / 8⌉ bytes, one short of the completed group. A payload
59//! with the group completed decodes the same.
60//!
61//! With a row stride — a camera that sends bytes after every line, as the
62//! GVSP image leader's `padding_x` declares — each line is decoded on its
63//! own: [`PixelFormat::line_bytes`] of pixels, a packing group the line ends
64//! inside completed (§6.7 *line padding*), then the next line `row_stride`
65//! bytes after the start of this one.
66//!
67//! The two readings differ only when a line ends inside a packing group (an
68//! odd width in `12p`, say). PFNC leaves the choice to the transport
69//! standard. The Manta G-125B declares no padding at an odd width in
70//! `Mono12Packed` and runs its pixels on, which is the first reading; how a
71//! camera that declares `padding_x` counts the group its line ends inside is
72//! open (backlog PX-05).
73
74use core::fmt;
75
76use crate::PixelFormat;
77
78/// Why a frame could not be converted.
79#[derive(Debug, Clone, PartialEq, Eq)]
80#[non_exhaustive]
81pub enum ConvertError {
82    /// The format has no conversion here (`Coord3D_*`, `Confidence8`,
83    /// event streams, codes this crate does not name).
84    Unsupported(PixelFormat),
85    /// The payload is shorter than the image it claims to be.
86    ShortPayload {
87        /// The frame's pixel format.
88        format: PixelFormat,
89        /// Bytes the geometry needs ([`PixelFormat::image_bytes`]).
90        expected: usize,
91        /// Bytes the payload has.
92        actual: usize,
93    },
94    /// The row stride is shorter than one line of the image.
95    StrideTooShort {
96        /// Bytes from one line to the next, as given.
97        stride: usize,
98        /// Bytes one line needs ([`PixelFormat::line_bytes`]).
99        line: usize,
100    },
101    /// `width × height` does not fit in memory.
102    TooLarge {
103        /// Frame width in pixels.
104        width: u32,
105        /// Frame height in pixels.
106        height: u32,
107    },
108}
109
110impl fmt::Display for ConvertError {
111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
112        match self {
113            ConvertError::Unsupported(format) => {
114                write!(f, "no conversion for pixel format {format}")
115            }
116            ConvertError::ShortPayload {
117                format,
118                expected,
119                actual,
120            } => write!(
121                f,
122                "{format} payload is {actual} bytes; the image needs {expected}"
123            ),
124            ConvertError::StrideTooShort { stride, line } => write!(
125                f,
126                "a row stride of {stride} bytes is shorter than a line, {line} bytes"
127            ),
128            ConvertError::TooLarge { width, height } => {
129                write!(f, "a {width}×{height} image does not fit in memory")
130            }
131        }
132    }
133}
134
135impl std::error::Error for ConvertError {}
136
137/// An image at the camera's own depth, as [`full_depth`] returns it.
138///
139/// 16-bit samples hold the camera's values, `0 ..= 2^bits − 1`, not scaled
140/// to 16 bits. Colour samples are interleaved R, G, B.
141#[derive(Debug, Clone, PartialEq, Eq)]
142#[non_exhaustive]
143pub enum Pixels {
144    /// One 8-bit sample per pixel.
145    Gray8(Vec<u8>),
146    /// One sample per pixel, `bits` of it significant.
147    Gray16 {
148        /// The camera's values.
149        samples: Vec<u16>,
150        /// The camera's bit depth, 9 to 16.
151        bits: u8,
152    },
153    /// Three 8-bit samples per pixel.
154    Rgb8(Vec<u8>),
155    /// Three samples per pixel, `bits` of each significant.
156    Rgb16 {
157        /// Demosaiced values at the camera's depth.
158        samples: Vec<u16>,
159        /// The camera's bit depth, 9 to 16.
160        bits: u8,
161    },
162}
163
164impl Pixels {
165    /// The same image in colour: grey samples are repeated into R, G and B;
166    /// colour is returned as it is.
167    pub fn into_rgb(self) -> Pixels {
168        fn triple<T: Copy>(gray: &[T]) -> Vec<T> {
169            gray.iter().flat_map(|&v| [v, v, v]).collect()
170        }
171        match self {
172            Pixels::Gray8(gray) => Pixels::Rgb8(triple(&gray)),
173            Pixels::Gray16 { samples, bits } => Pixels::Rgb16 {
174                samples: triple(&samples),
175                bits,
176            },
177            colour => colour,
178        }
179    }
180}
181
182/// Whether [`to_rgb8`] converts `format` — the formats a viewer can draw.
183pub fn supports(format: PixelFormat) -> bool {
184    layout(format).is_some()
185}
186
187/// The camera's sample values of a single-component format (`Mono*`,
188/// `Bayer*`), one per pixel, row-major. A Bayer mosaic is returned as it is.
189///
190/// `row_stride` is the distance in bytes from the start of one line to the
191/// next when the camera pads its lines; `None` reads the image as one run.
192/// The module's *Geometry* section says which is which.
193pub fn unpack_u16(
194    format: PixelFormat,
195    width: u32,
196    height: u32,
197    row_stride: Option<usize>,
198    src: &[u8],
199) -> Result<Vec<u16>, ConvertError> {
200    let rows = rows(format, width, height, row_stride, src)?;
201    let single = match layout(format) {
202        Some(Layout::Mono(single) | Layout::Bayer(single, _)) => single,
203        _ => return Err(ConvertError::Unsupported(format)),
204    };
205    let mut out = Vec::new();
206    unpack_rows(single, rows, &mut out);
207    Ok(out)
208}
209
210/// The frame as 8-bit RGB, three bytes per pixel.
211///
212/// Allocates its output; [`Converter::rgb8`] reuses buffers between frames.
213pub fn to_rgb8(
214    format: PixelFormat,
215    width: u32,
216    height: u32,
217    row_stride: Option<usize>,
218    src: &[u8],
219) -> Result<Vec<u8>, ConvertError> {
220    let mut out = Vec::new();
221    Converter::new().rgb8_into(format, width, height, row_stride, src, &mut out)?;
222    Ok(out)
223}
224
225/// The frame without losing depth: monochrome as grey, everything else as
226/// RGB, 16-bit when the camera's samples are wider than 8 bits — a Bayer
227/// mosaic demosaiced at its own depth.
228pub fn full_depth(
229    format: PixelFormat,
230    width: u32,
231    height: u32,
232    row_stride: Option<usize>,
233    src: &[u8],
234) -> Result<Pixels, ConvertError> {
235    let layout = layout(format).ok_or(ConvertError::Unsupported(format))?;
236    let rows = rows(format, width, height, row_stride, src)?;
237    let mut conv = Converter::new();
238    Ok(match layout {
239        Layout::Mono(single) if single.is_8_bit() => {
240            let mut scratch = Vec::new();
241            Pixels::Gray8(gather8(rows, &mut scratch).to_vec())
242        }
243        Layout::Mono(single) => {
244            let mut samples = Vec::new();
245            unpack_rows(single, rows, &mut samples);
246            Pixels::Gray16 {
247                samples,
248                bits: single.bits,
249            }
250        }
251        Layout::Bayer(single, offsets) if !single.is_8_bit() => {
252            unpack_rows(single, rows, &mut conv.samples);
253            let mut samples = Vec::new();
254            demosaic_bilinear(
255                &conv.samples,
256                width as usize,
257                height as usize,
258                offsets,
259                &mut samples,
260            );
261            Pixels::Rgb16 {
262                samples,
263                bits: single.bits,
264            }
265        }
266        _ => {
267            let mut out = Vec::new();
268            conv.rgb8_into(format, width, height, row_stride, src, &mut out)?;
269            Pixels::Rgb8(out)
270        }
271    })
272}
273
274/// Converts frames, keeping its buffers between them: after the first frame
275/// of a size, converting another allocates nothing.
276#[derive(Debug, Default, Clone)]
277pub struct Converter {
278    /// Unpacked samples.
279    samples: Vec<u16>,
280    /// An unpacked mosaic normalised to 8 bits.
281    mosaic: Vec<u8>,
282    /// The result handed out.
283    out: Vec<u8>,
284}
285
286impl Converter {
287    /// A converter with empty buffers.
288    pub fn new() -> Self {
289        Self::default()
290    }
291
292    /// A monochrome frame as 8-bit grey, one byte per pixel; `Mono8` without
293    /// line padding is lent back as it is. [`ConvertError::Unsupported`] for
294    /// anything else.
295    pub fn gray8<'a>(
296        &'a mut self,
297        format: PixelFormat,
298        width: u32,
299        height: u32,
300        row_stride: Option<usize>,
301        src: &'a [u8],
302    ) -> Result<&'a [u8], ConvertError> {
303        let Some(Layout::Mono(single)) = layout(format) else {
304            return Err(ConvertError::Unsupported(format));
305        };
306        let rows = rows(format, width, height, row_stride, src)?;
307        if single.is_8_bit() {
308            return Ok(gather8(rows, &mut self.out));
309        }
310        unpack_rows(single, rows, &mut self.samples);
311        narrow_into(&self.samples, single.bits, &mut self.out);
312        Ok(&self.out)
313    }
314
315    /// The frame as 8-bit RGB, three bytes per pixel; `RGB8` without line
316    /// padding is lent back as it is.
317    pub fn rgb8<'a>(
318        &'a mut self,
319        format: PixelFormat,
320        width: u32,
321        height: u32,
322        row_stride: Option<usize>,
323        src: &'a [u8],
324    ) -> Result<&'a [u8], ConvertError> {
325        if format == PixelFormat::RGB8Packed {
326            let rows = rows(format, width, height, row_stride, src)?;
327            if rows.count <= 1 {
328                return Ok(&rows.src[..rows.pixels * 3]);
329            }
330        }
331        let mut out = core::mem::take(&mut self.out);
332        let result = self.rgb8_into(format, width, height, row_stride, src, &mut out);
333        self.out = out;
334        result.map(|()| self.out.as_slice())
335    }
336
337    fn rgb8_into(
338        &mut self,
339        format: PixelFormat,
340        width: u32,
341        height: u32,
342        row_stride: Option<usize>,
343        src: &[u8],
344        out: &mut Vec<u8>,
345    ) -> Result<(), ConvertError> {
346        let layout = layout(format).ok_or(ConvertError::Unsupported(format))?;
347        let rows = rows(format, width, height, row_stride, src)?;
348        out.clear();
349        match layout {
350            Layout::Mono(single) => {
351                if single.is_8_bit() {
352                    for row in rows.iter() {
353                        out.extend(row[..rows.pixels].iter().flat_map(|&v| [v, v, v]));
354                    }
355                } else {
356                    unpack_rows(single, rows, &mut self.samples);
357                    let bits = single.bits;
358                    out.extend(self.samples.iter().flat_map(|&v| {
359                        let v = narrow(v, bits);
360                        [v, v, v]
361                    }));
362                }
363            }
364            Layout::Bayer(single, offsets) => {
365                let mosaic = if single.is_8_bit() {
366                    gather8(rows, &mut self.mosaic)
367                } else {
368                    unpack_rows(single, rows, &mut self.samples);
369                    narrow_into(&self.samples, single.bits, &mut self.mosaic);
370                    &self.mosaic[..]
371                };
372                demosaic_bilinear(mosaic, width as usize, height as usize, offsets, out);
373            }
374            Layout::Rgb(order) => {
375                let stride = order.stride();
376                let [r, g, b] = order.indices();
377                for row in rows.iter() {
378                    out.extend(
379                        row.chunks_exact(stride)
380                            .take(rows.pixels)
381                            .flat_map(|px| [px[r], px[g], px[b]]),
382                    );
383                }
384            }
385            Layout::Yuv(order) => {
386                out.reserve(rows.total() * 3);
387                for row in rows.iter() {
388                    yuv_append(order, rows.pixels, row, out);
389                }
390            }
391        }
392        Ok(())
393    }
394}
395
396/// Where an image's pixels lie in its payload: one run, or one line every
397/// `stride` bytes.
398#[derive(Clone, Copy)]
399struct Rows<'a> {
400    src: &'a [u8],
401    /// Pixels in a row: the whole image when it is one run.
402    pixels: usize,
403    /// Bytes holding a row's pixels.
404    bytes: usize,
405    stride: usize,
406    count: usize,
407}
408
409impl<'a> Rows<'a> {
410    fn iter(self) -> impl Iterator<Item = &'a [u8]> {
411        (0..self.count).map(move |y| &self.src[y * self.stride..][..self.bytes])
412    }
413
414    fn total(self) -> usize {
415        self.pixels * self.count
416    }
417}
418
419/// The rows of an image, or why its payload cannot hold them.
420///
421/// Without a stride the image is one run of `width × height` pixels (PFNC
422/// 2.4 §6.7 image padding). With one, each line holds `width` pixels, a
423/// packing group it ends inside completed (§6.7 line padding), and starts
424/// `stride` bytes after the previous one; the last needs no padding after it.
425fn rows(
426    format: PixelFormat,
427    width: u32,
428    height: u32,
429    row_stride: Option<usize>,
430    src: &[u8],
431) -> Result<Rows<'_>, ConvertError> {
432    let Some(stride) = row_stride else {
433        let (pixels, src) = geometry(format, width, height, src)?;
434        return Ok(Rows {
435            src,
436            pixels,
437            bytes: src.len(),
438            stride: src.len(),
439            count: 1,
440        });
441    };
442    let too_large = ConvertError::TooLarge { width, height };
443    (width as usize)
444        .checked_mul(height as usize)
445        .ok_or(too_large.clone())?;
446    let line = format.line_bytes(width).ok_or(too_large.clone())?;
447    if stride < line {
448        return Err(ConvertError::StrideTooShort { stride, line });
449    }
450    let expected = match (height as usize).checked_sub(1) {
451        None => 0,
452        Some(before_last) => stride
453            .checked_mul(before_last)
454            .and_then(|start| start.checked_add(line))
455            .ok_or(too_large)?,
456    };
457    if src.len() < expected {
458        return Err(ConvertError::ShortPayload {
459            format,
460            expected,
461            actual: src.len(),
462        });
463    }
464    Ok(Rows {
465        src,
466        pixels: width as usize,
467        bytes: line,
468        stride,
469        count: height as usize,
470    })
471}
472
473/// The 8-bit samples of `rows` in one slice: borrowed when the image is one
474/// run, gathered into `scratch` otherwise.
475fn gather8<'a>(rows: Rows<'a>, scratch: &'a mut Vec<u8>) -> &'a [u8] {
476    if rows.count <= 1 {
477        return &rows.src[..rows.total()];
478    }
479    scratch.clear();
480    for row in rows.iter() {
481        scratch.extend_from_slice(&row[..rows.pixels]);
482    }
483    scratch
484}
485
486/// Every row's samples, in order.
487fn unpack_rows(single: Single, rows: Rows<'_>, out: &mut Vec<u16>) {
488    out.clear();
489    out.reserve(rows.total());
490    for row in rows.iter() {
491        unpack_append(single, rows.pixels, row, out);
492    }
493}
494
495/// The pixel count and the bytes it occupies, or why not.
496fn geometry(
497    format: PixelFormat,
498    width: u32,
499    height: u32,
500    src: &[u8],
501) -> Result<(usize, &[u8]), ConvertError> {
502    let too_large = ConvertError::TooLarge { width, height };
503    let pixels = (width as usize)
504        .checked_mul(height as usize)
505        .ok_or(too_large.clone())?;
506    // Every format with a layout declares a size; `None` here is overflow.
507    let completed = format.image_bytes(width, height).ok_or(too_large.clone())?;
508    let expected = match layout(format) {
509        // A bit-packed run needs only the bytes up to its last pixel's: a
510        // camera may stop inside the last packing group (the module's
511        // *Geometry*). An lsb bit stream holds a pixel's bits end to end.
512        Some(Layout::Mono(single) | Layout::Bayer(single, _))
513            if matches!(single.packing, Packing::Lsb) =>
514        {
515            pixels
516                .checked_mul(usize::from(single.bits))
517                .ok_or(too_large)?
518                .div_ceil(8)
519        }
520        // GigE Vision's two pixels in three bytes, whatever their bits: the
521        // whole groups, and a lone last pixel's first two bytes.
522        Some(Layout::Mono(single) | Layout::Bayer(single, _))
523            if matches!(single.packing, Packing::Gige) =>
524        {
525            (pixels / 2)
526                .checked_mul(3)
527                .and_then(|whole| whole.checked_add(if pixels % 2 == 1 { 2 } else { 0 }))
528                .ok_or(too_large)?
529        }
530        _ => completed,
531    };
532    if src.len() < expected {
533        return Err(ConvertError::ShortPayload {
534            format,
535            expected,
536            actual: src.len(),
537        });
538    }
539    Ok((pixels, &src[..completed.min(src.len())]))
540}
541
542// ── Layouts ──────────────────────────────────────────────────────────────────
543
544/// How a format's bytes become samples.
545#[derive(Clone, Copy)]
546enum Layout {
547    Mono(Single),
548    /// The mosaic's offsets to RGGB, as [`PixelFormat::cfa_pattern`] gives.
549    Bayer(Single, (u8, u8)),
550    Rgb(RgbOrder),
551    Yuv(YuvOrder),
552}
553
554/// One component per pixel.
555#[derive(Clone, Copy)]
556struct Single {
557    bits: u8,
558    packing: Packing,
559}
560
561impl Single {
562    fn is_8_bit(self) -> bool {
563        self.bits == 8
564    }
565}
566
567#[derive(Clone, Copy)]
568enum Packing {
569    /// PFNC lsb unpacked: one byte, or two little-endian bytes.
570    Unpacked,
571    /// PFNC lsb packed (`p`): an lsb-first bit stream.
572    Lsb,
573    /// GigE Vision 2.0 `10Packed`/`12Packed`: two pixels in three bytes, the
574    /// eight msb of each in bytes 0 and 2, their lsb in the low and high
575    /// nibble of byte 1.
576    Gige,
577}
578
579#[derive(Clone, Copy)]
580enum RgbOrder {
581    Rgb,
582    Bgr,
583    Rgba,
584    Bgra,
585}
586
587impl RgbOrder {
588    fn stride(self) -> usize {
589        match self {
590            RgbOrder::Rgb | RgbOrder::Bgr => 3,
591            RgbOrder::Rgba | RgbOrder::Bgra => 4,
592        }
593    }
594
595    /// Where R, G and B sit in a pixel.
596    fn indices(self) -> [usize; 3] {
597        match self {
598            RgbOrder::Rgb | RgbOrder::Rgba => [0, 1, 2],
599            RgbOrder::Bgr | RgbOrder::Bgra => [2, 1, 0],
600        }
601    }
602}
603
604/// Byte order of a Y'CbCr group (U = Cb, V = Cr).
605#[derive(Clone, Copy)]
606enum YuvOrder {
607    /// 4:2:2, Y0 U Y1 V — PFNC's default 4:2:2 order (§3.1.3).
608    Yuyv,
609    /// 4:2:2, U Y0 V Y1.
610    Uyvy,
611    /// 4:1:1, U Y0 Y1 V Y2 Y3.
612    Uyyvyy,
613    /// 4:4:4, U Y V.
614    Uyv,
615    /// 4:4:4, Y U V.
616    Yuv,
617}
618
619fn layout(format: PixelFormat) -> Option<Layout> {
620    use PixelFormat as P;
621    let single = |bits, packing| Single { bits, packing };
622    let unpacked = |bits| single(bits, Packing::Unpacked);
623    let mono_or_bayer = |s: Single| match format.cfa_pattern() {
624        Some((_, x, y)) => Layout::Bayer(s, (x, y)),
625        None => Layout::Mono(s),
626    };
627    Some(match format {
628        P::Mono8 | P::BayerRG8 | P::BayerGR8 | P::BayerGB8 | P::BayerBG8 => {
629            mono_or_bayer(unpacked(8))
630        }
631        P::Mono10 | P::BayerRG10 | P::BayerGR10 | P::BayerGB10 | P::BayerBG10 => {
632            mono_or_bayer(unpacked(10))
633        }
634        P::Mono12 | P::BayerRG12 | P::BayerGR12 | P::BayerGB12 | P::BayerBG12 => {
635            mono_or_bayer(unpacked(12))
636        }
637        P::Mono14 => mono_or_bayer(unpacked(14)),
638        P::Mono16 | P::BayerRG16 | P::BayerGR16 | P::BayerGB16 | P::BayerBG16 => {
639            mono_or_bayer(unpacked(16))
640        }
641        P::Mono10p | P::BayerRG10p | P::BayerGR10p | P::BayerGB10p | P::BayerBG10p => {
642            mono_or_bayer(single(10, Packing::Lsb))
643        }
644        P::Mono12p | P::BayerRG12p | P::BayerGR12p | P::BayerGB12p | P::BayerBG12p => {
645            mono_or_bayer(single(12, Packing::Lsb))
646        }
647        P::Mono10Packed
648        | P::BayerRG10Packed
649        | P::BayerGR10Packed
650        | P::BayerGB10Packed
651        | P::BayerBG10Packed => mono_or_bayer(single(10, Packing::Gige)),
652        P::Mono12Packed
653        | P::BayerRG12Packed
654        | P::BayerGR12Packed
655        | P::BayerGB12Packed
656        | P::BayerBG12Packed => mono_or_bayer(single(12, Packing::Gige)),
657        P::RGB8Packed => Layout::Rgb(RgbOrder::Rgb),
658        P::BGR8Packed => Layout::Rgb(RgbOrder::Bgr),
659        P::RGBa8 => Layout::Rgb(RgbOrder::Rgba),
660        P::BGRa8 => Layout::Rgb(RgbOrder::Bgra),
661        P::YUV422_8 | P::YCbCr422_8 => Layout::Yuv(YuvOrder::Yuyv),
662        P::YUV422_8_UYVY | P::YCbCr422_8_CbYCrY => Layout::Yuv(YuvOrder::Uyvy),
663        P::YUV411_8_UYYVYY => Layout::Yuv(YuvOrder::Uyyvyy),
664        P::YUV8_UYV | P::YCbCr8_CbYCr => Layout::Yuv(YuvOrder::Uyv),
665        P::YCbCr8 => Layout::Yuv(YuvOrder::Yuv),
666        _ => return None,
667    })
668}
669
670// ── Unpacking and normalising ────────────────────────────────────────────────
671
672/// Append `pixels` samples of `src`, which [`rows`] has sized.
673fn unpack_append(single: Single, pixels: usize, src: &[u8], out: &mut Vec<u16>) {
674    let start = out.len();
675    out.reserve(pixels);
676    match single.packing {
677        Packing::Unpacked if single.is_8_bit() => {
678            out.extend(src[..pixels].iter().map(|&v| u16::from(v)));
679        }
680        Packing::Unpacked => {
681            out.extend(
682                src.as_chunks::<2>().0[..pixels]
683                    .iter()
684                    .map(|pair| u16::from_le_bytes(*pair)),
685            );
686        }
687        Packing::Lsb => {
688            let bits = u32::from(single.bits);
689            let mask = (1u32 << bits) - 1;
690            let (mut acc, mut held) = (0u32, 0u32);
691            let mut bytes = src.iter();
692            for _ in 0..pixels {
693                while held < bits {
694                    acc |= u32::from(bytes.next().copied().unwrap_or(0)) << held;
695                    held += 8;
696                }
697                out.push((acc & mask) as u16);
698                acc >>= bits;
699                held -= bits;
700            }
701        }
702        Packing::Gige => {
703            let shift = single.bits - 8;
704            let mask = (1u16 << shift) - 1;
705            let (groups, tail) = src.as_chunks::<3>();
706            for &[msb0, lsb, msb1] in groups {
707                out.push((u16::from(msb0) << shift) | (u16::from(lsb) & mask));
708                out.push((u16::from(msb1) << shift) | ((u16::from(lsb) >> 4) & mask));
709            }
710            // A run that stops inside its last group: that group's first
711            // pixel, from its eight msb and the low nibble after them.
712            if let &[msb0, lsb, ..] = tail {
713                out.push((u16::from(msb0) << shift) | (u16::from(lsb) & mask));
714            }
715            // A completed last group carries one pixel too many.
716            out.truncate(start + pixels);
717        }
718    }
719}
720
721/// A sample's top eight bits.
722fn narrow(value: u16, bits: u8) -> u8 {
723    // A camera that sets padding bits would overflow; saturate rather than wrap.
724    (value >> (bits - 8)).min(0xFF) as u8
725}
726
727fn narrow_into(samples: &[u16], bits: u8, out: &mut Vec<u8>) {
728    out.clear();
729    out.extend(samples.iter().map(|&v| narrow(v, bits)));
730}
731
732// ── Demosaicing ──────────────────────────────────────────────────────────────
733
734/// A sample type the demosaic averages in `u32`.
735trait Sample: Copy + Default {
736    fn widen(self) -> u32;
737    /// `value` is a mean of samples, so it fits.
738    fn narrow(value: u32) -> Self;
739}
740
741impl Sample for u8 {
742    fn widen(self) -> u32 {
743        u32::from(self)
744    }
745    fn narrow(value: u32) -> Self {
746        value as u8
747    }
748}
749
750impl Sample for u16 {
751    fn widen(self) -> u32 {
752        u32::from(self)
753    }
754    fn narrow(value: u32) -> Self {
755        value as u16
756    }
757}
758
759/// Bilinear demosaic of a `width × height` mosaic whose pixel `(x, y)` has
760/// the colour RGGB has at `(x + offsets.0, y + offsets.1)`. See the module
761/// documentation for the edge rule.
762fn demosaic_bilinear<T: Sample>(
763    mosaic: &[T],
764    width: usize,
765    height: usize,
766    (x_offset, y_offset): (u8, u8),
767    out: &mut Vec<T>,
768) {
769    out.clear();
770    out.resize(width * height * 3, T::default());
771    if width == 0 || height == 0 {
772        return;
773    }
774    let row = |y: usize| &mosaic[y * width..][..width];
775    for y in 0..height {
776        let (above, here, below) = (
777            row(y.saturating_sub(1)),
778            row(y),
779            row((y + 1).min(height - 1)),
780        );
781        let y_site = (y + usize::from(y_offset)) & 1;
782        for x in 0..width {
783            let (left, right) = (x.saturating_sub(1), (x + 1).min(width - 1));
784            let at = |line: &[T], i: usize| line[i].widen();
785            let centre = at(here, x);
786            let horizontal = || (at(here, left) + at(here, right)) / 2;
787            let vertical = || (at(above, x) + at(below, x)) / 2;
788            let cross = || (at(here, left) + at(here, right) + at(above, x) + at(below, x)) / 4;
789            let diagonal =
790                || (at(above, left) + at(above, right) + at(below, left) + at(below, right)) / 4;
791            let (r, g, b) = match ((x + usize::from(x_offset)) & 1, y_site) {
792                // Red site.
793                (0, 0) => (centre, cross(), diagonal()),
794                // Green between reds (left/right) and blues (above/below).
795                (1, 0) => (horizontal(), centre, vertical()),
796                // Green between blues (left/right) and reds (above/below).
797                (0, 1) => (vertical(), centre, horizontal()),
798                // Blue site.
799                _ => (diagonal(), cross(), centre),
800            };
801            let px = &mut out[(y * width + x) * 3..][..3];
802            px.copy_from_slice(&[T::narrow(r), T::narrow(g), T::narrow(b)]);
803        }
804    }
805}
806
807// ── Y'CbCr ───────────────────────────────────────────────────────────────────
808
809/// PFNC 2.4 §8.2.1, generic full-scale Y'CbCr to R'G'B' (8-bit):
810/// R' = Y' + 1.402 (Cr − 128), G' = Y' − 0.34414 (Cb − 128) − 0.71414 (Cr − 128),
811/// B' = Y' + 1.772 (Cb − 128), rounded and clamped to 0-255.
812fn ycbcr_to_rgb(y: u8, cb: u8, cr: u8) -> [u8; 3] {
813    let y = f32::from(y);
814    let cb = f32::from(cb) - 128.0;
815    let cr = f32::from(cr) - 128.0;
816    let channel = |v: f32| v.round().clamp(0.0, 255.0) as u8;
817    [
818        channel(y + 1.402 * cr),
819        channel(y - 0.34414 * cb - 0.71414 * cr),
820        channel(y + 1.772 * cb),
821    ]
822}
823
824/// Append `pixels` pixels of `src` as RGB.
825fn yuv_append(order: YuvOrder, pixels: usize, src: &[u8], out: &mut Vec<u8>) {
826    let start = out.len();
827    // (bytes per group, the luma offsets, the Cb offset, the Cr offset)
828    let (group, lumas, cb, cr): (usize, &[usize], usize, usize) = match order {
829        YuvOrder::Yuyv => (4, &[0, 2], 1, 3),
830        YuvOrder::Uyvy => (4, &[1, 3], 0, 2),
831        YuvOrder::Uyyvyy => (6, &[1, 2, 4, 5], 0, 3),
832        YuvOrder::Uyv => (3, &[1], 0, 2),
833        YuvOrder::Yuv => (3, &[0], 1, 2),
834    };
835    out.reserve(pixels * 3);
836    for chunk in src.chunks_exact(group) {
837        for &luma in lumas {
838            out.extend_from_slice(&ycbcr_to_rgb(chunk[luma], chunk[cb], chunk[cr]));
839        }
840    }
841    // A completed last group carries pixels past the image.
842    out.truncate(start + pixels * 3);
843}
844
845#[cfg(test)]
846mod tests {
847    use super::*;
848    use crate::PixelFormat as P;
849
850    fn unpack(format: P, width: u32, height: u32, src: &[u8]) -> Vec<u16> {
851        unpack_u16(format, width, height, None, src).unwrap()
852    }
853
854    // ── Unpacking: golden vectors from the standards ─────────────────────────
855
856    /// PFNC 2.4 §6.1.1, Figures 6-2 and 6-3: lsb unpacked, the sample in the
857    /// low bits of two little-endian bytes.
858    #[test]
859    fn mono10_and_mono12_are_lsb_aligned_in_two_bytes() {
860        assert_eq!(unpack(P::Mono10, 1, 1, &[0xA5, 0x02]), [0x2A5]);
861        assert_eq!(
862            unpack(P::Mono12, 2, 1, &[0xBC, 0x0A, 0x23, 0x01]),
863            [0xABC, 0x123]
864        );
865        assert_eq!(unpack(P::Mono16, 1, 1, &[0x34, 0x12]), [0x1234]);
866        assert_eq!(unpack(P::Mono8, 2, 1, &[7, 250]), [7, 250]);
867    }
868
869    /// PFNC 2.4 §6.3.1, Figure 6-9 (Mono10p): byte 0 holds L1 bits 7-0;
870    /// byte 1 L2 bits 5-0 over L1 bits 9-8; byte 2 L3 bits 3-0 over L2 bits
871    /// 9-6; byte 3 L4 bits 1-0 over L3 bits 9-4; byte 4 L4 bits 9-2.
872    #[test]
873    fn mono10p_follows_figure_6_9() {
874        // L1 = 0x2A5, L2 = 0x15A, L3 = 0x0F0, L4 = 0x30F.
875        let bytes = [0xA5, 0x6A, 0x05, 0xCF, 0xC3];
876        assert_eq!(
877            unpack(P::Mono10p, 4, 1, &bytes),
878            [0x2A5, 0x15A, 0x0F0, 0x30F]
879        );
880        assert_eq!(
881            unpack(P::BayerRG10p, 2, 2, &bytes),
882            [0x2A5, 0x15A, 0x0F0, 0x30F]
883        );
884    }
885
886    /// PFNC 2.4 §6.3.1, "lsb Packed" construction rules: the first
887    /// component's bit 0 is bit 0 of byte 0, the next component is appended
888    /// from its own lsb. For 12 bits: byte 0 = L1 bits 7-0, byte 1 = L2 bits
889    /// 3-0 over L1 bits 11-8, byte 2 = L2 bits 11-4.
890    #[test]
891    fn mono12p_is_lsb_packed() {
892        let bytes = [0xBC, 0x3A, 0x12];
893        assert_eq!(unpack(P::Mono12p, 2, 1, &bytes), [0xABC, 0x123]);
894        assert_eq!(unpack(P::BayerGB12p, 2, 1, &bytes), [0xABC, 0x123]);
895    }
896
897    /// GigE Vision 2.0 Mono12Packed, as Teledyne FLIR documents it (the GigE
898    /// Vision text is not public; the EMVA values table assigns the code to
899    /// it): "The first byte … contains the eight msb of the first pixel. The
900    /// third byte contains the eight msb of the second pixel. The four lsb of
901    /// the second byte contains four lsb of the first pixel, and the rest of
902    /// the second byte is packed with the four lsb of the second pixel."
903    #[test]
904    fn mono12packed_is_the_gige_vision_layout() {
905        let bytes = [0xAB, 0x3C, 0x12];
906        assert_eq!(unpack(P::Mono12Packed, 2, 1, &bytes), [0xABC, 0x123]);
907        // The same source says the Bayer*12Packed formats share the layout.
908        assert_eq!(unpack(P::BayerBG12Packed, 2, 1, &bytes), [0xABC, 0x123]);
909    }
910
911    /// GigE Vision 2.0 Mono10Packed, same source: bytes 0 and 2 hold the eight
912    /// msb of the two pixels; bits 1-0 of byte 1 the first pixel's two lsb,
913    /// bits 5-4 the second's; the remaining bits are zero.
914    #[test]
915    fn mono10packed_is_the_gige_vision_layout() {
916        let bytes = [0xA9, 0x21, 0x56];
917        assert_eq!(unpack(P::Mono10Packed, 2, 1, &bytes), [0x2A5, 0x15A]);
918        assert_eq!(unpack(P::BayerGR10Packed, 2, 1, &bytes), [0x2A5, 0x15A]);
919    }
920
921    /// The reason a round trip proves nothing: the two 12-bit packings read
922    /// the same three bytes as different pixels.
923    #[test]
924    fn the_two_12_bit_packings_disagree_on_the_same_bytes() {
925        let bytes = [0xAB, 0x3C, 0x12];
926        assert_eq!(unpack(P::Mono12p, 2, 1, &bytes), [0xCAB, 0x123]);
927        assert_ne!(
928            unpack(P::Mono12p, 2, 1, &bytes),
929            unpack(P::Mono12Packed, 2, 1, &bytes)
930        );
931    }
932
933    /// An image that ends inside a packing group needs only the bytes its
934    /// pixels' bits fill. PFNC 2.4 §6.7 completes the group with zero
935    /// components, but an Allied Vision Manta G-125B at 1291 × 963 in
936    /// `Mono12Packed` — 1 243 233 pixels, an odd count — gave `PayloadSize`
937    /// 1 864 850 and sent frames of that length: ⌈1 243 233 × 12 / 8⌉, one
938    /// byte short of the completed group. A completed group still decodes.
939    #[test]
940    fn a_partial_last_group_needs_only_its_pixels_bits() {
941        // The last pixel's eight msb, then its four lsb in the next byte.
942        let manta = [0xAB, 0x3C, 0x12, 0x45, 0x06];
943        assert_eq!(unpack(P::Mono12Packed, 3, 1, &manta), [0xABC, 0x123, 0x456]);
944        assert_eq!(
945            unpack(P::Mono12Packed, 3, 1, &[0xAB, 0x3C, 0x12, 0x45, 0x06, 0x00]),
946            [0xABC, 0x123, 0x456],
947            "the group completed"
948        );
949        assert_eq!(unpack(P::Mono12p, 1, 1, &[0xBC, 0x0A]), [0xABC]);
950        assert_eq!(unpack(P::Mono12p, 1, 1, &[0xBC, 0x0A, 0x00]), [0xABC]);
951        assert_eq!(
952            unpack_u16(P::Mono12Packed, 3, 1, None, &manta[..4]),
953            Err(ConvertError::ShortPayload {
954                format: P::Mono12Packed,
955                expected: 5,
956                actual: 4
957            })
958        );
959        // The Manta's own geometry, through every conversion.
960        let (width, height) = (1291, 963);
961        let src = vec![0x80; 1_864_850];
962        let mut conv = Converter::new();
963        assert_eq!(
964            conv.gray8(P::Mono12Packed, width, height, None, &src)
965                .map(<[u8]>::len),
966            Ok(1_243_233)
967        );
968        assert!(to_rgb8(P::Mono12Packed, width, height, None, &src).is_ok());
969    }
970
971    /// GigE Vision's `10Packed` puts two 10-bit pixels in three bytes, four
972    /// bits unused, so a pixel count's bits are not its bytes: 4 pixels take
973    /// 6 bytes, not ⌈4 × 10 / 8⌉ = 5. Five bytes are short (backlog PX-07:
974    /// three samples came back, and a Bayer conversion read past the end
975    /// and panicked); the last pixel of an odd count needs its group's first
976    /// two bytes, as the Manta's `Mono12Packed` frame has.
977    #[test]
978    fn a_gige_packed_group_is_counted_whole_up_to_its_last_pixel() {
979        assert_eq!(
980            unpack_u16(P::Mono10Packed, 4, 1, None, &[0; 5]),
981            Err(ConvertError::ShortPayload {
982                format: P::Mono10Packed,
983                expected: 6,
984                actual: 5
985            })
986        );
987        assert_eq!(unpack(P::Mono10Packed, 4, 1, &[0; 6]).len(), 4);
988        // An odd count: one group and the first two bytes of the next.
989        assert_eq!(unpack(P::Mono10Packed, 3, 1, &[0; 5]).len(), 3);
990        assert_eq!(
991            unpack_u16(P::Mono10Packed, 3, 1, None, &[0; 4]),
992            Err(ConvertError::ShortPayload {
993                format: P::Mono10Packed,
994                expected: 5,
995                actual: 4
996            })
997        );
998    }
999
1000    /// The same short `10Packed` payload through a Bayer conversion, which
1001    /// indexed past its end and panicked (PX-07).
1002    #[test]
1003    fn a_short_gige_packed_bayer_image_is_refused_not_read_past() {
1004        assert_eq!(
1005            to_rgb8(P::BayerRG10Packed, 2, 2, None, &[0; 5]),
1006            Err(ConvertError::ShortPayload {
1007                format: P::BayerRG10Packed,
1008                expected: 6,
1009                actual: 5
1010            })
1011        );
1012        assert!(to_rgb8(P::BayerRG10Packed, 2, 2, None, &[0; 6]).is_ok());
1013    }
1014
1015    /// A GVSP image leader declares `padding_x` bytes after every line
1016    /// (Codex review of #196): with a row stride each line starts where it
1017    /// says, not where the previous one's pixels ended.
1018    #[test]
1019    fn padded_lines_are_read_from_their_own_start() {
1020        // Mono8, 3 × 2, two bytes of padding after each line.
1021        let src = [1, 2, 3, 0xEE, 0xEE, 4, 5, 6, 0xEE, 0xEE];
1022        assert_eq!(
1023            unpack_u16(P::Mono8, 3, 2, Some(5), &src).unwrap(),
1024            [1, 2, 3, 4, 5, 6]
1025        );
1026        let mut conv = Converter::new();
1027        assert_eq!(
1028            conv.gray8(P::Mono8, 3, 2, Some(5), &src).unwrap(),
1029            [1, 2, 3, 4, 5, 6]
1030        );
1031        // The last line needs no padding after it.
1032        assert!(unpack_u16(P::Mono8, 3, 2, Some(5), &src[..8]).is_ok());
1033        // RGB8, 1 × 2, one byte of padding.
1034        let rgb = [1, 2, 3, 0xEE, 4, 5, 6, 0xEE];
1035        assert_eq!(
1036            to_rgb8(P::RGB8Packed, 1, 2, Some(4), &rgb).unwrap(),
1037            [1, 2, 3, 4, 5, 6]
1038        );
1039        assert_eq!(
1040            conv.rgb8(P::RGB8Packed, 1, 2, Some(4), &rgb).unwrap(),
1041            [1, 2, 3, 4, 5, 6]
1042        );
1043    }
1044
1045    /// A padded `Mono12p` line of three pixels ends inside its second
1046    /// packing group, which the line completes (PFNC 2.4 §6.7): six bytes,
1047    /// then the padding, then the next line.
1048    #[test]
1049    fn a_padded_packed_line_completes_its_own_group() {
1050        let src = [
1051            0x23, 0x61, 0x45, 0x89, 0x07, 0x00, 0xEE, // 0x123 0x456 0x789 (+0) | pad
1052            0x11, 0x21, 0x22, 0x33, 0x03, 0x00, 0xEE, // 0x111 0x222 0x333 (+0) | pad
1053        ];
1054        assert_eq!(
1055            unpack_u16(P::Mono12p, 3, 2, Some(7), &src).unwrap(),
1056            [0x123, 0x456, 0x789, 0x111, 0x222, 0x333]
1057        );
1058        assert_eq!(
1059            unpack_u16(P::Mono12p, 3, 2, Some(5), &src),
1060            Err(ConvertError::StrideTooShort { stride: 5, line: 6 })
1061        );
1062    }
1063
1064    #[test]
1065    fn short_payloads_are_refused_and_trailing_bytes_ignored() {
1066        assert_eq!(
1067            to_rgb8(P::Mono8, 2, 2, None, &[1, 2, 3]),
1068            Err(ConvertError::ShortPayload {
1069                format: P::Mono8,
1070                expected: 4,
1071                actual: 3
1072            })
1073        );
1074        assert_eq!(
1075            to_rgb8(P::Mono8, 1, 1, None, &[9, 0xEE, 0xEE]).unwrap(),
1076            [9, 9, 9]
1077        );
1078    }
1079
1080    /// `supports` answers exactly for the formats `to_rgb8` converts.
1081    #[test]
1082    fn supports_is_true_exactly_for_the_formats_converted() {
1083        let mut supported = 0;
1084        for &format in P::ALL {
1085            let Some(len) = format.image_bytes(4, 2) else {
1086                assert!(!supports(format), "{format}");
1087                continue;
1088            };
1089            let converts = to_rgb8(format, 4, 2, None, &vec![0; len]).is_ok();
1090            assert_eq!(supports(format), converts, "{format}");
1091            supported += usize::from(converts);
1092        }
1093        // 9 Mono, 32 Bayer, 4 RGB, 8 Y'CbCr.
1094        assert_eq!(supported, 53);
1095    }
1096
1097    #[test]
1098    fn formats_without_a_conversion_say_so() {
1099        for format in [P::Coord3DC32f, P::Confidence8, P::Unknown(0x0123_4567)] {
1100            assert_eq!(
1101                to_rgb8(format, 1, 1, None, &[0; 16]),
1102                Err(ConvertError::Unsupported(format))
1103            );
1104        }
1105        let mut conv = Converter::new();
1106        assert_eq!(
1107            conv.gray8(P::RGB8Packed, 1, 1, None, &[1, 2, 3]),
1108            Err(ConvertError::Unsupported(P::RGB8Packed))
1109        );
1110    }
1111
1112    // ── Normalising to 8 bits ────────────────────────────────────────────────
1113
1114    /// The top eight bits of the camera's depth.
1115    #[test]
1116    fn deep_samples_keep_their_top_eight_bits() {
1117        let mut conv = Converter::new();
1118        assert_eq!(
1119            conv.gray8(P::Mono10, 1, 1, None, &[0xFF, 0x03]).unwrap(),
1120            [0xFF]
1121        );
1122        assert_eq!(
1123            conv.gray8(P::Mono12, 1, 1, None, &[0xF0, 0x0F]).unwrap(),
1124            [0xFF]
1125        );
1126        assert_eq!(
1127            conv.gray8(P::Mono14, 1, 1, None, &[0xFF, 0x3F]).unwrap(),
1128            [0xFF]
1129        );
1130        assert_eq!(
1131            conv.gray8(P::Mono16, 1, 1, None, &[0x00, 0x80]).unwrap(),
1132            [0x80]
1133        );
1134        // 0xABC >> 4 and 0x123 >> 4.
1135        assert_eq!(
1136            conv.gray8(P::Mono12p, 2, 1, None, &[0xBC, 0x3A, 0x12])
1137                .unwrap(),
1138            [0xAB, 0x12]
1139        );
1140        assert_eq!(
1141            conv.gray8(P::Mono12Packed, 2, 1, None, &[0xAB, 0x3C, 0x12])
1142                .unwrap(),
1143            [0xAB, 0x12]
1144        );
1145        assert_eq!(conv.gray8(P::Mono8, 2, 1, None, &[3, 4]).unwrap(), [3, 4]);
1146        assert_eq!(
1147            to_rgb8(P::Mono10p, 4, 1, None, &[0xA5, 0x6A, 0x05, 0xCF, 0xC3]).unwrap(),
1148            [
1149                0xA9, 0xA9, 0xA9, 0x56, 0x56, 0x56, 0x3C, 0x3C, 0x3C, 0xC3, 0xC3, 0xC3
1150            ]
1151        );
1152    }
1153
1154    // ── Demosaicing ──────────────────────────────────────────────────────────
1155
1156    /// A 4×4 mosaic with each site's colour written per PFNC 2.4 §3.1.7
1157    /// (R = 200, G = 100, B = 50 after normalising). Away from the border
1158    /// every neighbour is in the image, so bilinear interpolation of a flat
1159    /// colour must give it back exactly — for every pattern and depth.
1160    #[test]
1161    fn every_bayer_pattern_puts_colours_where_pfnc_3_1_7_does() {
1162        // Top-left 2×2 tile per Figures 3-7, 3-9, 3-11, 3-13.
1163        let tiles: [(&[P], [[char; 2]; 2]); 4] = [
1164            (
1165                &[P::BayerRG8, P::BayerRG10, P::BayerRG12, P::BayerRG16],
1166                [['R', 'G'], ['G', 'B']],
1167            ),
1168            (
1169                &[P::BayerGR8, P::BayerGR10, P::BayerGR12, P::BayerGR16],
1170                [['G', 'R'], ['B', 'G']],
1171            ),
1172            (
1173                &[P::BayerGB8, P::BayerGB10, P::BayerGB12, P::BayerGB16],
1174                [['G', 'B'], ['R', 'G']],
1175            ),
1176            (
1177                &[P::BayerBG8, P::BayerBG10, P::BayerBG12, P::BayerBG16],
1178                [['B', 'G'], ['G', 'R']],
1179            ),
1180        ];
1181        for (formats, tile) in tiles {
1182            for &format in formats {
1183                let bits = format.bits_per_pixel().unwrap();
1184                let depth = match format.to_string().trim_start_matches("Bayer")[2..].parse::<u32>()
1185                {
1186                    Ok(d) => d,
1187                    Err(_) => unreachable!(),
1188                };
1189                let mut src = Vec::new();
1190                for y in 0..4 {
1191                    for x in 0..4 {
1192                        let v8: u32 = match tile[y % 2][x % 2] {
1193                            'R' => 200,
1194                            'G' => 100,
1195                            _ => 50,
1196                        };
1197                        let v = v8 << (depth - 8);
1198                        if bits == 8 {
1199                            src.push(v as u8);
1200                        } else {
1201                            src.extend_from_slice(&(v as u16).to_le_bytes());
1202                        }
1203                    }
1204                }
1205                let rgb = to_rgb8(format, 4, 4, None, &src).unwrap();
1206                for (x, y) in [(1, 1), (2, 1), (1, 2), (2, 2)] {
1207                    let i = (y * 4 + x) * 3;
1208                    assert_eq!(&rgb[i..i + 3], [200, 100, 50], "{format} at ({x}, {y})");
1209                }
1210            }
1211        }
1212    }
1213
1214    /// The arithmetic, by hand: bilinear interpolation with truncating
1215    /// integer means, edge samples replicated (clamp-to-edge) — the kernel
1216    /// Viva Studio's viewer used before this module existed.
1217    #[test]
1218    fn bilinear_demosaic_by_hand() {
1219        #[rustfmt::skip]
1220        let mosaic = [
1221             12, 200,  34, 180,
1222             90,   7, 150,   3,
1223             56, 210,  78, 190,
1224            120,   9, 140,  11,
1225        ];
1226        let rgb = to_rgb8(P::BayerRG8, 4, 4, None, &mosaic).unwrap();
1227        let at = |x: usize, y: usize| <[u8; 3]>::try_from(&rgb[(y * 4 + x) * 3..][..3]).unwrap();
1228        // B site: G = (90+150+200+210)/4 = 162, R = (12+34+56+78)/4 = 45.
1229        assert_eq!(at(1, 1), [45, 162, 7]);
1230        // G on a B row: R from above/below, B from left/right.
1231        assert_eq!(at(2, 1), [(34 + 78) / 2, 150, (7 + 3) / 2]);
1232        // G on an R row: R from left/right, B from above/below.
1233        assert_eq!(at(1, 2), [(56 + 78) / 2, 210, (7 + 9) / 2]);
1234        // R site: G = (210+190+150+140)/4 = 172, B = (7+3+9+11)/4 = 7.
1235        assert_eq!(at(2, 2), [78, 172, 7]);
1236        // Corner: the missing neighbours repeat the edge, R included.
1237        // G = (12+200+12+90)/4 = 78, B = (12+200+90+7)/4 = 77.
1238        assert_eq!(at(0, 0), [12, 78, 77]);
1239    }
1240
1241    /// GigE Vision 12Packed Bayer, packed by hand: R = 0xC8F, G = 0x64A,
1242    /// B = 0x323, i.e. 200, 100 and 50 in their top eight bits. Read with the
1243    /// wrong 12-bit packing, R would come out as 0xFC8 >> 4 = 252.
1244    #[test]
1245    fn packed_bayer_is_unpacked_before_demosaicing() {
1246        let rg = [0xC8, 0xAF, 0x64];
1247        let gb = [0x64, 0x3A, 0x32];
1248        let mut src = Vec::new();
1249        for row in [rg, gb, rg, gb] {
1250            src.extend_from_slice(&row);
1251            src.extend_from_slice(&row);
1252        }
1253        let rgb = to_rgb8(P::BayerRG12Packed, 4, 4, None, &src).unwrap();
1254        assert_eq!(&rgb[(4 + 1) * 3..][..3], [200, 100, 50]);
1255        assert_eq!(&rgb[(2 * 4 + 2) * 3..][..3], [200, 100, 50]);
1256
1257        let Pixels::Rgb16 { samples, bits } =
1258            full_depth(P::BayerRG12Packed, 4, 4, None, &src).unwrap()
1259        else {
1260            panic!("a 12-bit mosaic keeps its depth");
1261        };
1262        assert_eq!(bits, 12);
1263        assert_eq!(&samples[(4 + 1) * 3..][..3], [0xC8F, 0x64A, 0x323]);
1264    }
1265
1266    // ── Y'CbCr ───────────────────────────────────────────────────────────────
1267
1268    /// PFNC 2.4 §8.2.1 reverse equations, worked by hand for Y' = 100,
1269    /// Cb = 150, Cr = 90:
1270    ///   R' = 100 + 1.402 × (−38)                  =  46.72 → 47
1271    ///   G' = 100 − 0.34414 × 22 − 0.71414 × (−38) = 119.57 → 120
1272    ///   B' = 100 + 1.772 × 22                     = 138.98 → 139
1273    /// and for Y' = 200 with the same chroma: 147, 220, 239.
1274    const PX0: [u8; 3] = [47, 120, 139];
1275    const PX1: [u8; 3] = [147, 220, 239];
1276
1277    #[test]
1278    fn yuv422_component_orders() {
1279        // §3.1.3: the default 4:2:2 order is Y U Y V; `_UYVY` and `_CbYCrY`
1280        // name theirs (§7.3).
1281        for (format, bytes) in [
1282            (P::YUV422_8, [100, 150, 200, 90]),
1283            (P::YCbCr422_8, [100, 150, 200, 90]),
1284            (P::YUV422_8_UYVY, [150, 100, 90, 200]),
1285            (P::YCbCr422_8_CbYCrY, [150, 100, 90, 200]),
1286        ] {
1287            assert_eq!(
1288                to_rgb8(format, 2, 1, None, &bytes).unwrap(),
1289                [PX0, PX1].concat(),
1290                "{format}"
1291            );
1292        }
1293    }
1294
1295    #[test]
1296    fn yuv411_and_444_component_orders() {
1297        assert_eq!(
1298            to_rgb8(
1299                P::YUV411_8_UYYVYY,
1300                4,
1301                1,
1302                None,
1303                &[150, 100, 200, 90, 100, 200]
1304            )
1305            .unwrap(),
1306            [PX0, PX1, PX0, PX1].concat()
1307        );
1308        assert_eq!(
1309            to_rgb8(P::YUV8_UYV, 1, 1, None, &[150, 100, 90]).unwrap(),
1310            PX0
1311        );
1312        assert_eq!(
1313            to_rgb8(P::YCbCr8_CbYCr, 1, 1, None, &[150, 100, 90]).unwrap(),
1314            PX0
1315        );
1316        assert_eq!(
1317            to_rgb8(P::YCbCr8, 1, 1, None, &[100, 150, 90]).unwrap(),
1318            PX0
1319        );
1320    }
1321
1322    /// §8.2.1: "Values must be truncated to fit in that range."
1323    /// Y' = 250, Cb = 128, Cr = 255: R' = 250 + 1.402 × 127 = 428 → 255,
1324    /// G' = 250 − 0.71414 × 127 = 159.3 → 159, B' = 250.
1325    #[test]
1326    fn ycbcr_results_are_clamped_to_the_8_bit_range() {
1327        assert_eq!(
1328            to_rgb8(P::YCbCr8, 1, 1, None, &[250, 128, 255]).unwrap(),
1329            [255, 159, 250]
1330        );
1331    }
1332
1333    /// §6.7: an odd last pixel still arrives in a whole 4:2:2 group.
1334    #[test]
1335    fn an_odd_yuv422_width_reads_the_completed_group() {
1336        let rgb = to_rgb8(
1337            P::YUV422_8,
1338            3,
1339            1,
1340            None,
1341            &[100, 150, 200, 90, 100, 150, 0, 90],
1342        )
1343        .unwrap();
1344        assert_eq!(rgb, [PX0, PX1, PX0].concat());
1345    }
1346
1347    // ── RGB family ───────────────────────────────────────────────────────────
1348
1349    #[test]
1350    fn rgb_orders_and_alpha() {
1351        assert_eq!(
1352            to_rgb8(P::RGB8Packed, 1, 1, None, &[1, 2, 3]).unwrap(),
1353            [1, 2, 3]
1354        );
1355        assert_eq!(
1356            to_rgb8(P::BGR8Packed, 1, 1, None, &[1, 2, 3]).unwrap(),
1357            [3, 2, 1]
1358        );
1359        assert_eq!(
1360            to_rgb8(P::RGBa8, 1, 1, None, &[1, 2, 3, 99]).unwrap(),
1361            [1, 2, 3]
1362        );
1363        assert_eq!(
1364            to_rgb8(P::BGRa8, 1, 1, None, &[1, 2, 3, 99]).unwrap(),
1365            [3, 2, 1]
1366        );
1367        let mut conv = Converter::new();
1368        let src = [4, 5, 6];
1369        let out = conv.rgb8(P::RGB8Packed, 1, 1, None, &src).unwrap();
1370        assert!(core::ptr::eq(out, &src[..]), "RGB8 is lent, not copied");
1371    }
1372
1373    // ── Full depth ───────────────────────────────────────────────────────────
1374
1375    #[test]
1376    fn full_depth_keeps_the_camera_values() {
1377        assert_eq!(
1378            full_depth(P::Mono12p, 2, 1, None, &[0xBC, 0x3A, 0x12]).unwrap(),
1379            Pixels::Gray16 {
1380                samples: vec![0xABC, 0x123],
1381                bits: 12
1382            }
1383        );
1384        assert_eq!(
1385            full_depth(P::Mono8, 2, 1, None, &[1, 2]).unwrap(),
1386            Pixels::Gray8(vec![1, 2])
1387        );
1388        assert_eq!(
1389            full_depth(P::BGR8Packed, 1, 1, None, &[1, 2, 3]).unwrap(),
1390            Pixels::Rgb8(vec![3, 2, 1])
1391        );
1392        assert_eq!(
1393            full_depth(P::Mono10, 1, 1, None, &[0xA5, 0x02])
1394                .unwrap()
1395                .into_rgb(),
1396            Pixels::Rgb16 {
1397                samples: vec![0x2A5; 3],
1398                bits: 10
1399            }
1400        );
1401        assert_eq!(
1402            full_depth(P::Mono8, 1, 1, None, &[7]).unwrap().into_rgb(),
1403            Pixels::Rgb8(vec![7; 3])
1404        );
1405    }
1406
1407    /// The converter's buffers are reused: a second frame of the same size
1408    /// does not allocate.
1409    #[test]
1410    fn the_converter_reuses_its_buffers() {
1411        let mut conv = Converter::new();
1412        let src = [0u8; 16 * 2];
1413        let first = conv.rgb8(P::BayerRG12, 4, 4, None, &src).unwrap().as_ptr();
1414        let second = conv.rgb8(P::BayerRG12, 4, 4, None, &src).unwrap().as_ptr();
1415        assert_eq!(first, second);
1416    }
1417}