Skip to main content

oa/ui/
image.rs

1//! Planar multi-dtype images for `Ui::image_planar`/`Ui::image_plane`.
2//!
3//! Donor: `oa/ui/image.h` and `oa/ui/image.cpp`.
4//!
5//! [`ImagePlanes`] stores one device buffer per channel, each in an
6//! independent [`ImageDtype`]. Plane buffers are retained `Matrix` values —
7//! display consumption through `Ui` retains them automatically until frame
8//! completion, so the donor's manual `markConsumed` contract has no owner
9//! here.
10//!
11//! Typical flows:
12//! ```ignore
13//! let planes = ImagePlanes::load_file(&runtime, "frame.png")?;       // planar U8
14//! let planes = ImagePlanes::from_planes(&runtime, &[&r, &d],         // RGB + U16 depth
15//!     &[ImageDtype::U8, ImageDtype::U16], 640, 480)?;
16//! ui.image_planar(&planes, 0, 0)?;
17//! ui.image_plane(&planes, 1, 0, 0)?; // depth channel as grayscale
18//! ```
19
20use std::path::Path;
21
22use crate::runtime::RuntimeHandle;
23use crate::{Error, Matrix, Result, Runtime};
24
25/// Per-channel storage type; selects the `blit_planar` normalization path.
26///
27/// Donor: `oa::ImageDtype`.
28#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
29#[repr(u8)]
30pub enum ImageDtype {
31	/// `uint8` `[0, 255]` normalized to `[0.0, 1.0]`.
32	#[default]
33	U8 = 0,
34	/// `uint16` `[0, 65535]` normalized to `[0.0, 1.0]`.
35	U16 = 1,
36	/// `float32` passed through as-is.
37	F32 = 2,
38	/// `bfloat16` decoded to float32, passed through as-is.
39	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
52/// Maximum channel/plane count: 1=gray, 2=gray+alpha, 3=RGB, 4=RGBA/RGB+depth.
53///
54/// Donor: `oa::kImageMaxPlanes`.
55pub const IMAGE_MAX_PLANES: usize = 4;
56
57/// Planar image: one retained device buffer per channel, independent dtype.
58///
59/// Each plane is a flat row-major array of `width * height` elements. Missing
60/// alpha (fewer than 4 channels) defaults to `1.0` in the blit shader. The
61/// value owns its plane storage; cloning plane buffers for frame retention is
62/// internal to `Ui`.
63///
64/// Donor: `oa::ImagePlanes`.
65pub struct ImagePlanes {
66	runtime: RuntimeHandle,
67	planes: Vec<Matrix>,
68	dtypes: Vec<ImageDtype>,
69	width: i32,
70	height: i32,
71}
72
73impl ImagePlanes {
74	/// Return the dtype stored for `channel` (`U8` when out of range).
75	#[must_use]
76	pub fn plane_dtype(&self, channel: usize) -> ImageDtype {
77		self.dtypes.get(channel).copied().unwrap_or_default()
78	}
79
80	/// Return the image width in pixels.
81	#[must_use]
82	pub const fn width(&self) -> i32 {
83		self.width
84	}
85
86	/// Return the image height in pixels.
87	#[must_use]
88	pub const fn height(&self) -> i32 {
89		self.height
90	}
91
92	/// Return the number of planes (1–4).
93	#[must_use]
94	pub fn channel_count(&self) -> usize {
95		self.planes.len()
96	}
97
98	/// Return whether the image has positive dimensions and live planes.
99	#[must_use]
100	pub fn is_valid(&self) -> bool {
101		self.width > 0 && self.height > 0 && !self.planes.is_empty()
102	}
103
104	/// Bindless buffer index for `channel`, or `u32::MAX` when absent.
105	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	/// Clone the retained plane storages for frame-scope retention.
119	pub(crate) fn retain_planes(&self, frame_matrices: &mut Vec<Matrix>) {
120		frame_matrices.extend(self.planes.iter().cloned());
121	}
122
123	/// Decode a supported image file into planar channels.
124	///
125	/// Preserves the file's channel count: 1=gray, 2=gray+alpha, 3=RGB,
126	/// 4=RGBA. 8-bit files upload `U8` planes, 16-bit files `U16`, and
127	/// floating-point (HDR) files `F32`. This is a synchronous host codec
128	/// boundary followed by device uploads.
129	///
130	/// # Errors
131	///
132	/// Returns an error for an unreadable, unsupported, or malformed file,
133	/// checked-size overflow, or device upload failure.
134	///
135	/// This variant loads on this thread's default runtime. An runtime
136	/// initialization failure is returned before decoding starts.
137	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	/// Load an image file into device-uploaded planes on a particular runtime.
142	///
143	/// This is the [`load_file`](Self::load_file) contract evaluated on
144	/// `runtime` instead of this thread's default runtime.
145	///
146	/// # Errors
147	///
148	/// Returns the same errors as [`load_file`](Self::load_file).
149	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	/// Upload caller-provided planes.
209	///
210	/// `planes` and `dtypes` must have the same length (1–4); each span holds
211	/// exactly `width * height * sizeof(dtype)` bytes. Synchronous.
212	///
213	/// # Errors
214	///
215	/// Returns an error for a channel count outside 1–4, a planes/dtypes
216	/// length mismatch, non-positive or overflowing dimensions, a plane byte
217	/// size that does not match its dtype, or device upload failure.
218	///
219	/// This variant uploads on this thread's default runtime. An runtime
220	/// initialization failure is returned before the upload starts.
221	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	/// Upload caller-provided planes on a particular runtime.
231	///
232	/// This is the [`from_planes`](Self::from_planes) contract evaluated on
233	/// `runtime` instead of this thread's default runtime.
234	///
235	/// # Errors
236	///
237	/// Returns the same errors as [`from_planes`](Self::from_planes).
238	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}