forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB2602aecTahinli6 days ago3958 commits

transform.rs201 lines, 7.1 KiBHistoryRawDownload
1//! Pixel transforms for packed 8-bit buffers: quarter turns, half turns and
2//! mirrors, and the EXIF orientation that combines them.
3//!
4//! Buffers are row-major, top row first, with no padding: `width * height *
5//! bytes_per_pixel` bytes. A turn of a `w x h` image is `h x w`. Every function
6//! returns a new buffer; the input is never modified.
7
8use ec_core::{Error, Result};
9
10/// The packed 8-bit pixel layouts the transforms accept.
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum Layout {
13 /// Three bytes per pixel: R, G, B.
14 Rgb8,
15 /// Four bytes per pixel: R, G, B, A.
16 Rgba8,
17}
18
19impl Layout {
20 /// Bytes in one pixel.
21 pub fn bytes_per_pixel(self) -> usize {
22 match self {
23 Layout::Rgb8 => 3,
24 Layout::Rgba8 => 4,
25 }
26 }
27}
28
29/// Turn clockwise by 90 degrees. The result is `height x width`.
30pub fn rotate90(layout: Layout, width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>> {
31 let (w, h) = dims(layout, width, height, pixels)?;
32 Ok(map(layout, w, pixels, h, w, |x, y| (y, h - 1 - x)))
33}
34
35/// Turn by 180 degrees. The result is `width x height`.
36pub fn rotate180(layout: Layout, width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>> {
37 let (w, h) = dims(layout, width, height, pixels)?;
38 Ok(map(layout, w, pixels, w, h, |x, y| (w - 1 - x, h - 1 - y)))
39}
40
41/// Turn counter-clockwise by 90 degrees (clockwise by 270). The result is `height x width`.
42pub fn rotate270(layout: Layout, width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>> {
43 let (w, h) = dims(layout, width, height, pixels)?;
44 Ok(map(layout, w, pixels, h, w, |x, y| (w - 1 - y, x)))
45}
46
47/// Mirror left to right. Dimensions are unchanged.
48pub fn flip_horizontal(layout: Layout, width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>> {
49 let (w, h) = dims(layout, width, height, pixels)?;
50 Ok(map(layout, w, pixels, w, h, |x, y| (w - 1 - x, y)))
51}
52
53/// Mirror top to bottom. Dimensions are unchanged.
54pub fn flip_vertical(layout: Layout, width: u32, height: u32, pixels: &[u8]) -> Result<Vec<u8>> {
55 let (w, h) = dims(layout, width, height, pixels)?;
56 Ok(map(layout, w, pixels, w, h, |x, y| (x, h - 1 - y)))
57}
58
59/// Apply an EXIF orientation (1..=8) so the pixels are upright.
60///
61/// Returns `(width, height, pixels)` of the upright image. Orientation 1 copies
62/// the input unchanged. The mapping is the one `image` applies (its
63/// `DynamicImage::apply_orientation`), which follows the EXIF 2.3 table.
64pub fn apply_orientation(
65 layout: Layout,
66 width: u32,
67 height: u32,
68 pixels: &[u8],
69 orientation: u8,
70) -> Result<(u32, u32, Vec<u8>)> {
71 match orientation {
72 1 => Ok((width, height, pixels.to_vec())),
73 2 => Ok((
74 width,
75 height,
76 flip_horizontal(layout, width, height, pixels)?,
77 )),
78 3 => Ok((width, height, rotate180(layout, width, height, pixels)?)),
79 4 => Ok((width, height, flip_vertical(layout, width, height, pixels)?)),
80 5 => {
81 let t = rotate90(layout, width, height, pixels)?;
82 Ok((height, width, flip_horizontal(layout, height, width, &t)?))
83 }
84 6 => Ok((height, width, rotate90(layout, width, height, pixels)?)),
85 7 => {
86 let t = rotate270(layout, width, height, pixels)?;
87 Ok((height, width, flip_horizontal(layout, height, width, &t)?))
88 }
89 8 => Ok((height, width, rotate270(layout, width, height, pixels)?)),
90 other => Err(Error::unsupported(
91 "EXIF orientation",
92 format!("{other} is not one of 1..=8"),
93 )),
94 }
95}
96
97/// Validate a buffer against its dimensions, returning the dimensions as `usize`.
98fn dims(layout: Layout, width: u32, height: u32, pixels: &[u8]) -> Result<(usize, usize)> {
99 let (w, h) = (width as usize, height as usize);
100 let need = w
101 .checked_mul(h)
102 .and_then(|p| p.checked_mul(layout.bytes_per_pixel()))
103 .ok_or_else(|| Error::unsupported("transform", "image size overflows"))?;
104 if pixels.len() != need {
105 return Err(Error::unsupported(
106 "transform",
107 format!("{} bytes for {width}x{height} (need {need})", pixels.len()),
108 ));
109 }
110 Ok((w, h))
111}
112
113/// Build a `dst_w x dst_h` buffer where destination pixel `(x, y)` is copied from
114/// source pixel `src(x, y)`. The caller has validated `pixels` against `w x h`.
115fn map(
116 layout: Layout,
117 w: usize,
118 pixels: &[u8],
119 dst_w: usize,
120 dst_h: usize,
121 src: impl Fn(usize, usize) -> (usize, usize),
122) -> Vec<u8> {
123 let bpp = layout.bytes_per_pixel();
124 let mut out = Vec::with_capacity(dst_w * dst_h * bpp);
125 for y in 0..dst_h {
126 for x in 0..dst_w {
127 let (sx, sy) = src(x, y);
128 let at = (sy * w + sx) * bpp;
129 out.extend_from_slice(&pixels[at..at + bpp]);
130 }
131 }
132 out
133}
134
135#[cfg(test)]
136mod tests {
137 use super::*;
138
139 // A 3x2 RGB image whose pixel values spell their position: 10*y + x in R.
140 fn sample() -> Vec<u8> {
141 let mut v = Vec::new();
142 for y in 0..2u8 {
143 for x in 0..3u8 {
144 v.extend_from_slice(&[10 * y + x, 0, 0]);
145 }
146 }
147 v
148 }
149
150 #[test]
151 fn quarter_turn_moves_the_top_left_pixel_to_the_top_right() {
152 let r = rotate90(Layout::Rgb8, 3, 2, &sample()).unwrap();
153 // 2 wide, 3 tall: row 0 is the old column 0 read bottom to top.
154 let reds: Vec<u8> = r.chunks(3).map(|p| p[0]).collect();
155 assert_eq!(reds, vec![10, 0, 11, 1, 12, 2]);
156 }
157
158 #[test]
159 fn a_full_cycle_is_the_identity() {
160 let s = sample();
161 let a = rotate90(Layout::Rgb8, 3, 2, &s).unwrap();
162 let b = rotate90(Layout::Rgb8, 2, 3, &a).unwrap();
163 let c = rotate90(Layout::Rgb8, 3, 2, &b).unwrap();
164 let d = rotate90(Layout::Rgb8, 2, 3, &c).unwrap();
165 assert_eq!(d, s);
166 let half = rotate180(Layout::Rgb8, 3, 2, &s).unwrap();
167 assert_eq!(rotate180(Layout::Rgb8, 3, 2, &half).unwrap(), s);
168 assert_eq!(
169 rotate270(Layout::Rgb8, 3, 2, &s).unwrap(),
170 rotate90(Layout::Rgb8, 3, 2, &half).unwrap()
171 );
172 }
173
174 #[test]
175 fn mirrors_keep_dimensions_and_are_involutions() {
176 let s = sample();
177 let h = flip_horizontal(Layout::Rgb8, 3, 2, &s).unwrap();
178 assert_eq!(h[0], 2);
179 assert_eq!(flip_horizontal(Layout::Rgb8, 3, 2, &h).unwrap(), s);
180 let v = flip_vertical(Layout::Rgba8, 1, 2, &[1, 1, 1, 1, 2, 2, 2, 2]).unwrap();
181 assert_eq!(v, vec![2, 2, 2, 2, 1, 1, 1, 1]);
182 }
183
184 #[test]
185 fn every_orientation_gives_the_right_size_and_is_refused_outside_1_to_8() {
186 let s = sample();
187 for o in 1..=8u8 {
188 let (w, h, px) = apply_orientation(Layout::Rgb8, 3, 2, &s, o).unwrap();
189 assert_eq!(px.len(), (w * h * 3) as usize);
190 let expect = if o >= 5 { (2, 3) } else { (3, 2) };
191 assert_eq!((w, h), expect, "orientation {o}");
192 }
193 assert!(apply_orientation(Layout::Rgb8, 3, 2, &s, 0).is_err());
194 assert!(apply_orientation(Layout::Rgb8, 3, 2, &s, 9).is_err());
195 }
196
197 #[test]
198 fn a_mismatched_buffer_is_refused() {
199 assert!(rotate90(Layout::Rgba8, 3, 2, &sample()).is_err());
200 }
201}