Skip to main content

oa/image/codec/
decode.rs

1//! Synchronous CPU decoding into semantic [`crate::Image`] values.
2
3use std::{fs, path::Path};
4
5use crate::{Error, Image, ImageFormat, ImageLayout, Matrix, Result, Runtime};
6
7use super::detect_codec;
8
9/// Decode a JPEG, PNG, WebP, BMP, TGA, or TIFF file and upload normalized planar FP32 pixels.
10///
11/// The result is one NCHW image shaped `[1, channels, height, width]`. This is
12/// a synchronous host codec boundary followed by device upload.
13///
14/// # Errors
15///
16/// Returns an error for an empty path, filesystem failure, unsupported or
17/// malformed media, unsupported requested format, checked-size overflow, or
18/// device allocation/upload failure.
19///
20/// This variant decodes on this thread's default runtime. An runtime
21/// initialization failure is returned before decoding starts.
22pub fn decode_file(path: impl AsRef<Path>, format: ImageFormat) -> Result<Image> {
23	let path = path.as_ref();
24	decode_file_on(&Runtime::current()?, path, format)
25}
26/// Decode a JPEG, PNG, WebP, BMP, TGA, or TIFF file and upload normalized planar FP32
27/// pixels on a particular runtime.
28///
29/// This is the [`decode_file`] contract evaluated on `runtime` instead of this
30/// thread's default runtime.
31///
32/// # Errors
33///
34/// Returns the same errors as [`decode_file`].
35pub fn decode_file_on(
36	runtime: &Runtime,
37	path: impl AsRef<Path>,
38	format: ImageFormat,
39) -> Result<Image> {
40	let path = path.as_ref();
41	if path.as_os_str().is_empty() {
42		return Err(Error::invalid_argument("image::decode_file path is empty"));
43	}
44	let encoded = fs::read(path).map_err(|source| Error::io("image file read", source))?;
45	decode_memory_on(runtime, &encoded, format)
46}
47
48/// Decode JPEG, PNG, WebP, BMP, TGA, or TIFF bytes and upload normalized planar FP32 pixels.
49///
50/// The requested output format may be Gray, Rgb, or Rgba. The result is one
51/// NCHW image shaped `[1, channels, height, width]`.
52///
53/// # Errors
54///
55/// Returns an error for empty, unsupported, or malformed media, unsupported
56/// requested format, checked-size overflow, or device allocation/upload
57/// failure.
58///
59/// This variant decodes on this thread's default runtime. An runtime
60/// initialization failure is returned before decoding starts.
61pub fn decode_memory(encoded: &[u8], format: ImageFormat) -> Result<Image> {
62	decode_memory_on(&Runtime::current()?, encoded, format)
63}
64
65/// Decode JPEG, PNG, WebP, BMP, TGA, or TIFF bytes and upload normalized planar FP32
66/// pixels on a particular runtime.
67///
68/// # Errors
69///
70/// Returns an error for empty, unsupported, or malformed media, unsupported
71/// requested format, checked-size overflow, or device allocation/upload
72/// failure.
73pub fn decode_memory_on(runtime: &Runtime, encoded: &[u8], format: ImageFormat) -> Result<Image> {
74	if encoded.is_empty() {
75		return Err(Error::invalid_argument(
76			"image::decode_memory input buffer is empty",
77		));
78	}
79	if !matches!(
80		format,
81		ImageFormat::Gray | ImageFormat::Rgb | ImageFormat::Rgba
82	) {
83		return Err(Error::invalid_argument(
84			"image::decode_memory output format must be Gray, Rgb, or Rgba",
85		));
86	}
87	let codec = detect_codec(encoded).ok_or_else(|| {
88		Error::invalid_argument("image::decode_memory bitstream is unsupported or unrecognized")
89	})?;
90	let external = super::external_format(codec)
91		.ok_or_else(|| Error::internal("detected image codec has no decoder format"))?;
92	let decoded = image_codec::load_from_memory_with_format(encoded, external)
93		.map_err(|source| Error::backend_failure("image", "decode", source))?;
94	let width = usize::try_from(decoded.width())
95		.map_err(|_| Error::out_of_range("decoded image width exceeds usize"))?;
96	let height = usize::try_from(decoded.height())
97		.map_err(|_| Error::out_of_range("decoded image height exceeds usize"))?;
98	if width == 0 || height == 0 {
99		return Err(Error::invalid_argument(
100			"image::decode_memory decoded an empty image",
101		));
102	}
103
104	let packed = match format {
105		ImageFormat::Gray => decoded.to_luma8().into_raw(),
106		ImageFormat::Rgb => decoded.to_rgb8().into_raw(),
107		ImageFormat::Rgba => decoded.to_rgba8().into_raw(),
108		_ => unreachable!("requested output format was validated"),
109	};
110	upload_packed(runtime, &packed, width, height, format)
111}
112
113fn upload_packed(
114	runtime: &Runtime,
115	packed: &[u8],
116	width: usize,
117	height: usize,
118	format: ImageFormat,
119) -> Result<Image> {
120	let channels = format.channels();
121	let pixels = width
122		.checked_mul(height)
123		.ok_or_else(|| Error::out_of_range("decoded image pixel count overflows usize"))?;
124	let elements = pixels
125		.checked_mul(channels)
126		.ok_or_else(|| Error::out_of_range("decoded image element count overflows usize"))?;
127	if packed.len() != elements {
128		return Err(Error::internal(
129			"decoded image pixel count does not match its metadata",
130		));
131	}
132	let mut planar = Vec::new();
133	planar
134		.try_reserve_exact(elements)
135		.map_err(|_| Error::resource_exhausted("decoded image allocation failed"))?;
136	planar.resize(elements, 0.0_f32);
137	for pixel in 0..pixels {
138		for channel in 0..channels {
139			planar[channel * pixels + pixel] = f32::from(packed[pixel * channels + channel]) / 255.0;
140		}
141	}
142	let matrix = Matrix::new_from_slice_on(runtime, [1, channels, height, width], &planar)?;
143	Image::new(matrix, ImageLayout::Nchw, format)
144}