mynd-core 0.3.0

Format-neutral no_std image types for the mynd ecosystem.
Documentation
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
use core::convert::TryFrom;
use core::num::NonZeroU8;

use mynd_math::{MathError, checked_add_u64, checked_mul_u64};

use crate::{
    Dimensions, OutputLength, PixelLayoutError, PixelLayoutResult, PlaneLayout, SampleStorage,
    checked_plane_output_len,
};

const ONE: NonZeroU8 = NonZeroU8::MIN;
const TWO: NonZeroU8 = NonZeroU8::MIN.saturating_add(1);
const THREE: NonZeroU8 = NonZeroU8::MIN.saturating_add(2);
const FOUR: NonZeroU8 = NonZeroU8::MIN.saturating_add(3);

/// The meaning of stored alpha samples.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum AlphaAssociation {
    /// Color samples are independent of alpha.
    Straight,
    /// Color samples are already multiplied by alpha.
    Premultiplied,
}

/// Chroma sampling factors relative to full-resolution luma.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(kani, derive(kani::Arbitrary))]
pub enum ChromaSubsampling {
    /// No chroma subsampling (4:4:4).
    Cs444,
    /// Half horizontal chroma resolution (4:2:2).
    Cs422,
    /// Half horizontal and vertical chroma resolution (4:2:0).
    Cs420,
    /// Half vertical chroma resolution (4:4:0).
    Cs440,
    /// Quarter horizontal chroma resolution (4:1:1).
    Cs411,
    /// Quarter horizontal and half vertical chroma resolution (4:1:0).
    Cs410,
}

impl ChromaSubsampling {
    const fn factors(self) -> (NonZeroU8, NonZeroU8) {
        match self {
            Self::Cs444 => (ONE, ONE),
            Self::Cs422 => (TWO, ONE),
            Self::Cs420 => (TWO, TWO),
            Self::Cs440 => (ONE, TWO),
            Self::Cs411 => (FOUR, ONE),
            Self::Cs410 => (FOUR, TWO),
        }
    }

    /// Returns the horizontal chroma divisor.
    #[must_use]
    pub const fn horizontal_divisor(self) -> NonZeroU8 {
        self.factors().0
    }

    /// Returns the vertical chroma divisor.
    #[must_use]
    pub const fn vertical_divisor(self) -> NonZeroU8 {
        self.factors().1
    }
}

/// Channel order for interleaved gray-and-alpha samples.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum GrayAlphaOrder {
    /// Gray followed by alpha.
    GrayAlpha,
    /// Alpha followed by gray.
    AlphaGray,
}

/// Channel order for interleaved three-channel RGB samples.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RgbOrder {
    /// Red, green, blue.
    Rgb,
    /// Blue, green, red.
    Bgr,
}

/// Channel order for interleaved RGB-with-alpha samples.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RgbaOrder {
    /// Red, green, blue, alpha.
    Rgba,
    /// Blue, green, red, alpha.
    Bgra,
    /// Alpha, red, green, blue.
    Argb,
    /// Alpha, blue, green, red.
    Abgr,
}

/// Channel order for the interleaved chroma plane of a semi-planar layout.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum ChromaOrder {
    /// Cb followed by Cr.
    CbCr,
    /// Cr followed by Cb.
    CrCb,
}

/// One logical plane required by a [`PixelLayout`].
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct PixelPlane {
    sample: SampleStorage,
    channels: NonZeroU8,
    horizontal_divisor: NonZeroU8,
    vertical_divisor: NonZeroU8,
}

impl PixelPlane {
    const fn new(
        sample: SampleStorage,
        channels: NonZeroU8,
        horizontal_divisor: NonZeroU8,
        vertical_divisor: NonZeroU8,
    ) -> Self {
        Self {
            sample,
            channels,
            horizontal_divisor,
            vertical_divisor,
        }
    }

    /// Returns the shared storage domain for each channel in this plane.
    #[must_use]
    pub const fn sample(self) -> SampleStorage {
        self.sample
    }

    /// Returns the number of interleaved channels in this plane.
    #[must_use]
    pub const fn channels(self) -> NonZeroU8 {
        self.channels
    }

    /// Returns the horizontal sampling divisor relative to the image.
    #[must_use]
    pub const fn horizontal_divisor(self) -> NonZeroU8 {
        self.horizontal_divisor
    }

