use std::path::Path;
use crate::imageio::validate_buffer_len;
use crate::{path_to_utf8, pixel, sys, Error, ImageSpec, Pixel, PixelFormat, Result, Roi};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Wrap {
Default,
Black,
Clamp,
Periodic,
Mirror,
}
impl Wrap {
fn to_sys(self) -> sys::imagebuf::WrapMode {
match self {
Self::Default => sys::imagebuf::WrapMode::WrapDefault,
Self::Black => sys::imagebuf::WrapMode::WrapBlack,
Self::Clamp => sys::imagebuf::WrapMode::WrapClamp,
Self::Periodic => sys::imagebuf::WrapMode::WrapPeriodic,
Self::Mirror => sys::imagebuf::WrapMode::WrapMirror,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Storage {
Uninitialized,
Local,
App,
Cache,
}
impl Storage {
fn from_sys(storage: sys::imagebuf::IBStorage) -> Self {
match storage {
sys::imagebuf::IBStorage::LOCALBUFFER => Self::Local,
sys::imagebuf::IBStorage::APPBUFFER => Self::App,
sys::imagebuf::IBStorage::IMAGECACHE => Self::Cache,
_ => Self::Uninitialized,
}
}
}
pub struct ImageBuf {
inner: cxx::UniquePtr<sys::imagebuf::ImageBuf>,
}
unsafe impl Send for ImageBuf {}
impl ImageBuf {
pub fn empty() -> Result<Self> {
Self::from_inner(sys::imagebuf::imagebuf_default(), "create image buffer")
}
pub fn new(spec: &ImageSpec) -> Result<Self> {
if spec.is_deep() {
let pixels = spec.pixel_count()?;
if pixels > i32::MAX as usize {
return Err(Error::InvalidImageSpec(format!(
"a deep image is limited to {} pixels, and this spec has {pixels}",
i32::MAX
)));
}
}
let native_spec = spec.to_sys()?;
let Some(native_spec) = native_spec.as_ref() else {
return Err(Error::InvalidImageSpec(
"OpenImageIO could not allocate an image specification".to_owned(),
));
};
let mut error = String::new();
let inner = sys::imagebuf::imagebuf_new_from_spec_checked(native_spec, &mut error);
if inner.is_null() && !error.is_empty() {
return Err(Error::operation("allocate image buffer", error));
}
Self::from_inner(inner, "allocate image buffer")
}
pub fn from_path(image_path: &Path) -> Result<Self> {
Self::from_path_at(image_path, 0, 0)
}
pub fn from_path_at(image_path: &Path, subimage: u32, mip_level: u32) -> Result<Self> {
let filename = path_to_utf8(image_path)?;
let subimage = level_index(subimage)?;
let mip_level = level_index(mip_level)?;
let inner = unsafe {
sys::imagebuf::imagebuf_new_from_file(
filename,
subimage,
mip_level,
cxx::SharedPtr::null(),
std::ptr::null(),
std::ptr::null_mut(),
)
};
let mut buffer = Self::from_inner(inner, "open image buffer")?;
if !sys::imagebuf::imagebuf_init_spec(buffer.inner_mut(), filename, subimage, mip_level) {
return Err(Error::OpenImage {
path: image_path.to_path_buf(),
message: buffer.take_error(),
});
}
Ok(buffer)
}
pub fn read(&mut self) -> Result<()> {
self.read_at(self.subimage(), self.mip_level(), None)
}
pub fn read_at(
&mut self,
subimage: u32,
mip_level: u32,
convert_to: Option<PixelFormat>,
) -> Result<()> {
let subimage = level_index(subimage)?;
let mip_level = level_index(mip_level)?;
let convert = convert_to.unwrap_or(PixelFormat::Other).to_sys();
let succeeded =
sys::imagebuf::imagebuf_read(self.inner_mut(), subimage, mip_level, true, convert);
self.check("read image buffer", succeeded)
}
pub fn read_channels(&mut self, channels: std::ops::Range<u32>) -> Result<()> {
self.read_channels_at(0, 0, channels, None)
}
pub fn read_channels_at(
&mut self,
subimage: u32,
mip_level: u32,
channels: std::ops::Range<u32>,
convert_to: Option<PixelFormat>,
) -> Result<()> {
const OPERATION: &str = "read image buffer channels";
let subimage = level_index(subimage)?;
let mip_level = level_index(mip_level)?;
if channels.start >= channels.end {
return Err(Error::InvalidRoi(format!(
"channel range {}..{} is empty or reversed",
channels.start, channels.end
)));
}
let filename = self.name().to_owned();
if filename.is_empty() {
return Err(Error::operation(
OPERATION,
"this buffer is not attached to a file".to_owned(),
));
}
if !sys::imagebuf::imagebuf_init_spec(self.inner_mut(), &filename, subimage, mip_level) {
return Err(Error::operation(OPERATION, self.take_error()));
}
let native = self.native_spec()?;
if native.is_deep() {
return Err(Error::operation(
OPERATION,
"this image is deep, and OpenImageIO reads a deep file whole, \
ignoring the channel subset; use ImageBuf::read"
.to_owned(),
));
}
let count = native.channel_count();
if channels.end > count {
return Err(Error::InvalidRoi(format!(
"channel range {}..{} is outside the native channel count {count}",
channels.start, channels.end
)));
}
let to_i32 = |value: u32| {
i32::try_from(value)
.map_err(|_| Error::InvalidRoi("channel index exceeds i32::MAX".to_owned()))
};
let chbegin = to_i32(channels.start)?;
let chend = to_i32(channels.end)?;
let convert = convert_to.unwrap_or(PixelFormat::Other).to_sys();
let succeeded = sys::imagebuf::imagebuf_read_subset(
self.inner_mut(),
subimage,
mip_level,
chbegin,
chend,
true,
convert,
);
self.check(OPERATION, succeeded)?;
let expected = &native.channel_names()[channels.start as usize..channels.end as usize];
let held = self.spec()?;
if held.channel_names() != expected {
return Err(Error::operation(
OPERATION,
format!(
"the buffer kept previously read channels {:?} instead of {:?}; \
OpenImageIO does not re-read when only the position of a \
same-sized channel range changes; read the full image first, \
or use a fresh buffer",
held.channel_names(),
expected
),
));
}
Ok(())
}
pub fn spec(&self) -> Result<ImageSpec> {
ImageSpec::from_sys(sys::imagebuf::imagebuf_spec(self.inner()))
}
pub fn native_spec(&self) -> Result<ImageSpec> {
ImageSpec::from_sys(sys::imagebuf::imagebuf_nativespec(self.inner()))
}
pub fn storage(&self) -> Storage {
Storage::from_sys(sys::imagebuf::imagebuf_storage(self.inner()))
}
pub fn is_initialized(&self) -> bool {
sys::imagebuf::imagebuf_initialized(self.inner())
}
pub fn name(&self) -> &str {
sys::imagebuf::imagebuf_name(self.inner())
}
pub fn file_format_name(&self) -> &str {
sys::imagebuf::imagebuf_file_format_name(self.inner())
}
pub fn subimage_count(&self) -> i32 {
sys::imagebuf::imagebuf_nsubimages(self.inner())
}
pub fn mip_level_count(&self) -> i32 {
sys::imagebuf::imagebuf_nmiplevels(self.inner())
}
pub fn pixels_valid(&self) -> bool {
sys::imagebuf::imagebuf_pixels_valid(self.inner())
}
pub fn channel_count(&self) -> u32 {
sys::imagebuf::imagebuf_nchannels(self.inner()).max(0) as u32
}
pub fn pixels<T: Pixel>(&self) -> Result<&[T]> {
const OPERATION: &str = "borrow image buffer pixels";
let count = self.borrowable_element_count::<T>(OPERATION)?;
let data = unsafe { sys::imagebuf::imagebuf_localpixels(self.inner()) };
Ok(unsafe { std::slice::from_raw_parts(data.cast::<T>(), count) })
}
pub fn pixels_mut<T: Pixel>(&mut self) -> Result<&mut [T]> {
const OPERATION: &str = "borrow image buffer pixels for writing";
let count = self.borrowable_element_count::<T>(OPERATION)?;
let data = unsafe { sys::imagebuf::imagebuf_localpixels_mut(self.inner_mut()) };
Ok(unsafe { std::slice::from_raw_parts_mut(data.cast::<T>(), count) })
}
fn borrowable_element_count<T: Pixel>(&self, operation: &'static str) -> Result<usize> {
self.require_flat(operation)?;
if !sys::imagebuf::imagebuf_pixels_valid(self.inner()) {
return Err(Error::operation(
operation,
"this buffer has no pixels yet; read it first".to_owned(),
));
}
let spec = self.spec()?;
let actual = spec.format();
if actual != T::FORMAT {
return Err(Error::operation(
operation,
format!(
"the buffer holds {actual:?} and nothing is converted when \
borrowing; ask for {actual:?}, or use get_pixels_into to \
convert to {:?}",
T::FORMAT
),
));
}
if unsafe { sys::imagebuf::imagebuf_localpixels(self.inner()) }.is_null() {
return Err(Error::operation(
operation,
format!(
"these pixels are not the buffer's to lend: its storage is \
{:?}",
self.storage()
),
));
}
if !sys::imagebuf::imagebuf_contiguous(self.inner()) {
return Err(Error::operation(
operation,
"this buffer's rows are not contiguous, so a flat slice would \
not describe it; use get_pixels_into"
.to_owned(),
));
}
spec.element_count()
}
pub fn get_pixels_into<T: Pixel>(&self, roi: Roi, pixels: &mut [T]) -> Result<()> {
self.require_flat("read image buffer pixels")?;
self.require_region_inside(&roi)?;
validate_buffer_len(roi.element_count()?, pixels.len())?;
let sys_roi = roi.to_sys();
let succeeded = unsafe {
sys::imagebuf::imagebuf_get_pixels_span(
self.inner(),
&sys_roi,
pixel::type_desc::<T>(),
pixel::as_bytes_mut(pixels),
)
};
if !succeeded {
return Err(Error::operation(
"read image buffer pixels",
sys::imagebuf::imagebuf_geterror(self.inner(), true),
));
}
if let Err(error) = self.require_filled("read image buffer pixels") {
pixel::as_bytes_mut(pixels).fill(0);
return Err(error);
}
Ok(())
}
pub fn set_pixels<T: Pixel>(&mut self, roi: Roi, pixels: &[T]) -> Result<()> {
self.require_flat("write image buffer pixels")?;
self.require_region_inside(&roi)?;
validate_buffer_len(roi.element_count()?, pixels.len())?;
let sys_roi = roi.to_sys();
let succeeded = unsafe {
sys::imagebuf::imagebuf_set_pixels_span(
self.inner_mut(),
&sys_roi,
pixel::type_desc::<T>(),
pixel::as_bytes(pixels),
)
};
self.check("write image buffer pixels", succeeded)
}
pub fn write(&mut self, image_path: &Path) -> Result<()> {
self.write_as(image_path, None)
}
pub fn write_as(&mut self, image_path: &Path, format: Option<PixelFormat>) -> Result<()> {
let filename = path_to_utf8(image_path)?;
let dtype = format.unwrap_or(PixelFormat::Other).to_sys();
let succeeded = sys::imagebuf::imagebuf_write(self.inner_mut(), filename, dtype, "");
self.check("write image buffer", succeeded)
}
pub fn write_to(&mut self, output: &mut crate::ImageOutput) -> Result<()> {
const OPERATION: &str = "write image buffer to output";
if !self.is_initialized() {
return Err(Error::operation(
OPERATION,
"this buffer has no specification yet; nothing to write".to_owned(),
));
}
let buf_spec = self.spec()?;
let out_spec = output.spec();
if !self.is_deep() {
if !self.name().is_empty() && !self.pixels_valid() {
let (subimage, mip_level) = (self.subimage(), self.mip_level());
self.read_at(subimage, mip_level, None)?;
}
self.require_filled(OPERATION)?;
}
if self.is_deep() && !out_spec.is_deep() {
return Err(Error::operation(
OPERATION,
"the writer was opened for flat pixels but this buffer is deep; \
open it with a spec from ImageSpec::as_deep"
.to_owned(),
));
}
if !self.is_deep() && out_spec.is_deep() {
return Err(Error::operation(
OPERATION,
"the writer was opened for deep samples but this buffer is flat".to_owned(),
));
}
if buf_spec.origin() != out_spec.origin()
|| buf_spec.dimensions() != out_spec.dimensions()
|| buf_spec.channel_count() != out_spec.channel_count()
{
return Err(Error::InvalidImageSpec(format!(
"the buffer's data window (origin {:?}, size {:?}, {} channels) must \
exactly equal the writer's (origin {:?}, size {:?}, {} channels); \
rebuild the buffer or writer from the other's spec",
buf_spec.origin(),
buf_spec.dimensions(),
buf_spec.channel_count(),
out_spec.origin(),
out_spec.dimensions(),
out_spec.channel_count()
)));
}
let top = out_spec.origin()[1];
if output.scanline_cursor() != top {
return Err(Error::operation(
OPERATION,
format!(
"rows {top}..{} of this subimage were already written through \
write_scanlines; write_to needs an untouched subimage",
output.scanline_cursor()
),
));
}
let succeeded = unsafe {
let out_ptr = output.native_mut().get_unchecked_mut() as *mut sys::imageio::ImageOutput;
sys::imagebuf::imagebuf_write_to_imageoutput(self.inner_mut(), out_ptr)
};
self.check(OPERATION, succeeded)?;
output.mark_whole_subimage_written();
Ok(())
}
pub fn make_writable(&mut self) -> Result<()> {
let succeeded = sys::imagebuf::imagebuf_make_writeable(self.inner_mut(), true);
self.check("make image buffer writable", succeeded)
}
pub fn is_deep(&self) -> bool {
sys::imagebuf::imagebuf_deep(self.inner())
}
pub fn deep_sample_count(&self, x: i32, y: i32) -> u32 {
sys::imagebuf::imagebuf_deep_samples(self.inner(), x, y, 0).max(0) as u32
}
pub fn set_deep_sample_count(&mut self, x: i32, y: i32, count: u32) -> Result<()> {
self.require_deep("set deep sample count")?;
self.require_inside("set deep sample count", x, y)?;
let count = i32::try_from(count).map_err(|_| {
Error::InvalidImageSpec("deep sample count exceeds i32::MAX".to_owned())
})?;
let mut error = String::new();
if !sys::imagebuf::imagebuf_set_deep_samples(self.inner_mut(), x, y, 0, count, &mut error) {
return Err(Error::operation("set deep sample count", error));
}
Ok(())
}
pub fn deep_value(&self, x: i32, y: i32, channel: u32, sample: u32) -> Result<f32> {
let (channel, sample) = self.deep_index("read deep value", x, y, channel, sample)?;
Ok(sys::imagebuf::imagebuf_deep_value(
self.inner(),
x,
y,
0,
channel,
sample,
))
}
pub fn deep_value_uint(&self, x: i32, y: i32, channel: u32, sample: u32) -> Result<u32> {
let (channel, sample) = self.deep_index("read deep value", x, y, channel, sample)?;
Ok(sys::imagebuf::imagebuf_deep_value_uint(
self.inner(),
x,
y,
0,
channel,
sample,
))
}
pub fn set_deep_value(
&mut self,
x: i32,
y: i32,
channel: u32,
sample: u32,
value: f32,
) -> Result<()> {
let (channel, sample) = self.deep_index("write deep value", x, y, channel, sample)?;
let mut error = String::new();
if !sys::imagebuf::imagebuf_set_deep_value(
self.inner_mut(),
x,
y,
0,
channel,
sample,
value,
&mut error,
) {
return Err(Error::operation("write deep value", error));
}
Ok(())
}
pub fn set_deep_value_uint(
&mut self,
x: i32,
y: i32,
channel: u32,
sample: u32,
value: u32,
) -> Result<()> {
let (channel, sample) = self.deep_index("write deep value", x, y, channel, sample)?;
let mut error = String::new();
if !sys::imagebuf::imagebuf_set_deep_value_uint(
self.inner_mut(),
x,
y,
0,
channel,
sample,
value,
&mut error,
) {
return Err(Error::operation("write deep value", error));
}
Ok(())
}
fn require_inside(&self, operation: &'static str, x: i32, y: i32) -> Result<()> {
let spec = self.spec()?;
let [origin_x, origin_y, _] = spec.origin();
let [width, height, _] = spec.dimensions();
let inside = x >= origin_x
&& y >= origin_y
&& (i64::from(x) - i64::from(origin_x)) < i64::from(width)
&& (i64::from(y) - i64::from(origin_y)) < i64::from(height);
if inside {
Ok(())
} else {
Err(Error::operation(
operation,
format!(
"{x},{y} is outside the data window {origin_x},{origin_y} \
to {},{}",
origin_x + width as i32,
origin_y + height as i32
),
))
}
}
fn require_filled(&self, operation: &'static str) -> Result<()> {
if self.storage() != Storage::Local || self.pixels_valid() {
return Ok(());
}
let recorded = sys::imagebuf::imagebuf_geterror(self.inner(), true);
let mut message =
"the pixels were never read; the deferred read failed and left the allocation untouched"
.to_owned();
if !recorded.is_empty() {
message.push_str(" (");
message.push_str(recorded.trim_end());
message.push(')');
}
Err(Error::operation(operation, message))
}
fn require_flat(&self, operation: &'static str) -> Result<()> {
if self.is_deep() {
Err(Error::operation(
operation,
"this image is deep; use DeepImage or ImageBuf::deep_value \
to reach its samples"
.to_owned(),
))
} else {
Ok(())
}
}
fn require_region_inside(&self, roi: &Roi) -> Result<()> {
roi.validate_within(&self.spec()?)
}
fn require_deep(&self, operation: &'static str) -> Result<()> {
if self.is_deep() {
Ok(())
} else {
Err(Error::operation(
operation,
"this image is not deep; build it from ImageSpec::as_deep".to_owned(),
))
}
}
fn deep_index(
&self,
operation: &'static str,
x: i32,
y: i32,
channel: u32,
sample: u32,
) -> Result<(i32, i32)> {
self.require_deep(operation)?;
let channels = self.channel_count();
if channel >= channels {
return Err(Error::operation(
operation,
format!("channel {channel} is outside the image's {channels}"),
));
}
let samples = self.deep_sample_count(x, y);
if sample >= samples {
return Err(Error::operation(
operation,
format!("sample {sample} is outside the {samples} at {x},{y}"),
));
}
let to_i32 = |value: u32| {
i32::try_from(value)
.map_err(|_| Error::InvalidImageSpec("deep index exceeds i32::MAX".to_owned()))
};
Ok((to_i32(channel)?, to_i32(sample)?))
}
fn from_inner(
inner: cxx::UniquePtr<sys::imagebuf::ImageBuf>,
operation: &'static str,
) -> Result<Self> {
if inner.is_null() {
return Err(Error::operation(
operation,
"OpenImageIO returned a null image buffer".to_owned(),
));
}
Ok(Self { inner })
}
pub(crate) fn take_error(&self) -> String {
sys::imagebuf::imagebuf_geterror(self.inner(), true)
}
fn check(&mut self, operation: &'static str, succeeded: bool) -> Result<()> {
if succeeded {
Ok(())
} else {
Err(Error::operation(operation, self.take_error()))
}
}
pub fn subimage(&self) -> u32 {
sys::imagebuf::imagebuf_subimage(self.inner()).max(0) as u32
}
pub fn mip_level(&self) -> u32 {
sys::imagebuf::imagebuf_miplevel(self.inner()).max(0) as u32
}
pub fn threads(&self) -> u32 {
sys::imagebuf::imagebuf_threads(self.inner()).max(0) as u32
}
pub fn set_threads(&mut self, count: u32) -> Result<()> {
let count = i32::try_from(count)
.map_err(|_| Error::InvalidImageSpec("thread count exceeds i32::MAX".to_owned()))?;
sys::imagebuf::imagebuf_set_threads(self.inner_mut(), count);
Ok(())
}
pub fn channel_at(&self, x: i32, y: i32, channel: u32, wrap: Wrap) -> Result<f32> {
self.require_flat("read a channel")?;
let channel = i32::try_from(channel)
.map_err(|_| Error::InvalidRoi("channel exceeds i32::MAX".to_owned()))?;
self.require_wrappable(wrap)?;
let value =
sys::imagebuf::imagebuf_getchannel(self.inner(), x, y, 0, channel, wrap.to_sys());
self.require_filled("read a channel")?;
Ok(value)
}
pub fn pixel_at_into(&self, x: i32, y: i32, wrap: Wrap, values: &mut [f32]) -> Result<()> {
self.require_flat("read a pixel")?;
self.require_wrappable(wrap)?;
let count = i32::try_from(values.len())
.map_err(|_| Error::InvalidRoi("channel count exceeds i32::MAX".to_owned()))?;
unsafe {
sys::imagebuf::imagebuf_getpixel(
self.inner(),
x,
y,
0,
values.as_mut_ptr(),
count,
wrap.to_sys(),
);
}
let channels = self.channel_count() as usize;
if values.len() > channels {
values[channels..].fill(0.0);
}
if let Err(error) = self.require_filled("read a pixel") {
values.fill(0.0);
return Err(error);
}
Ok(())
}
pub fn set_pixel_at(&mut self, x: i32, y: i32, values: &[f32]) -> Result<()> {
self.require_flat("write a pixel")?;
self.require_inside("write a pixel", x, y)?;
sys::imagebuf::imagebuf_setpixel(self.inner_mut(), x, y, 0, values);
Ok(())
}
pub fn interpolated_pixel_into(
&self,
x: f32,
y: f32,
wrap: Wrap,
values: &mut [f32],
) -> Result<()> {
self.require_interpolatable(wrap, values)?;
unsafe {
sys::imagebuf::imagebuf_interppixel(
self.inner(),
x,
y,
values.as_mut_ptr(),
wrap.to_sys(),
);
}
self.finish_point_read(values)
}
pub fn interpolated_pixel_bicubic_into(
&self,
x: f32,
y: f32,
wrap: Wrap,
values: &mut [f32],
) -> Result<()> {
self.require_interpolatable(wrap, values)?;
unsafe {
sys::imagebuf::imagebuf_interppixel_bicubic(
self.inner(),
x,
y,
values.as_mut_ptr(),
wrap.to_sys(),
);
}
self.finish_point_read(values)
}
pub fn interpolated_pixel_ndc_into(
&self,
s: f32,
t: f32,
wrap: Wrap,
values: &mut [f32],
) -> Result<()> {
self.require_interpolatable(wrap, values)?;
self.require_positive_display("interpolate in NDC")?;
unsafe {
sys::imagebuf::imagebuf_interppixel_NDC(
self.inner(),
s,
t,
values.as_mut_ptr(),
wrap.to_sys(),
);
}
self.finish_point_read(values)
}
pub fn interpolated_pixel_bicubic_ndc_into(
&self,
s: f32,
t: f32,
wrap: Wrap,
values: &mut [f32],
) -> Result<()> {
self.require_interpolatable(wrap, values)?;
self.require_positive_display("interpolate in NDC")?;
unsafe {
sys::imagebuf::imagebuf_interppixel_bicubic_NDC(
self.inner(),
s,
t,
values.as_mut_ptr(),
wrap.to_sys(),
);
}
self.finish_point_read(values)
}
fn finish_point_read(&self, values: &mut [f32]) -> Result<()> {
if let Err(error) = self.require_filled("interpolate a pixel") {
values.fill(0.0);
return Err(error);
}
Ok(())
}
fn require_interpolatable(&self, wrap: Wrap, values: &[f32]) -> Result<()> {
self.require_flat("interpolate a pixel")?;
self.require_wrappable(wrap)?;
let channels = self.channel_count() as usize;
if values.len() != channels {
return Err(Error::BufferLength {
expected: channels,
actual: values.len(),
});
}
if channels > 1024 {
return Err(Error::operation(
"interpolate a pixel",
format!("interpolation supports at most 1024 channels, this image has {channels}"),
));
}
Ok(())
}
fn require_wrappable(&self, wrap: Wrap) -> Result<()> {
if matches!(wrap, Wrap::Periodic | Wrap::Mirror) {
self.require_positive_display("wrap periodically")?;
}
Ok(())
}
fn require_positive_display(&self, operation: &'static str) -> Result<()> {
let spec = self.spec()?;
let [width, height, depth] = spec.full_dimensions();
if width == 0 || height == 0 || depth == 0 {
return Err(Error::operation(
operation,
"the display window has a zero-sized axis, which this operation divides by"
.to_owned(),
));
}
Ok(())
}
pub fn set_origin(&mut self, origin: [i32; 3]) {
sys::imagebuf::imagebuf_set_origin(self.inner_mut(), origin[0], origin[1], origin[2]);
}
pub fn set_full_window(&mut self, origin: [i32; 3], size: [u32; 3]) -> Result<()> {
let mut end = [0_i32; 3];
for axis in 0..3 {
if size[axis] == 0 {
return Err(Error::InvalidImageSpec(
"the display window needs a positive size on every axis".to_owned(),
));
}
let extent = i32::try_from(size[axis])
.map_err(|_| Error::InvalidImageSpec("display window too large".to_owned()))?;
end[axis] = origin[axis].checked_add(extent).ok_or_else(|| {
Error::InvalidImageSpec("the display window overflows i32".to_owned())
})?;
}
sys::imagebuf::imagebuf_set_full(
self.inner_mut(),
origin[0],
end[0],
origin[1],
end[1],
origin[2],
end[2],
);
Ok(())
}
pub fn set_display_window(&mut self, roi: Roi) {
let sys_roi = roi.to_sys();
sys::imagebuf::imagebuf_set_roi_full(self.inner_mut(), &sys_roi);
}
pub fn set_orientation(&mut self, orientation: u32) -> Result<()> {
if !(1..=8).contains(&orientation) {
return Err(Error::InvalidImageSpec(format!(
"orientation is EXIF's 1..=8, got {orientation}"
)));
}
sys::imagebuf::imagebuf_set_orientation(self.inner_mut(), orientation as i32);
Ok(())
}
pub fn copy_metadata(&mut self, src: &ImageBuf) {
sys::imagebuf::imagebuf_copy_metadata(self.inner_mut(), src.inner());
}
pub fn merge_metadata(
&mut self,
src: &ImageBuf,
override_existing: bool,
pattern: &str,
) -> Result<()> {
let mut error = String::new();
if !sys::imagebuf::imagebuf_merge_metadata(
self.inner_mut(),
src.inner(),
override_existing,
pattern,
&mut error,
) {
return Err(Error::operation("merge metadata", error));
}
Ok(())
}
pub fn has_thumbnail(&self) -> bool {
!sys::imagebuf::imagebuf_get_thumbnail(self.inner()).is_null()
}
pub fn thumbnail(&self) -> Result<Option<ImageBuf>> {
let shared = sys::imagebuf::imagebuf_get_thumbnail(self.inner());
let Some(stored) = shared.as_ref() else {
return Ok(None);
};
let mut error = String::new();
let inner = sys::imagebuf::imagebuf_clone_checked(stored, &mut error);
if inner.is_null() {
return Err(Error::operation("copy thumbnail", error));
}
Ok(Some(Self { inner }))
}
pub fn set_thumbnail(&mut self, thumbnail: &ImageBuf) -> Result<()> {
sys::imagebuf::imagebuf_set_thumbnail(self.inner_mut(), thumbnail.inner());
let stored = sys::imagebuf::imagebuf_get_thumbnail(self.inner());
if let Some(stored) = stored.as_ref() {
if sys::imagebuf::imagebuf_has_error(stored) {
let message = sys::imagebuf::imagebuf_geterror(stored, false);
sys::imagebuf::imagebuf_clear_thumbnail(self.inner_mut());
return Err(Error::operation("set thumbnail", message));
}
}
Ok(())
}
pub fn clear_thumbnail(&mut self) {
sys::imagebuf::imagebuf_clear_thumbnail(self.inner_mut());
}
pub fn try_clone(&self) -> Result<Self> {
let mut error = String::new();
let inner = sys::imagebuf::imagebuf_clone_checked(self.inner(), &mut error);
if inner.is_null() {
return Err(Error::operation("copy image buffer", error));
}
Ok(Self { inner })
}
pub(crate) fn inner(&self) -> &sys::imagebuf::ImageBuf {
self.inner
.as_ref()
.expect("ImageBuf invariant violated: null native pointer")
}
pub(crate) fn inner_mut(&mut self) -> std::pin::Pin<&mut sys::imagebuf::ImageBuf> {
self.inner
.as_mut()
.expect("ImageBuf invariant violated: null native pointer")
}
}
impl Clone for ImageBuf {
fn clone(&self) -> Self {
self.try_clone()
.expect("copying this image buffer failed; ImageBuf::try_clone reports the reason")
}
}
impl std::fmt::Debug for ImageBuf {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter
.debug_struct("ImageBuf")
.field("name", &self.name())
.field("storage", &self.storage())
.field("channels", &self.channel_count())
.finish_non_exhaustive()
}
}
fn level_index(index: u32) -> Result<i32> {
i32::try_from(index)
.map_err(|_| Error::InvalidImageSpec("image level index exceeds i32::MAX".to_owned()))
}
enum_names!("wrap mode", Wrap {
Default => "default",
Black => "black",
Clamp => "clamp",
Periodic => "periodic",
Mirror => "mirror",
});
enum_names!("storage kind", Storage {
Uninitialized => "uninitialized",
Local => "local",
App => "app",
Cache => "cache",
});