1use std::path::Path;
21
22use crate::runtime::RuntimeHandle;
23use crate::{Error, Matrix, Result, Runtime};
24
25#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29#[repr(u8)]
30pub enum ImageDtype {
31 #[default]
33 U8 = 0,
34 U16 = 1,
36 F32 = 2,
38 Bf16 = 3,
40}
41
42impl ImageDtype {
43 const fn scalar_bytes(self) -> usize {
44 match self {
45 Self::U8 => 1,
46 Self::U16 | Self::Bf16 => 2,
47 Self::F32 => 4,
48 }
49 }
50}
51
52pub const IMAGE_MAX_PLANES: usize = 4;
56
57pub struct ImagePlanes {
66 runtime: RuntimeHandle,
67 planes: Vec<Matrix>,
68 dtypes: Vec<ImageDtype>,
69 width: i32,
70 height: i32,
71}
72
73impl ImagePlanes {
74 #[must_use]
76 pub fn plane_dtype(&self, channel: usize) -> ImageDtype {
77 self.dtypes.get(channel).copied().unwrap_or_default()
78 }
79
80 #[must_use]
82 pub const fn width(&self) -> i32 {
83 self.width
84 }
85
86 #[must_use]
88 pub const fn height(&self) -> i32 {
89 self.height
90 }
91
92 #[must_use]
94 pub fn channel_count(&self) -> usize {
95 self.planes.len()
96 }
97
98 #[must_use]
100 pub fn is_valid(&self) -> bool {
101 self.width > 0 && self.height > 0 && !self.planes.is_empty()
102 }
103
104 pub(crate) fn plane_index(&self, channel: usize) -> Result<u32> {
106 if channel >= self.planes.len() {
107 return Ok(u32::MAX);
108 }
109 self
110 .runtime
111 .storage_descriptor_index(self.planes[channel].storage())
112 }
113
114 pub(crate) const fn runtime(&self) -> &RuntimeHandle {
115 &self.runtime
116 }
117
118 pub(crate) fn retain_planes(&self, frame_matrices: &mut Vec<Matrix>) {
120 frame_matrices.extend(self.planes.iter().cloned());
121 }
122
123 pub fn load_file(path: impl AsRef<Path>) -> Result<Self> {
138 let path = path.as_ref();
139 Self::load_file_on(&Runtime::current()?, path)
140 }
141 pub fn load_file_on(runtime: &Runtime, path: impl AsRef<Path>) -> Result<Self> {
150 let path = path.as_ref();
151 if path.as_os_str().is_empty() {
152 return Err(Error::invalid_argument(
153 "ImagePlanes::load_file path is empty",
154 ));
155 }
156 let encoded = std::fs::read(path).map_err(|source| Error::io("image file read", source))?;
157 let decoded = image_codec::load_from_memory(&encoded)
158 .map_err(|source| Error::backend_failure("image", "decode", source))?;
159 let (channels, dtype) = match &decoded {
160 image_codec::DynamicImage::ImageLuma8(_) => (1_usize, ImageDtype::U8),
161 image_codec::DynamicImage::ImageLumaA8(_) => (2, ImageDtype::U8),
162 image_codec::DynamicImage::ImageRgb8(_) => (3, ImageDtype::U8),
163 image_codec::DynamicImage::ImageRgba8(_) => (4, ImageDtype::U8),
164 image_codec::DynamicImage::ImageLuma16(_) => (1, ImageDtype::U16),
165 image_codec::DynamicImage::ImageLumaA16(_) => (2, ImageDtype::U16),
166 image_codec::DynamicImage::ImageRgb16(_) => (3, ImageDtype::U16),
167 image_codec::DynamicImage::ImageRgba16(_) => (4, ImageDtype::U16),
168 image_codec::DynamicImage::ImageRgb32F(_) => (3, ImageDtype::F32),
169 image_codec::DynamicImage::ImageRgba32F(_) => (4, ImageDtype::F32),
170 _ => {
171 return Err(Error::invalid_argument(
172 "ImagePlanes::load_file decoded an unsupported pixel format",
173 ));
174 }
175 };
176 let width = usize::try_from(decoded.width())
177 .map_err(|_| Error::out_of_range("decoded image width exceeds usize"))?;
178 let height = usize::try_from(decoded.height())
179 .map_err(|_| Error::out_of_range("decoded image height exceeds usize"))?;
180 let bytes = decoded.into_bytes();
181 let scalar = dtype.scalar_bytes();
182 let stride = channels * scalar;
183 if bytes.len() != width * height * stride {
184 return Err(Error::internal(
185 "decoded plane byte count does not match extent",
186 ));
187 }
188 let plane_bytes = (0..channels)
189 .map(|channel| {
190 bytes
191 .chunks_exact(stride)
192 .flat_map(|pixel| &pixel[channel * scalar..(channel + 1) * scalar])
193 .copied()
194 .collect::<Vec<u8>>()
195 })
196 .collect::<Vec<_>>();
197 let spans = plane_bytes.iter().map(Vec::as_slice).collect::<Vec<_>>();
198 let dtypes = vec![dtype; channels];
199 Self::from_planes_on(
200 runtime,
201 &spans,
202 &dtypes,
203 i32::try_from(width).map_err(|_| Error::out_of_range("image width exceeds i32"))?,
204 i32::try_from(height).map_err(|_| Error::out_of_range("image height exceeds i32"))?,
205 )
206 }
207
208 pub fn from_planes(
222 planes: &[&[u8]],
223 dtypes: &[ImageDtype],
224 width: i32,
225 height: i32,
226 ) -> Result<Self> {
227 Self::from_planes_on(&Runtime::current()?, planes, dtypes, width, height)
228 }
229
230 pub fn from_planes_on(
239 runtime: &Runtime,
240 planes: &[&[u8]],
241 dtypes: &[ImageDtype],
242 width: i32,
243 height: i32,
244 ) -> Result<Self> {
245 if planes.is_empty() || planes.len() > IMAGE_MAX_PLANES {
246 return Err(Error::invalid_argument(
247 "ImagePlanes::from_planes channel count must be 1-4",
248 ));
249 }
250 if planes.len() != dtypes.len() {
251 return Err(Error::invalid_argument(
252 "ImagePlanes::from_planes planes/dtypes size mismatch",
253 ));
254 }
255 if width <= 0 || height <= 0 {
256 return Err(Error::invalid_argument(
257 "ImagePlanes::from_planes dimensions must be positive",
258 ));
259 }
260 let pixels = (width as u64)
261 .checked_mul(height as u64)
262 .ok_or_else(|| Error::invalid_argument("ImagePlanes::from_planes pixel count overflows"))?;
263 let mut uploaded = Vec::with_capacity(planes.len());
264 for (index, (plane, dtype)) in planes.iter().zip(dtypes).enumerate() {
265 let expected = usize::try_from(pixels.checked_mul(dtype.scalar_bytes() as u64).ok_or_else(
266 || Error::invalid_argument("ImagePlanes::from_planes plane byte size overflows"),
267 )?)
268 .map_err(|_| Error::invalid_argument("ImagePlanes::from_planes plane byte size overflows"))?;
269 if plane.len() != expected {
270 return Err(Error::invalid_argument(format!(
271 "ImagePlanes::from_planes plane {index} byte size does not match dimensions and dtype",
272 )));
273 }
274 uploaded.push(Matrix::new_from_slice_on(runtime, [expected], plane)?);
275 }
276 Ok(Self {
277 runtime: runtime.handle(),
278 planes: uploaded,
279 dtypes: dtypes.to_vec(),
280 width,
281 height,
282 })
283 }
284}