    /// Returns the vertical sampling divisor relative to the image.
    #[must_use]
    pub const fn vertical_divisor(self) -> NonZeroU8 {
        self.vertical_divisor
    }

    /// Returns the exact logical dimensions sampled by this plane.
    pub fn dimensions(self, image: Dimensions) -> PixelLayoutResult<Dimensions> {
        let width = divided_ceil(image.width(), self.horizontal_divisor);
        let height = divided_ceil(image.height(), self.vertical_divisor);
        Dimensions::new(width, height).map_err(PixelLayoutError::Geometry)
    }

    /// Returns the exact bytes used by one tightly packed plane row.
    ///
    /// A final partial byte is charged in full. Row-stride padding is not
    /// included.
    ///
    /// # Errors
    ///
    /// Returns an arithmetic error if the row-bit calculation overflows.
    pub fn row_bytes(self, image: Dimensions) -> PixelLayoutResult<u64> {
        let samples = u64::from(divided_ceil(image.width(), self.horizontal_divisor));
        let samples = checked_mul_u64(samples, u64::from(self.channels.get()))
            .map_err(PixelLayoutError::Arithmetic)?;
        let bits = checked_mul_u64(samples, u64::from(self.sample.storage_bits()))
            .map_err(PixelLayoutError::Arithmetic)?;
        let rounded = checked_add_u64(bits, 7).map_err(PixelLayoutError::Arithmetic)?;
        Ok(rounded / 8)
    }
}

/// A format-neutral pixel layout whose channel, alpha, chroma, and plane
/// relationships are fixed by its variant.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum PixelLayout {
    /// One full-resolution gray plane.
    Gray {
        /// Gray sample storage.
        sample: SampleStorage,
    },
    /// One full-resolution interleaved gray/alpha plane.
    GrayAlphaInterleaved {
        /// Shared gray and alpha storage.
        sample: SampleStorage,
        /// Interleaved channel order.
        order: GrayAlphaOrder,
        /// Alpha association.
        alpha: AlphaAssociation,
    },
    /// Separate full-resolution gray and alpha planes, in that order.
    GrayAlphaPlanar {
        /// Gray-plane storage.
        gray: SampleStorage,
        /// Alpha-plane storage.
        alpha_sample: SampleStorage,
        /// Alpha association.
        alpha: AlphaAssociation,
    },
    /// One full-resolution interleaved RGB plane.
    RgbInterleaved {
        /// Shared channel storage.
        sample: SampleStorage,
        /// Interleaved channel order.
        order: RgbOrder,
    },
    /// Separate full-resolution R, G, and B planes, in that order.
    RgbPlanar {
        /// Shared channel storage.
        sample: SampleStorage,
    },
    /// One full-resolution interleaved RGB/alpha plane.
    RgbaInterleaved {
        /// Shared channel storage.
        sample: SampleStorage,
        /// Interleaved channel order.
        order: RgbaOrder,
        /// Alpha association.
        alpha: AlphaAssociation,
    },
    /// Separate full-resolution R, G, B, and alpha planes, in that order.
    RgbaPlanar {
        /// Shared RGB-plane storage.
        color: SampleStorage,
        /// Alpha-plane storage.
        alpha_sample: SampleStorage,
        /// Alpha association.
        alpha: AlphaAssociation,
    },
    /// Separate Y, Cb, and Cr planes, in that order.
    YcbcrPlanar {
        /// Luma-plane storage.
        luma: SampleStorage,
        /// Shared chroma-plane storage.
        chroma: SampleStorage,
        /// Chroma sampling factors.
        subsampling: ChromaSubsampling,
    },
    /// A full-resolution Y plane followed by one interleaved chroma plane.
    YcbcrSemiPlanar {
        /// Luma-plane storage.
        luma: SampleStorage,
        /// Chroma-plane channel storage.
        chroma: SampleStorage,
        /// Chroma sampling factors.
        subsampling: ChromaSubsampling,
        /// Interleaved chroma order.
        order: ChromaOrder,
    },
    /// Separate Y, Cb, Cr, and full-resolution alpha planes, in that order.
    YcbcrAlphaPlanar {
        /// Luma-plane storage.
        luma: SampleStorage,
        /// Shared chroma-plane storage.
        chroma: SampleStorage,
        /// Alpha-plane storage.
        alpha_sample: SampleStorage,
        /// Chroma sampling factors.
        subsampling: ChromaSubsampling,
        /// Alpha association.
        alpha: AlphaAssociation,
    },
    /// Y, interleaved chroma, and full-resolution alpha planes, in that order.
    YcbcrAlphaSemiPlanar {
        /// Luma-plane storage.
        luma: SampleStorage,
        /// Chroma-plane channel storage.
        chroma: SampleStorage,
        /// Alpha-plane storage.
        alpha_sample: SampleStorage,
        /// Chroma sampling factors.
        subsampling: ChromaSubsampling,
        /// Interleaved chroma order.
        order: ChromaOrder,
        /// Alpha association.
        alpha: AlphaAssociation,
    },
}

