use crate::dec::webp_dec::webp_check_crop_dimensions;
use crate::utils::rescaler_utils::webp_rescaler_get_scaled_dimensions;
use crate::utils::utils::{webp_copy_plane, webp_safe_malloc};
use crate::webp::decode::{
VP8StatusCode, WEBP_CSP_MODE, WEBP_DECODER_ABI_VERSION, WebPBitstreamFeatures, WebPDecBuffer,
WebPDecBufferPlanes, WebPDecoderOptions, WebPRGBABuffer, WebPYUVABuffer, webp_is_alpha_mode,
webp_is_premultiplied_mode, webp_is_rgb_mode,
};
use crate::webp::types::{PlaneOffset, PlaneStorage, webp_abi_is_incompatible};
const MODE_BPP: [u8; WEBP_CSP_MODE::MODE_LAST.0 as usize] = [
3, 4, 3, 4, 4, 2, 2, 4, 4, 4, 2, 1, 1,
];
fn mode_bpp(mode: WEBP_CSP_MODE) -> u8 {
MODE_BPP[mode.0 as usize]
}
#[must_use]
pub fn is_valid_colorspace(webp_csp_mode: i32) -> bool {
webp_csp_mode >= WEBP_CSP_MODE::MODE_RGB.0.cast_signed()
&& webp_csp_mode < WEBP_CSP_MODE::MODE_LAST.0.cast_signed()
}
fn colorspace_int(mode: WEBP_CSP_MODE) -> i32 {
mode.0.cast_signed()
}
fn min_buffer_size(width: u64, height: i32, stride: i32) -> u64 {
u64::from(stride.cast_unsigned())
.wrapping_mul(i64::from(height - 1).cast_unsigned())
.wrapping_add(width)
}
fn to_u64(value: i32) -> u64 {
i64::from(value).cast_unsigned()
}
#[must_use]
pub fn is_null_plane(storage: &PlaneStorage<'_, u8>, plane: PlaneOffset) -> bool {
match storage {
PlaneStorage::Internal(memory) => memory.is_empty(),
PlaneStorage::External(_) | PlaneStorage::Shared(_) => {
storage.region(plane.region).is_none()
}
}
}
fn check_dec_buffer(buffer: &WebPDecBuffer<'_>) -> Result<(), VP8StatusCode> {
let mut ok = true;
let mode = buffer.colorspace;
let width = buffer.width;
let height = buffer.height;
if !is_valid_colorspace(colorspace_int(mode)) {
ok = false;
} else if !webp_is_rgb_mode(mode) {
if let WebPDecBufferPlanes::YUVA(buf) = &buffer.u {
let uv_width = (width + 1) / 2;
let uv_height = (height + 1) / 2;
let y_stride = buf.y_stride.abs();
let u_stride = buf.u_stride.abs();
let v_stride = buf.v_stride.abs();
let a_stride = buf.a_stride.abs();
let y_size = min_buffer_size(to_u64(width), height, y_stride);
let u_size = min_buffer_size(to_u64(uv_width), uv_height, u_stride);
let v_size = min_buffer_size(to_u64(uv_width), uv_height, v_stride);
let a_size = min_buffer_size(to_u64(width), height, a_stride);
ok &= y_size <= buf.y_size as u64;
ok &= u_size <= buf.u_size as u64;
ok &= v_size <= buf.v_size as u64;
ok &= y_stride >= width;
ok &= u_stride >= uv_width;
ok &= v_stride >= uv_width;
ok &= !is_null_plane(&buffer.storage, buf.y);
ok &= !is_null_plane(&buffer.storage, buf.u);
ok &= !is_null_plane(&buffer.storage, buf.v);
if mode == WEBP_CSP_MODE::MODE_YUVA {
ok &= a_stride >= width;
ok &= a_size <= buf.a_size as u64;
ok &= buf.a.is_some_and(|a| !is_null_plane(&buffer.storage, a));
}
} else {
ok = false; }
} else {
if let WebPDecBufferPlanes::RGBA(buf) = &buffer.u {
let bpp = mode_bpp(mode);
let stride = buf.stride.abs();
let size = min_buffer_size(to_u64(width).wrapping_mul(u64::from(bpp)), height, stride);
ok &= size <= buf.size as u64;
ok &= stride >= width * i32::from(bpp);
ok &= !is_null_plane(&buffer.storage, buf.rgba);
} else {
ok = false; }
}
if ok {
Ok(())
} else {
Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM)
}
}
#[expect(
clippy::cast_possible_truncation,
reason = "C converts the uint64_t sizes to size_t, which holds them after WebPSafeMalloc"
)]
fn allocate_buffer(buffer: &mut WebPDecBuffer<'_>) -> Result<(), VP8StatusCode> {
let w = buffer.width;
let h = buffer.height;
let mode = buffer.colorspace;
if w <= 0 || h <= 0 || !is_valid_colorspace(colorspace_int(mode)) {
return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
}
if matches!(&buffer.storage, PlaneStorage::Internal(memory) if memory.is_empty()) {
let mut uv_stride = 0;
let mut a_stride = 0;
let mut uv_size: u64 = 0;
let mut a_size: u64 = 0;
let bpp = mode_bpp(mode);
if to_u64(w) * u64::from(bpp) >= (1u64 << 31) {
return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
}
let stride = w * i32::from(bpp);
let size = to_u64(stride) * to_u64(h);
if !webp_is_rgb_mode(mode) {
uv_stride = (w + 1) / 2;
uv_size = to_u64(uv_stride) * to_u64((h + 1) / 2);
if mode == WEBP_CSP_MODE::MODE_YUVA {
a_stride = w;
a_size = to_u64(a_stride) * to_u64(h);
}
}
let total_size = size + 2 * uv_size + a_size;
let Some(mut output) = webp_safe_malloc::<u8>(total_size, 1) else {
return Err(VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY);
};
output.resize(total_size as usize, 0);
buffer.storage = PlaneStorage::Internal(output);
let plane = |offset: u64| PlaneOffset {
region: 0,
offset: offset as usize,
};
if webp_is_rgb_mode(mode) {
buffer.u = WebPDecBufferPlanes::RGBA(WebPRGBABuffer {
rgba: plane(0),
stride,
size: size as usize,
});
} else {
let a = match &buffer.u {
WebPDecBufferPlanes::YUVA(buf) => buf.a,
WebPDecBufferPlanes::RGBA(_) => None,
};
buffer.u = WebPDecBufferPlanes::YUVA(WebPYUVABuffer {
y: plane(0),
y_stride: stride,
y_size: size as usize,
u: plane(size),
u_stride: uv_stride,
u_size: uv_size as usize,
v: plane(size + uv_size),
v_stride: uv_stride,
v_size: uv_size as usize,
a: if mode == WEBP_CSP_MODE::MODE_YUVA {
Some(plane(size + 2 * uv_size))
} else {
a
},
a_size: a_size as usize,
a_stride,
});
}
}
check_dec_buffer(buffer)
}
fn move_plane(plane: &mut PlaneOffset, delta: i64) {
plane.offset = plane
.offset
.checked_add_signed(isize::try_from(delta).expect("the plane offset fits"))
.expect("the flipped plane starts inside its region");
}
pub fn webp_flip_buffer(buffer: &mut WebPDecBuffer<'_>) -> Result<(), VP8StatusCode> {
let height = i64::from(buffer.height);
if webp_is_rgb_mode(buffer.colorspace) {
if let WebPDecBufferPlanes::RGBA(buf) = &mut buffer.u {
move_plane(&mut buf.rgba, (height - 1) * i64::from(buf.stride));
buf.stride = -buf.stride;
}
} else if let WebPDecBufferPlanes::YUVA(buf) = &mut buffer.u {
let h = height;
move_plane(&mut buf.y, (h - 1) * i64::from(buf.y_stride));
buf.y_stride = -buf.y_stride;
move_plane(&mut buf.u, ((h - 1) >> 1) * i64::from(buf.u_stride));
buf.u_stride = -buf.u_stride;
move_plane(&mut buf.v, ((h - 1) >> 1) * i64::from(buf.v_stride));
buf.v_stride = -buf.v_stride;
if let Some(a) = &mut buf.a {
move_plane(a, (h - 1) * i64::from(buf.a_stride));
buf.a_stride = -buf.a_stride;
}
}
Ok(())
}
pub fn webp_allocate_dec_buffer(
width: i32,
height: i32,
options: Option<&WebPDecoderOptions>,
buffer: &mut WebPDecBuffer<'_>,
) -> Result<(), VP8StatusCode> {
let mut width = width;
let mut height = height;
if width <= 0 || height <= 0 {
return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
}
if let Some(options) = options {
if options.use_cropping != 0 {
let cw = options.crop_width;
let ch = options.crop_height;
let x = options.crop_left & !1;
let y = options.crop_top & !1;
if !webp_check_crop_dimensions(width, height, x, y, cw, ch) {
return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM); }
width = cw;
height = ch;
}
if options.use_scaling != 0 {
let mut scaled_width = options.scaled_width;
let mut scaled_height = options.scaled_height;
if !webp_rescaler_get_scaled_dimensions(
width,
height,
&mut scaled_width,
&mut scaled_height,
) {
return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
}
width = scaled_width;
height = scaled_height;
}
}
buffer.width = width;
buffer.height = height;
allocate_buffer(buffer)?;
if options.is_some_and(|options| options.flip != 0) {
webp_flip_buffer(buffer)?;
}
Ok(())
}
#[must_use]
pub fn webp_init_dec_buffer_internal(buffer: &mut WebPDecBuffer<'_>, version: i32) -> bool {
if webp_abi_is_incompatible(version, WEBP_DECODER_ABI_VERSION) {
return false; }
*buffer = WebPDecBuffer::default();
true
}
pub fn webp_free_dec_buffer(buffer: &mut WebPDecBuffer<'_>) {
if let PlaneStorage::Internal(memory) = &mut buffer.storage {
*memory = Vec::new();
}
}
pub fn webp_copy_dec_buffer<'s>(src: &'s WebPDecBuffer<'_>, dst: &mut WebPDecBuffer<'s>) {
dst.colorspace = src.colorspace;
dst.width = src.width;
dst.height = src.height;
dst.slow_memory = false;
dst.u = src.u;
dst.pad = src.pad;
dst.storage = PlaneStorage::Shared(match &src.storage {
PlaneStorage::Internal(memory) => vec![memory.as_slice()],
PlaneStorage::External(slices) => slices.iter().map(|slice| &**slice).collect(),
PlaneStorage::Shared(slices) => slices.clone(),
});
}
pub fn webp_grab_dec_buffer<'a>(src: &mut WebPDecBuffer<'a>, dst: &mut WebPDecBuffer<'a>) {
dst.colorspace = src.colorspace;
dst.width = src.width;
dst.height = src.height;
dst.slow_memory = src.slow_memory;
dst.u = src.u;
dst.pad = src.pad;
let empty = match &src.storage {
PlaneStorage::Internal(_) => PlaneStorage::Internal(Vec::new()),
PlaneStorage::External(_) => PlaneStorage::External(Vec::new()),
PlaneStorage::Shared(_) => PlaneStorage::Shared(Vec::new()),
};
dst.storage = std::mem::replace(&mut src.storage, empty);
}
fn region<'b>(storage: &'b PlaneStorage<'_, u8>, plane: PlaneOffset) -> &'b [u8] {
storage
.region(plane.region)
.expect("the plane's region exists")
}
fn region_mut<'b>(storage: &'b mut PlaneStorage<'_, u8>, plane: PlaneOffset) -> &'b mut [u8] {
storage
.region_mut(plane.region)
.expect("the plane's region exists")
}
#[expect(
clippy::too_many_arguments,
reason = "the arguments of WebPCopyPlane with the two storages"
)]
fn copy_plane(
src: &PlaneStorage<'_, u8>,
src_plane: PlaneOffset,
src_stride: i32,
dst: &mut PlaneStorage<'_, u8>,
dst_plane: PlaneOffset,
dst_stride: i32,
width: i32,
height: i32,
) {
webp_copy_plane(
region(src, src_plane),
src_plane.offset,
src_stride,
region_mut(dst, dst_plane),
dst_plane.offset,
dst_stride,
width,
height,
);
}
pub fn webp_copy_dec_buffer_pixels(
src_buf: &WebPDecBuffer<'_>,
dst_buf: &mut WebPDecBuffer<'_>,
) -> Result<(), VP8StatusCode> {
debug_assert_eq!(src_buf.colorspace, dst_buf.colorspace);
dst_buf.width = src_buf.width;
dst_buf.height = src_buf.height;
if check_dec_buffer(dst_buf).is_err() {
return Err(VP8StatusCode::VP8_STATUS_INVALID_PARAM);
}
match (&src_buf.u, &dst_buf.u) {
(WebPDecBufferPlanes::RGBA(src), WebPDecBufferPlanes::RGBA(dst))
if webp_is_rgb_mode(src_buf.colorspace) =>
{
let (src, dst) = (*src, *dst);
copy_plane(
&src_buf.storage,
src.rgba,
src.stride,
&mut dst_buf.storage,
dst.rgba,
dst.stride,
src_buf.width * i32::from(mode_bpp(src_buf.colorspace)),
src_buf.height,
);
}
(WebPDecBufferPlanes::YUVA(src), WebPDecBufferPlanes::YUVA(dst))
if !webp_is_rgb_mode(src_buf.colorspace) =>
{
let (src, dst) = (*src, *dst);
copy_plane(
&src_buf.storage,
src.y,
src.y_stride,
&mut dst_buf.storage,
dst.y,
dst.y_stride,
src_buf.width,
src_buf.height,
);
copy_plane(
&src_buf.storage,
src.u,
src.u_stride,
&mut dst_buf.storage,
dst.u,
dst.u_stride,
(src_buf.width + 1) / 2,
(src_buf.height + 1) / 2,
);
copy_plane(
&src_buf.storage,
src.v,
src.v_stride,
&mut dst_buf.storage,
dst.v,
dst.v_stride,
(src_buf.width + 1) / 2,
(src_buf.height + 1) / 2,
);
if webp_is_alpha_mode(src_buf.colorspace) {
copy_plane(
&src_buf.storage,
src.a.expect("a YUVA buffer has an alpha plane"),
src.a_stride,
&mut dst_buf.storage,
dst.a.expect("the checked YUVA buffer has an alpha plane"),
dst.a_stride,
src_buf.width,
src_buf.height,
);
}
}
_ => panic!("the source buffer's member matches its colorspace"),
}
Ok(())
}
#[must_use]
pub fn webp_avoid_slow_memory(
output: &WebPDecBuffer<'_>,
features: Option<&WebPBitstreamFeatures>,
) -> bool {
output.slow_memory
&& webp_is_premultiplied_mode(output.colorspace)
&& features.is_some_and(|features| features.has_alpha != 0)
}