Skip to main content

mynd_core/
pixel.rs

1use core::convert::TryFrom;
2use core::num::NonZeroU8;
3
4use mynd_math::{MathError, checked_add_u64, checked_mul_u64};
5
6use crate::{
7    Dimensions, OutputLength, PixelLayoutError, PixelLayoutResult, PlaneLayout, SampleStorage,
8    checked_plane_output_len,
9};
10
11const ONE: NonZeroU8 = NonZeroU8::MIN;
12const TWO: NonZeroU8 = NonZeroU8::MIN.saturating_add(1);
13const THREE: NonZeroU8 = NonZeroU8::MIN.saturating_add(2);
14const FOUR: NonZeroU8 = NonZeroU8::MIN.saturating_add(3);
15
16/// The meaning of stored alpha samples.
17#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
18pub enum AlphaAssociation {
19    /// Color samples are independent of alpha.
20    Straight,
21    /// Color samples are already multiplied by alpha.
22    Premultiplied,
23}
24
25/// Chroma sampling factors relative to full-resolution luma.
26#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
27#[cfg_attr(kani, derive(kani::Arbitrary))]
28pub enum ChromaSubsampling {
29    /// No chroma subsampling (4:4:4).
30    Cs444,
31    /// Half horizontal chroma resolution (4:2:2).
32    Cs422,
33    /// Half horizontal and vertical chroma resolution (4:2:0).
34    Cs420,
35    /// Half vertical chroma resolution (4:4:0).
36    Cs440,
37    /// Quarter horizontal chroma resolution (4:1:1).
38    Cs411,
39    /// Quarter horizontal and half vertical chroma resolution (4:1:0).
40    Cs410,
41}
42
43impl ChromaSubsampling {
44    const fn factors(self) -> (NonZeroU8, NonZeroU8) {
45        match self {
46            Self::Cs444 => (ONE, ONE),
47            Self::Cs422 => (TWO, ONE),
48            Self::Cs420 => (TWO, TWO),
49            Self::Cs440 => (ONE, TWO),
50            Self::Cs411 => (FOUR, ONE),
51            Self::Cs410 => (FOUR, TWO),
52        }
53    }
54
55    /// Returns the horizontal chroma divisor.
56    #[must_use]
57    pub const fn horizontal_divisor(self) -> NonZeroU8 {
58        self.factors().0
59    }
60
61    /// Returns the vertical chroma divisor.
62    #[must_use]
63    pub const fn vertical_divisor(self) -> NonZeroU8 {
64        self.factors().1
65    }
66}
67
68/// Channel order for interleaved gray-and-alpha samples.
69#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
70pub enum GrayAlphaOrder {
71    /// Gray followed by alpha.
72    GrayAlpha,
73    /// Alpha followed by gray.
74    AlphaGray,
75}
76
77/// Channel order for interleaved three-channel RGB samples.
78#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
79pub enum RgbOrder {
80    /// Red, green, blue.
81    Rgb,
82    /// Blue, green, red.
83    Bgr,
84}
85
86/// Channel order for interleaved RGB-with-alpha samples.
87#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
88pub enum RgbaOrder {
89    /// Red, green, blue, alpha.
90    Rgba,
91    /// Blue, green, red, alpha.
92    Bgra,
93    /// Alpha, red, green, blue.
94    Argb,
95    /// Alpha, blue, green, red.
96    Abgr,
97}
98
99/// Channel order for the interleaved chroma plane of a semi-planar layout.
100#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
101pub enum ChromaOrder {
102    /// Cb followed by Cr.
103    CbCr,
104    /// Cr followed by Cb.
105    CrCb,
106}
107
108/// One logical plane required by a [`PixelLayout`].
109#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
110pub struct PixelPlane {
111    sample: SampleStorage,
112    channels: NonZeroU8,
113    horizontal_divisor: NonZeroU8,
114    vertical_divisor: NonZeroU8,
115}
116
117impl PixelPlane {
118    const fn new(
119        sample: SampleStorage,
120        channels: NonZeroU8,
121        horizontal_divisor: NonZeroU8,
122        vertical_divisor: NonZeroU8,
123    ) -> Self {
124        Self {
125            sample,
126            channels,
127            horizontal_divisor,
128            vertical_divisor,
129        }
130    }
131
132    /// Returns the shared storage domain for each channel in this plane.
133    #[must_use]
134    pub const fn sample(self) -> SampleStorage {
135        self.sample
136    }
137
138    /// Returns the number of interleaved channels in this plane.
139    #[must_use]
140    pub const fn channels(self) -> NonZeroU8 {
141        self.channels
142    }
143
144    /// Returns the horizontal sampling divisor relative to the image.
145    #[must_use]
146    pub const fn horizontal_divisor(self) -> NonZeroU8 {
147        self.horizontal_divisor
148    }
149
150    /// Returns the vertical sampling divisor relative to the image.
151    #[must_use]
152    pub const fn vertical_divisor(self) -> NonZeroU8 {
153        self.vertical_divisor
154    }
155
156    /// Returns the exact logical dimensions sampled by this plane.
157    pub fn dimensions(self, image: Dimensions) -> PixelLayoutResult<Dimensions> {
158        let width = divided_ceil(image.width(), self.horizontal_divisor);
159        let height = divided_ceil(image.height(), self.vertical_divisor);
160        Dimensions::new(width, height).map_err(PixelLayoutError::Geometry)
161    }
162
163    /// Returns the exact bytes used by one tightly packed plane row.
164    ///
165    /// A final partial byte is charged in full. Row-stride padding is not
166    /// included.
167    ///
168    /// # Errors
169    ///
170    /// Returns an arithmetic error if the row-bit calculation overflows.
171    pub fn row_bytes(self, image: Dimensions) -> PixelLayoutResult<u64> {
172        let samples = u64::from(divided_ceil(image.width(), self.horizontal_divisor));
173        let samples = checked_mul_u64(samples, u64::from(self.channels.get()))
174            .map_err(PixelLayoutError::Arithmetic)?;
175        let bits = checked_mul_u64(samples, u64::from(self.sample.storage_bits()))
176            .map_err(PixelLayoutError::Arithmetic)?;
177        let rounded = checked_add_u64(bits, 7).map_err(PixelLayoutError::Arithmetic)?;
178        Ok(rounded / 8)
179    }
180}
181
182/// A format-neutral pixel layout whose channel, alpha, chroma, and plane
183/// relationships are fixed by its variant.
184#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
185pub enum PixelLayout {
186    /// One full-resolution gray plane.
187    Gray {
188        /// Gray sample storage.
189        sample: SampleStorage,
190    },
191    /// One full-resolution interleaved gray/alpha plane.
192    GrayAlphaInterleaved {
193        /// Shared gray and alpha storage.
194        sample: SampleStorage,
195        /// Interleaved channel order.
196        order: GrayAlphaOrder,
197        /// Alpha association.
198        alpha: AlphaAssociation,
199    },
200    /// Separate full-resolution gray and alpha planes, in that order.
201    GrayAlphaPlanar {
202        /// Gray-plane storage.
203        gray: SampleStorage,
204        /// Alpha-plane storage.
205        alpha_sample: SampleStorage,
206        /// Alpha association.
207        alpha: AlphaAssociation,
208    },
209    /// One full-resolution interleaved RGB plane.
210    RgbInterleaved {
211        /// Shared channel storage.
212        sample: SampleStorage,
213        /// Interleaved channel order.
214        order: RgbOrder,
215    },
216    /// Separate full-resolution R, G, and B planes, in that order.
217    RgbPlanar {
218        /// Shared channel storage.
219        sample: SampleStorage,
220    },
221    /// One full-resolution interleaved RGB/alpha plane.
222    RgbaInterleaved {
223        /// Shared channel storage.
224        sample: SampleStorage,
225        /// Interleaved channel order.
226        order: RgbaOrder,
227        /// Alpha association.
228        alpha: AlphaAssociation,
229    },
230    /// Separate full-resolution R, G, B, and alpha planes, in that order.
231    RgbaPlanar {
232        /// Shared RGB-plane storage.
233        color: SampleStorage,
234        /// Alpha-plane storage.
235        alpha_sample: SampleStorage,
236        /// Alpha association.
237        alpha: AlphaAssociation,
238    },
239    /// Separate Y, Cb, and Cr planes, in that order.
240    YcbcrPlanar {
241        /// Luma-plane storage.
242        luma: SampleStorage,
243        /// Shared chroma-plane storage.
244        chroma: SampleStorage,
245        /// Chroma sampling factors.
246        subsampling: ChromaSubsampling,
247    },
248    /// A full-resolution Y plane followed by one interleaved chroma plane.
249    YcbcrSemiPlanar {
250        /// Luma-plane storage.
251        luma: SampleStorage,
252        /// Chroma-plane channel storage.
253        chroma: SampleStorage,
254        /// Chroma sampling factors.
255        subsampling: ChromaSubsampling,
256        /// Interleaved chroma order.
257        order: ChromaOrder,
258    },
259    /// Separate Y, Cb, Cr, and full-resolution alpha planes, in that order.
260    YcbcrAlphaPlanar {
261        /// Luma-plane storage.
262        luma: SampleStorage,
263        /// Shared chroma-plane storage.
264        chroma: SampleStorage,
265        /// Alpha-plane storage.
266        alpha_sample: SampleStorage,
267        /// Chroma sampling factors.
268        subsampling: ChromaSubsampling,
269        /// Alpha association.
270        alpha: AlphaAssociation,
271    },
272    /// Y, interleaved chroma, and full-resolution alpha planes, in that order.
273    YcbcrAlphaSemiPlanar {
274        /// Luma-plane storage.
275        luma: SampleStorage,
276        /// Chroma-plane channel storage.
277        chroma: SampleStorage,
278        /// Alpha-plane storage.
279        alpha_sample: SampleStorage,
280        /// Chroma sampling factors.
281        subsampling: ChromaSubsampling,
282        /// Interleaved chroma order.
283        order: ChromaOrder,
284        /// Alpha association.
285        alpha: AlphaAssociation,
286    },
287}
288
289impl PixelLayout {
290    /// Returns the exact number of planes required by the variant.
291    #[must_use]
292    pub const fn plane_count(self) -> u8 {
293        match self {
294            Self::Gray { .. }
295            | Self::GrayAlphaInterleaved { .. }
296            | Self::RgbInterleaved { .. }
297            | Self::RgbaInterleaved { .. } => 1,
298            Self::GrayAlphaPlanar { .. } | Self::YcbcrSemiPlanar { .. } => 2,
299            Self::RgbPlanar { .. }
300            | Self::YcbcrPlanar { .. }
301            | Self::YcbcrAlphaSemiPlanar { .. } => 3,
302            Self::RgbaPlanar { .. } | Self::YcbcrAlphaPlanar { .. } => 4,
303        }
304    }
305
306    /// Returns the alpha association only for layouts that contain alpha.
307    #[must_use]
308    pub const fn alpha_association(self) -> Option<AlphaAssociation> {
309        match self {
310            Self::GrayAlphaInterleaved { alpha, .. }
311            | Self::GrayAlphaPlanar { alpha, .. }
312            | Self::RgbaInterleaved { alpha, .. }
313            | Self::RgbaPlanar { alpha, .. }
314            | Self::YcbcrAlphaPlanar { alpha, .. }
315            | Self::YcbcrAlphaSemiPlanar { alpha, .. } => Some(alpha),
316            Self::Gray { .. }
317            | Self::RgbInterleaved { .. }
318            | Self::RgbPlanar { .. }
319            | Self::YcbcrPlanar { .. }
320            | Self::YcbcrSemiPlanar { .. } => None,
321        }
322    }
323
324    /// Returns chroma subsampling only for YCbCr layouts.
325    #[must_use]
326    pub const fn chroma_subsampling(self) -> Option<ChromaSubsampling> {
327        match self {
328            Self::YcbcrPlanar { subsampling, .. }
329            | Self::YcbcrSemiPlanar { subsampling, .. }
330            | Self::YcbcrAlphaPlanar { subsampling, .. }
331            | Self::YcbcrAlphaSemiPlanar { subsampling, .. } => Some(subsampling),
332            Self::Gray { .. }
333            | Self::GrayAlphaInterleaved { .. }
334            | Self::GrayAlphaPlanar { .. }
335            | Self::RgbInterleaved { .. }
336            | Self::RgbPlanar { .. }
337            | Self::RgbaInterleaved { .. }
338            | Self::RgbaPlanar { .. } => None,
339        }
340    }
341
342    /// Returns one logical plane, or `None` when the index is out of range.
343    #[must_use]
344    pub const fn plane(self, index: u8) -> Option<PixelPlane> {
345        match self {
346            Self::Gray { sample } if index == 0 => Some(full(sample, ONE)),
347            Self::GrayAlphaInterleaved { sample, .. } if index == 0 => Some(full(sample, TWO)),
348            Self::GrayAlphaPlanar {
349                gray, alpha_sample, ..
350            } => planar_two(index, gray, alpha_sample),
351            Self::RgbInterleaved { sample, .. } if index == 0 => Some(full(sample, THREE)),
352            Self::RgbPlanar { sample } => same_full(index, sample, THREE),
353            Self::RgbaInterleaved { sample, .. } if index == 0 => Some(full(sample, FOUR)),
354            Self::RgbaPlanar {
355                color,
356                alpha_sample,
357                ..
358            } => rgba_planar(index, color, alpha_sample),
359            Self::YcbcrPlanar {
360                luma,
361                chroma,
362                subsampling,
363            } => ycbcr_planar(index, luma, chroma, subsampling, None),
364            Self::YcbcrSemiPlanar {
365                luma,
366                chroma,
367                subsampling,
368                ..
369            } => ycbcr_semi(index, luma, chroma, subsampling, None),
370            Self::YcbcrAlphaPlanar {
371                luma,
372                chroma,
373                alpha_sample,
374                subsampling,
375                ..
376            } => ycbcr_planar(index, luma, chroma, subsampling, Some(alpha_sample)),
377            Self::YcbcrAlphaSemiPlanar {
378                luma,
379                chroma,
380                alpha_sample,
381                subsampling,
382                ..
383            } => ycbcr_semi(index, luma, chroma, subsampling, Some(alpha_sample)),
384            _ => None,
385        }
386    }
387
388    /// Validates concrete byte planes against the exact logical layout.
389    ///
390    /// Plane count, sampled row count, and tightly packed used row bytes must
391    /// match. Stride padding and gaps between planes remain permitted by
392    /// [`PlaneLayout`]; overlap and ordering remain forbidden.
393    ///
394    /// # Errors
395    ///
396    /// Rejects mismatched plane relationships, row-size arithmetic failure,
397    /// or invalid concrete plane ordering and overlap.
398    pub fn validate_planes(
399        self,
400        image: Dimensions,
401        planes: &[PlaneLayout],
402    ) -> PixelLayoutResult<OutputLength> {
403        if planes.len() != usize::from(self.plane_count()) {
404            return Err(PixelLayoutError::PlaneCountMismatch);
405        }
406        for (index, plane) in planes.iter().enumerate() {
407            let index = u8::try_from(index)
408                .map_err(|_| PixelLayoutError::Arithmetic(MathError::ConversionOutOfRange))?;
409            let expected = self
410                .plane(index)
411                .ok_or(PixelLayoutError::PlaneCountMismatch)?;
412            if plane.rows() != expected.dimensions(image)?.height() {
413                return Err(PixelLayoutError::PlaneRowsMismatch);
414            }
415            let row_bytes = u64::try_from(plane.row_bytes())
416                .map_err(|_| PixelLayoutError::Arithmetic(MathError::ConversionOutOfRange))?;
417            if row_bytes != expected.row_bytes(image)? {
418                return Err(PixelLayoutError::PlaneRowBytesMismatch);
419            }
420        }
421        checked_plane_output_len(planes).map_err(PixelLayoutError::Geometry)
422    }
423}
424
425const fn full(sample: SampleStorage, channels: NonZeroU8) -> PixelPlane {
426    PixelPlane::new(sample, channels, ONE, ONE)
427}
428
429const fn planar_two(index: u8, first: SampleStorage, second: SampleStorage) -> Option<PixelPlane> {
430    match index {
431        0 => Some(full(first, ONE)),
432        1 => Some(full(second, ONE)),
433        _ => None,
434    }
435}
436
437const fn same_full(index: u8, sample: SampleStorage, count: NonZeroU8) -> Option<PixelPlane> {
438    if index < count.get() {
439        Some(full(sample, ONE))
440    } else {
441        None
442    }
443}
444
445const fn rgba_planar(index: u8, color: SampleStorage, alpha: SampleStorage) -> Option<PixelPlane> {
446    match index {
447        0..=2 => Some(full(color, ONE)),
448        3 => Some(full(alpha, ONE)),
449        _ => None,
450    }
451}
452
453const fn ycbcr_planar(
454    index: u8,
455    luma: SampleStorage,
456    chroma: SampleStorage,
457    subsampling: ChromaSubsampling,
458    alpha: Option<SampleStorage>,
459) -> Option<PixelPlane> {
460    let (horizontal, vertical) = subsampling.factors();
461    match index {
462        0 => Some(full(luma, ONE)),
463        1 | 2 => Some(PixelPlane::new(chroma, ONE, horizontal, vertical)),
464        3 => match alpha {
465            Some(sample) => Some(full(sample, ONE)),
466            None => None,
467        },
468        _ => None,
469    }
470}
471
472const fn ycbcr_semi(
473    index: u8,
474    luma: SampleStorage,
475    chroma: SampleStorage,
476    subsampling: ChromaSubsampling,
477    alpha: Option<SampleStorage>,
478) -> Option<PixelPlane> {
479    let (horizontal, vertical) = subsampling.factors();
480    match index {
481        0 => Some(full(luma, ONE)),
482        1 => Some(PixelPlane::new(chroma, TWO, horizontal, vertical)),
483        2 => match alpha {
484            Some(sample) => Some(full(sample, ONE)),
485            None => None,
486        },
487        _ => None,
488    }
489}
490
491fn divided_ceil(value: u32, divisor: NonZeroU8) -> u32 {
492    value.div_ceil(u32::from(divisor.get()))
493}