impl PixelLayout {
    /// Returns the exact number of planes required by the variant.
    #[must_use]
    pub const fn plane_count(self) -> u8 {
        match self {
            Self::Gray { .. }
            | Self::GrayAlphaInterleaved { .. }
            | Self::RgbInterleaved { .. }
            | Self::RgbaInterleaved { .. } => 1,
            Self::GrayAlphaPlanar { .. } | Self::YcbcrSemiPlanar { .. } => 2,
            Self::RgbPlanar { .. }
            | Self::YcbcrPlanar { .. }
            | Self::YcbcrAlphaSemiPlanar { .. } => 3,
            Self::RgbaPlanar { .. } | Self::YcbcrAlphaPlanar { .. } => 4,
        }
    }

    /// Returns the alpha association only for layouts that contain alpha.
    #[must_use]
    pub const fn alpha_association(self) -> Option<AlphaAssociation> {
        match self {
            Self::GrayAlphaInterleaved { alpha, .. }
            | Self::GrayAlphaPlanar { alpha, .. }
            | Self::RgbaInterleaved { alpha, .. }
            | Self::RgbaPlanar { alpha, .. }
            | Self::YcbcrAlphaPlanar { alpha, .. }
            | Self::YcbcrAlphaSemiPlanar { alpha, .. } => Some(alpha),
            Self::Gray { .. }
            | Self::RgbInterleaved { .. }
            | Self::RgbPlanar { .. }
            | Self::YcbcrPlanar { .. }
            | Self::YcbcrSemiPlanar { .. } => None,
        }
    }

    /// Returns chroma subsampling only for YCbCr layouts.
    #[must_use]
    pub const fn chroma_subsampling(self) -> Option<ChromaSubsampling> {
        match self {
            Self::YcbcrPlanar { subsampling, .. }
            | Self::YcbcrSemiPlanar { subsampling, .. }
            | Self::YcbcrAlphaPlanar { subsampling, .. }
            | Self::YcbcrAlphaSemiPlanar { subsampling, .. } => Some(subsampling),
            Self::Gray { .. }
            | Self::GrayAlphaInterleaved { .. }
            | Self::GrayAlphaPlanar { .. }
            | Self::RgbInterleaved { .. }
            | Self::RgbPlanar { .. }
            | Self::RgbaInterleaved { .. }
            | Self::RgbaPlanar { .. } => None,
        }
    }

    /// Returns one logical plane, or `None` when the index is out of range.
    #[must_use]
    pub const fn plane(self, index: u8) -> Option<PixelPlane> {
        match self {
            Self::Gray { sample } if index == 0 => Some(full(sample, ONE)),
            Self::GrayAlphaInterleaved { sample, .. } if index == 0 => Some(full(sample, TWO)),
            Self::GrayAlphaPlanar {
                gray, alpha_sample, ..
            } => planar_two(index, gray, alpha_sample),
            Self::RgbInterleaved { sample, .. } if index == 0 => Some(full(sample, THREE)),
            Self::RgbPlanar { sample } => same_full(index, sample, THREE),
            Self::RgbaInterleaved { sample, .. } if index == 0 => Some(full(sample, FOUR)),
            Self::RgbaPlanar {
                color,
                alpha_sample,
                ..
            } => rgba_planar(index, color, alpha_sample),
            Self::YcbcrPlanar {
                luma,
                chroma,
                subsampling,
            } => ycbcr_planar(index, luma, chroma, subsampling, None),
            Self::YcbcrSemiPlanar {
                luma,
                chroma,
                subsampling,
                ..
            } => ycbcr_semi(index, luma, chroma, subsampling, None),
            Self::YcbcrAlphaPlanar {
                luma,
                chroma,
                alpha_sample,
                subsampling,
                ..
            } => ycbcr_planar(index, luma, chroma, subsampling, Some(alpha_sample)),
            Self::YcbcrAlphaSemiPlanar {
                luma,
                chroma,
                alpha_sample,
                subsampling,
                ..
            } => ycbcr_semi(index, luma, chroma, subsampling, Some(alpha_sample)),
            _ => None,
        }
    }

