ezk_image/
pixel_format.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
use crate::{plane_decs::*, planes::read_planes, InvalidNumberOfPlanesError, StrictApi as _};

/// Supported pixel formats
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PixelFormat {
    /// Y, U and V planes, 4:2:0 sub sampling, 8 bits per sample
    I420,

    /// Y, U and V planes, 4:2:2 sub sampling, 8 bits per sample
    I422,

    /// Y, U and V planes, 4:4:4 sub sampling, 8 bits per sample
    I444,

    /// Y, U, and V planes, 4:2:0 sub sampling, 10 bits per sample
    I010,

    /// Y, U, and V planes, 4:2:0 sub sampling, 12 bits per sample
    I012,

    /// Y, U, and V planes, 4:2:2 sub sampling, 10 bits per sample
    I210,

    /// Y, U, and V planes, 4:2:2 sub sampling, 10 bits per sample
    I212,

    /// Y, U, and V planes, 4:4:4 sub sampling, 10 bits per sample
    I410,

    /// Y, U, and V planes, 4:4:4 sub sampling, 12 bits per sample
    I412,

    /// Y and interleaved UV planes, 4:2:0 sub sampling
    NV12,

    /// Single YUYV, 4:2:2 sub sampling
    YUYV,

    /// Single RGBA interleaved plane
    RGBA,

    /// Single BGRA interleaved plane
    BGRA,

    /// Single RGB interleaved plane
    RGB,

    /// Single BGR interleaved plane
    BGR,
}

impl PixelFormat {
    /// Calculate the required buffer size given the [`PixelFormat`] self and image dimensions (in pixel width, height).
    ///
    /// The size is the amount of primitives (u8, u16) so when allocating size this must be accounted for.
    #[deny(clippy::arithmetic_side_effects)]
    pub fn buffer_size(self, width: usize, height: usize) -> usize {
        fn buffer_size(planes: &[PlaneDesc], width: usize, height: usize) -> usize {
            let mut size = 0;

            for plane in planes {
                let w = plane.width_op.op(width);
                let h = plane.height_op.op(height);

                size = size.strict_add_(w.strict_mul_(h).strict_mul_(plane.bytes_per_primitive));
            }

            size
        }

        buffer_size(self.plane_desc(), width, height)
    }

    /// Calculate the strides of an image in a packed buffer
    #[deny(clippy::arithmetic_side_effects)]
    pub fn packed_strides(self, width: usize) -> Vec<usize> {
        fn packed_strides(planes: &[PlaneDesc], width: usize) -> Vec<usize> {
            planes
                .iter()
                .map(|desc| desc.packed_stride(width))
                .collect()
        }

        packed_strides(self.plane_desc(), width)
    }

    /// Check if the given planes+strides are valid for dimensions
    #[deny(clippy::arithmetic_side_effects)]
    pub fn bounds_check<'a>(
        self,
        planes: impl Iterator<Item = (&'a [u8], usize)>,
        width: usize,
        height: usize,
    ) -> Result<(), BoundsCheckError> {
        use PixelFormat::*;

        fn bounds_check<const N: usize>(
            planes: [PlaneDesc; N],
            got: [(&[u8], usize); N],
            width: usize,
            height: usize,
        ) -> Result<(), BoundsCheckError> {
            for (i, (plane, (slice, stride))) in planes.into_iter().zip(got).enumerate() {
                // Ensure stride is not smaller than the width would allow
                let min_stride = plane.packed_stride(width);

                if min_stride > stride {
                    return Err(BoundsCheckError::InvalidStride {
                        plane: i,
                        minimum: min_stride,
                        got: stride,
                    });
                }

                // Ensure slice is large enough
                let min_len = stride.strict_mul_(plane.height_op.op(height));

                if min_len > slice.len() {
                    return Err(BoundsCheckError::InvalidPlaneSize {
                        plane: i,
                        minimum: min_len,
                        got: slice.len(),
                    });
                }
            }

            Ok(())
        }

        match self {
            I420 => bounds_check(I420_PLANES, read_planes(planes)?, width, height),
            I422 => bounds_check(I422_PLANES, read_planes(planes)?, width, height),
            I444 => bounds_check(I444_PLANES, read_planes(planes)?, width, height),
            I010 | I012 => bounds_check(I01X_PLANES, read_planes(planes)?, width, height),
            I210 | I212 => bounds_check(I21X_PLANES, read_planes(planes)?, width, height),
            I410 | I412 => bounds_check(I41X_PLANES, read_planes(planes)?, width, height),
            NV12 => bounds_check(NV12_PLANES, read_planes(planes)?, width, height),
            YUYV => bounds_check(YUYV_PLANES, read_planes(planes)?, width, height),
            RGBA | BGRA => bounds_check(RGBA_PLANES, read_planes(planes)?, width, height),
            RGB | BGR => bounds_check(RGB_PLANES, read_planes(planes)?, width, height),
        }
    }

    pub fn bits_per_component(&self) -> usize {
        match self {
            PixelFormat::I420 => 8,
            PixelFormat::I422 => 8,
            PixelFormat::I444 => 8,
            PixelFormat::I010 => 10,
            PixelFormat::I012 => 12,
            PixelFormat::I210 => 10,
            PixelFormat::I212 => 12,
            PixelFormat::I410 => 10,
            PixelFormat::I412 => 12,
            PixelFormat::NV12 => 8,
            PixelFormat::YUYV => 8,
            PixelFormat::RGBA => 8,
            PixelFormat::BGRA => 8,
            PixelFormat::RGB => 8,
            PixelFormat::BGR => 8,
        }
    }

    pub(crate) fn plane_desc(&self) -> &'static [PlaneDesc] {
        use PixelFormat::*;

        match self {
            I420 => &I420_PLANES,
            I422 => &I422_PLANES,
            I444 => &I444_PLANES,
            I010 | I012 => &I01X_PLANES,
            I210 | I212 => &I21X_PLANES,
            I410 | I412 => &I41X_PLANES,
            NV12 => &NV12_PLANES,
            YUYV => &YUYV_PLANES,
            RGBA | BGRA => &RGBA_PLANES,
            RGB | BGR => &RGB_PLANES,
        }
    }

    pub fn variants() -> impl IntoIterator<Item = Self> {
        use PixelFormat::*;

        [
            I420, I422, I444, I010, I012, I210, I212, I410, I412, NV12, YUYV, RGBA, BGRA, RGB, BGR,
        ]
    }
}

#[derive(Debug, thiserror::Error)]
pub enum BoundsCheckError {
    #[error(transparent)]
    InvalidNumberOfPlanes(#[from] InvalidNumberOfPlanesError),

    #[error(
        "invalid stride at plane {plane}, expected it to be at least {minimum}, but got {got}"
    )]
    InvalidStride {
        plane: usize,
        minimum: usize,
        got: usize,
    },

    #[error(
        "invalid plane size at plane {plane}, expected it to be at least {minimum}, but got {got}"
    )]
    InvalidPlaneSize {
        plane: usize,
        minimum: usize,
        got: usize,
    },
}