Skip to main content

fbsurface/
format.rs

1/*
2 * This file is part of strat9-os.
3 *
4 * strat9-os is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * strat9-os is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with strat9-os. If not, see <https://www.gnu.org/licenses/>.
16 *
17 * Website: https://www.strat9-os.org
18 * Repository: https://github.com/strat9-os/strat9-os
19 *
20 * Copyright (C) 2023-26 Guillaume Gielly
21 */
22
23//! Pixel formats and the packed-pixel newtype.
24//!
25//! [`Format`] is the crate's only source of truth for channel layout. It is
26//! a plain value with private fields, so a caller cannot build an
27//! inconsistent format (mask without shift, or the reverse) by accident.
28//!
29//! Colour conversion happens **only** through [`Format::pack`],
30//! [`Format::unpack`] and [`Format::convert`]. Bulk blits require identical
31//! formats; the conversion path is explicit and therefore visible at the
32//! call site, which is exactly what the old `CanvasBuffer::blit_rect`
33//! (packed XRGB in, native-format screen out) made impossible to see.
34
35/// An 8-bit-per-channel RGB triple, used at the boundaries.
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
37pub struct Rgb {
38    pub r: u8,
39    pub g: u8,
40    pub b: u8,
41}
42
43impl Rgb {
44    pub const BLACK: Self = Self::new(0, 0, 0);
45    pub const WHITE: Self = Self::new(0xFF, 0xFF, 0xFF);
46
47    #[inline]
48    pub const fn new(r: u8, g: u8, b: u8) -> Self {
49        Self { r, g, b }
50    }
51}
52
53/// A pixel already encoded in a [`Format`], with no implicit conversion.
54///
55/// Keeping the raw word in a newtype prevents the classic mix-up where a
56/// packed XRGB value is written to a screen whose native layout is BGRX.
57#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
58pub struct Packed(u32);
59
60impl Packed {
61    #[inline]
62    pub const fn raw(value: u32) -> Self {
63        Self(value)
64    }
65
66    #[inline]
67    pub const fn value(self) -> u32 {
68        self.0
69    }
70}
71
72/// Native pixel layout of a contiguous surface.
73///
74/// Supports the two layouts the kernel actually drives: 32 bpp and 24 bpp.
75/// 16 bpp can be represented (for `info` replies and future drivers) but is
76/// rejected by [`Canvas`](crate::Canvas) constructors, because the kernel
77/// SIMD paths have no 16 bpp implementation.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
79pub struct Format {
80    red_mask: u32,
81    red_shift: u8,
82    green_mask: u32,
83    green_shift: u8,
84    blue_mask: u32,
85    blue_shift: u8,
86    bits_per_pixel: u8,
87}
88
89impl Format {
90    /// Canonical format used by UEFI GOP on x86: `0x00RRGGBB` in a 32-bit
91    /// word, i.e. bytes `B, G, R, X` in memory.
92    pub const XRGB8888: Self =
93        Self::from_masks(32, 0x00FF_0000, 16, 0x0000_FF00, 8, 0x0000_00FF, 0);
94
95    /// Same 8-bit channels, but red in the low byte (`0x00BBGGRR`).
96    pub const BGRX8888: Self =
97        Self::from_masks(32, 0x0000_00FF, 0, 0x0000_FF00, 8, 0x00FF_0000, 16);
98
99    /// 24 bpp packed, `B, G, R` in memory.
100    pub const RGB888: Self = Self::from_masks(24, 0x00FF_0000, 16, 0x0000_FF00, 8, 0x0000_00FF, 0);
101
102    /// 16 bpp 5-6-5 (accepted by [`Format`], rejected by `Canvas` for now).
103    pub const RGB565: Self = Self::from_masks(16, 0xF800, 11, 0x07E0, 5, 0x001F, 0);
104
105    /// Build a format from explicit masks. Shifts are kept even when they
106    /// could be derived, so a driver that reports them can pass them
107    /// through unchanged.
108    #[inline]
109    pub const fn from_masks(
110        bits_per_pixel: u8,
111        red_mask: u32,
112        red_shift: u8,
113        green_mask: u32,
114        green_shift: u8,
115        blue_mask: u32,
116        blue_shift: u8,
117    ) -> Self {
118        Self {
119            red_mask,
120            red_shift,
121            green_mask,
122            green_shift,
123            blue_mask,
124            blue_shift,
125            bits_per_pixel,
126        }
127    }
128
129    #[inline]
130    pub const fn bits_per_pixel(self) -> u8 {
131        self.bits_per_pixel
132    }
133
134    #[inline]
135    pub const fn bytes_per_pixel(self) -> usize {
136        (self.bits_per_pixel / 8) as usize
137    }
138
139    #[inline]
140    pub const fn red_mask(self) -> u32 {
141        self.red_mask
142    }
143
144    #[inline]
145    pub const fn green_mask(self) -> u32 {
146        self.green_mask
147    }
148
149    #[inline]
150    pub const fn blue_mask(self) -> u32 {
151        self.blue_mask
152    }
153
154    #[inline]
155    pub const fn red_shift(self) -> u8 {
156        self.red_shift
157    }
158
159    #[inline]
160    pub const fn green_shift(self) -> u8 {
161        self.green_shift
162    }
163
164    #[inline]
165    pub const fn blue_shift(self) -> u8 {
166        self.blue_shift
167    }
168
169    /// Whether the drawing paths can drive this layout without conversion.
170    ///
171    /// 24 and 32 bpp only: those are the two widths implemented by
172    /// `PixelOps` and by the scalar fallbacks.
173    #[inline]
174    pub const fn is_supported(self) -> bool {
175        self.bits_per_pixel == 24 || self.bits_per_pixel == 32
176    }
177
178    #[inline]
179    pub const fn is_xrgb8888(self) -> bool {
180        self.bits_per_pixel == 32
181            && self.red_mask == 0x00FF_0000
182            && self.green_mask == 0x0000_FF00
183            && self.blue_mask == 0x0000_00FF
184            && self.red_shift == 16
185            && self.green_shift == 8
186            && self.blue_shift == 0
187    }
188
189    /// Whether the masks, shifts and width form a usable layout.
190    ///
191    /// [`Self::from_masks`] is public so a driver can pass its reported
192    /// layout through; this is the check that stops a malformed one from
193    /// reaching the pixel backends (shift overflow, mask wider than the
194    /// pixel, overlapping channels, or a shift that does not match the
195    /// mask).
196    pub const fn is_valid(self) -> bool {
197        if self.bits_per_pixel == 0 || self.bits_per_pixel > 32 {
198            return false;
199        }
200        if !mask_fits(self.red_mask, self.bits_per_pixel)
201            || !mask_fits(self.green_mask, self.bits_per_pixel)
202            || !mask_fits(self.blue_mask, self.bits_per_pixel)
203        {
204            return false;
205        }
206        if self.red_mask & self.green_mask != 0
207            || self.red_mask & self.blue_mask != 0
208            || self.green_mask & self.blue_mask != 0
209        {
210            return false;
211        }
212        channel_is_valid(self.red_mask, self.red_shift)
213            && channel_is_valid(self.green_mask, self.green_shift)
214            && channel_is_valid(self.blue_mask, self.blue_shift)
215    }
216
217    /// Two formats are compatible when a bulk copy can move raw words
218    /// between them without touching the bytes.
219    #[inline]
220    pub const fn compatible(self, other: Self) -> bool {
221        self.bits_per_pixel == other.bits_per_pixel
222            && self.red_mask == other.red_mask
223            && self.red_shift == other.red_shift
224            && self.green_mask == other.green_mask
225            && self.green_shift == other.green_shift
226            && self.blue_mask == other.blue_mask
227            && self.blue_shift == other.blue_shift
228    }
229
230    /// Encode an RGB triple into this layout.
231    ///
232    /// Channels narrower than 8 bits are truncated to their mask, never
233    /// shifted into the neighbouring channel. The unused byte of a 32 bpp
234    /// word is set opaque, matching the kernel's existing `pack_rgb`.
235    #[inline]
236    pub const fn pack(self, rgb: Rgb) -> Packed {
237        let mut v = ((rgb.r as u32) << self.red_shift) & self.red_mask;
238        v |= ((rgb.g as u32) << self.green_shift) & self.green_mask;
239        v |= ((rgb.b as u32) << self.blue_shift) & self.blue_mask;
240        if self.bits_per_pixel == 32 && self.red_mask & 0xFF00_0000 == 0 {
241            v |= 0xFF00_0000;
242        }
243        Packed(v)
244    }
245
246    /// Decode a pixel in this layout back to 8 bits per channel.
247    ///
248    /// Narrow channels are scaled (5 bits -> 8 bits) rather than shifted, so
249    /// a round trip through RGB565 is visually neutral.
250    pub const fn unpack(self, px: Packed) -> Rgb {
251        Rgb {
252            r: channel_to_u8(px.0, self.red_mask, self.red_shift),
253            g: channel_to_u8(px.0, self.green_mask, self.green_shift),
254            b: channel_to_u8(px.0, self.blue_mask, self.blue_shift),
255        }
256    }
257
258    /// Convert one pixel to another layout. This is the single conversion
259    /// point of the crate; everything else is a raw copy.
260    #[inline]
261    pub const fn convert(self, dst: Format, px: Packed) -> Packed {
262        if self.compatible(dst) {
263            return px;
264        }
265        dst.pack(self.unpack(px))
266    }
267
268    /// Convenience: pack an RGB triple without naming the format twice.
269    #[inline]
270    pub const fn rgb(self, r: u8, g: u8, b: u8) -> Packed {
271        self.pack(Rgb::new(r, g, b))
272    }
273
274    #[inline]
275    pub const fn black(self) -> Packed {
276        self.pack(Rgb::BLACK)
277    }
278
279    #[inline]
280    pub const fn white(self) -> Packed {
281        self.pack(Rgb::WHITE)
282    }
283}
284
285impl Default for Format {
286    fn default() -> Self {
287        Self::XRGB8888
288    }
289}
290
291/// A mask must not use bits above the pixel width.
292const fn mask_fits(mask: u32, bits_per_pixel: u8) -> bool {
293    bits_per_pixel >= 32 || (mask >> bits_per_pixel) == 0
294}
295
296/// A channel is a contiguous run of ones at exactly `shift`. An empty mask
297/// has no shift, and any other shift would make [`Format::pack`] overflow.
298const fn channel_is_valid(mask: u32, shift: u8) -> bool {
299    // Even an empty channel must keep its shift in range: `pack` still
300    // evaluates `value << shift` before masking it away.
301    if shift >= 32 {
302        return false;
303    }
304    if mask == 0 {
305        return true;
306    }
307    if mask.trailing_zeros() != shift as u32 {
308        return false;
309    }
310    let run = mask >> shift;
311    // 2^n - 1, n >= 1.
312    run != 0 && (run & run.wrapping_add(1)) == 0
313}
314
315/// Extract one channel and scale it to 8 bits.
316const fn channel_to_u8(px: u32, mask: u32, shift: u8) -> u8 {
317    if mask == 0 {
318        return 0;
319    }
320    let max = mask >> shift;
321    let value = (px & mask) >> shift;
322    if max == 0xFF {
323        value as u8
324    } else {
325        // Rounded scaling, overflow-free: value <= max, max <= u32::MAX.
326        ((value as u64 * 255 + (max as u64 / 2)) / max as u64) as u8
327    }
328}
329
330#[cfg(test)]
331mod tests {
332    use super::*;
333
334    #[test]
335    fn xrgb_pack_is_opaque_and_ordered() {
336        let p = Format::XRGB8888.pack(Rgb::new(0x12, 0x34, 0x56));
337        assert_eq!(p.value(), 0xFF12_3456);
338        assert_eq!(Format::XRGB8888.unpack(p), Rgb::new(0x12, 0x34, 0x56));
339    }
340
341    #[test]
342    fn bgrx_swaps_red_and_blue() {
343        let p = Format::BGRX8888.pack(Rgb::new(0x12, 0x34, 0x56));
344        assert_eq!(p.value(), 0xFF56_3412);
345        assert_eq!(Format::BGRX8888.unpack(p), Rgb::new(0x12, 0x34, 0x56));
346    }
347
348    #[test]
349    fn rgb565_truncates_without_bleeding() {
350        // 0xFF must fit in the 5-bit red field, not spill into green.
351        let p = Format::RGB565.pack(Rgb::new(0xFF, 0x00, 0x00));
352        assert_eq!(p.value(), 0xF800);
353        // Round trip is close, not exact.
354        let back = Format::RGB565.unpack(p);
355        assert_eq!(back.g, 0);
356        assert_eq!(back.b, 0);
357        assert!(back.r >= 247);
358    }
359
360    #[test]
361    fn rgb888_pack_does_not_set_alpha() {
362        let p = Format::RGB888.pack(Rgb::WHITE);
363        assert_eq!(p.value(), 0x00FF_FFFF);
364    }
365
366    #[test]
367    fn convert_xrgb_to_bgrx_round_trips() {
368        let src = Format::XRGB8888.rgb(1, 2, 3);
369        let dst = Format::XRGB8888.convert(Format::BGRX8888, src);
370        assert_eq!(dst.value(), 0xFF03_0201);
371        let back = Format::BGRX8888.convert(Format::XRGB8888, dst);
372        assert_eq!(back, src);
373    }
374
375    #[test]
376    fn identical_formats_are_bitwise_copies() {
377        let p = Packed::raw(0xDEAD_BEEF);
378        assert_eq!(Format::XRGB8888.convert(Format::XRGB8888, p), p);
379        assert!(Format::XRGB8888.compatible(Format::XRGB8888));
380        assert!(!Format::XRGB8888.compatible(Format::RGB888));
381    }
382
383    #[test]
384    fn invalid_layouts_are_rejected() {
385        assert!(Format::XRGB8888.is_valid());
386        assert!(Format::BGRX8888.is_valid());
387        assert!(Format::RGB888.is_valid());
388        assert!(Format::RGB565.is_valid());
389        // Shift that does not match the mask.
390        assert!(!Format::from_masks(32, 0x00FF_0000, 8, 0, 0, 0, 0).is_valid());
391        // Shift out of range: `pack` would overflow.
392        assert!(!Format::from_masks(32, 0, 0, 0, 0, 0, 40).is_valid());
393        // Channel wider than the pixel.
394        assert!(!Format::from_masks(24, 0xFF00_0000, 16, 0, 0, 0, 0).is_valid());
395        // Overlapping channels.
396        assert!(!Format::from_masks(32, 0x0000_FF00, 8, 0x0000_0F00, 8, 0, 0).is_valid());
397    }
398
399    #[test]
400    fn bytes_per_pixel_matches_width() {
401        assert_eq!(Format::XRGB8888.bytes_per_pixel(), 4);
402        assert_eq!(Format::RGB888.bytes_per_pixel(), 3);
403        assert_eq!(Format::RGB565.bytes_per_pixel(), 2);
404        assert!(Format::XRGB8888.is_supported());
405        assert!(!Format::RGB565.is_supported());
406    }
407}