    /// Validates concrete byte planes against the exact logical layout.
    ///
    /// Plane count, sampled row count, and tightly packed used row bytes must
    /// match. Stride padding and gaps between planes remain permitted by
    /// [`PlaneLayout`]; overlap and ordering remain forbidden.
    ///
    /// # Errors
    ///
    /// Rejects mismatched plane relationships, row-size arithmetic failure,
    /// or invalid concrete plane ordering and overlap.
    pub fn validate_planes(
        self,
        image: Dimensions,
        planes: &[PlaneLayout],
    ) -> PixelLayoutResult<OutputLength> {
        if planes.len() != usize::from(self.plane_count()) {
            return Err(PixelLayoutError::PlaneCountMismatch);
        }
        for (index, plane) in planes.iter().enumerate() {
            let index = u8::try_from(index)
                .map_err(|_| PixelLayoutError::Arithmetic(MathError::ConversionOutOfRange))?;
            let expected = self
                .plane(index)
                .ok_or(PixelLayoutError::PlaneCountMismatch)?;
            if plane.rows() != expected.dimensions(image)?.height() {
                return Err(PixelLayoutError::PlaneRowsMismatch);
            }
            let row_bytes = u64::try_from(plane.row_bytes())
                .map_err(|_| PixelLayoutError::Arithmetic(MathError::ConversionOutOfRange))?;
            if row_bytes != expected.row_bytes(image)? {
                return Err(PixelLayoutError::PlaneRowBytesMismatch);
            }
        }
        checked_plane_output_len(planes).map_err(PixelLayoutError::Geometry)
    }
}

const fn full(sample: SampleStorage, channels: NonZeroU8) -> PixelPlane {
    PixelPlane::new(sample, channels, ONE, ONE)
}

const fn planar_two(index: u8, first: SampleStorage, second: SampleStorage) -> Option<PixelPlane> {
    match index {
        0 => Some(full(first, ONE)),
        1 => Some(full(second, ONE)),
        _ => None,
    }
}

const fn same_full(index: u8, sample: SampleStorage, count: NonZeroU8) -> Option<PixelPlane> {
    if index < count.get() {
        Some(full(sample, ONE))
    } else {
        None
    }
}

const fn rgba_planar(index: u8, color: SampleStorage, alpha: SampleStorage) -> Option<PixelPlane> {
    match index {
        0..=2 => Some(full(color, ONE)),
        3 => Some(full(alpha, ONE)),
        _ => None,
    }
}

const fn ycbcr_planar(
    index: u8,
    luma: SampleStorage,
    chroma: SampleStorage,
    subsampling: ChromaSubsampling,
    alpha: Option<SampleStorage>,
) -> Option<PixelPlane> {
    let (horizontal, vertical) = subsampling.factors();
    match index {
        0 => Some(full(luma, ONE)),
        1 | 2 => Some(PixelPlane::new(chroma, ONE, horizontal, vertical)),
        3 => match alpha {
            Some(sample) => Some(full(sample, ONE)),
            None => None,
        },
        _ => None,
    }
}

const fn ycbcr_semi(
    index: u8,
    luma: SampleStorage,
    chroma: SampleStorage,
    subsampling: ChromaSubsampling,
    alpha: Option<SampleStorage>,
) -> Option<PixelPlane> {
    let (horizontal, vertical) = subsampling.factors();
    match index {
        0 => Some(full(luma, ONE)),
        1 => Some(PixelPlane::new(chroma, TWO, horizontal, vertical)),
        2 => match alpha {
            Some(sample) => Some(full(sample, ONE)),
            None => None,
        },
        _ => None,
    }
}

fn divided_ceil(value: u32, divisor: NonZeroU8) -> u32 {
    value.div_ceil(u32::from(divisor.get()))
}