use std::borrow::Cow;
use std::fmt;
use crate::dec::idec_dec::{
WebPIDecoder, webp_i_append, webp_i_dec_get_rgb, webp_i_dec_get_yuva, webp_i_decoded_area,
webp_i_new_decoder, webp_i_new_rgb, webp_i_new_yuva, webp_i_update,
};
use crate::dec::webp_dec::{webp_check_crop_dimensions, webp_decode, webp_validate_decoder_config};
use crate::demux::anim_decode::{
WebPAnimDecoder, anim_decoder_new_bytes, webp_anim_decoder_get_info,
webp_anim_decoder_get_next, webp_anim_decoder_has_more_frames, webp_anim_decoder_reset,
};
use crate::demux::demux::{
WebPDemuxer, demux_bytes, webp_demux_get_chunk, webp_demux_get_i, webp_demux_next_chunk,
};
use crate::webp::decode::{
VP8StatusCode, WEBP_CSP_MODE, WebPBitstreamFeatures, WebPDecBuffer, WebPDecBufferPlanes,
WebPDecoderConfig, WebPDecoderOptions, WebPRGBABuffer, WebPYUVABuffer, webp_get_features,
webp_init_decoder_config,
};
use crate::webp::demux::{
WEBP_DEMUX_ABI_VERSION, WebPAnimDecoderOptions, WebPChunkIterator, WebPDemuxState,
WebPFormatFeature, webp_anim_decoder_options_init,
};
use crate::webp::mux_types::WebPFeatureFlags;
use crate::webp::types::{PlaneOffset, PlaneStorage};
const MAX_SCALED_DIMENSION: u32 = 16383;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Plane {
Rows,
Y,
U,
V,
A,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DecodeError {
OutOfMemory,
InvalidParam,
BitstreamError,
UnsupportedFeature,
Suspended,
UserAbort,
NotEnoughData,
FrameFailed,
InvalidCrop {
left: u32,
top: u32,
width: u32,
height: u32,
},
InvalidScale {
width: u32,
height: u32,
},
InvalidStride {
plane: Plane,
stride: usize,
},
BufferTooShort {
plane: Plane,
len: usize,
needed: usize,
},
OutputMismatch {
mode: ColorMode,
},
InvalidParameter {
name: &'static str,
},
}
impl DecodeError {
#[must_use]
pub const fn code(&self) -> Option<VP8StatusCode> {
Some(match self {
Self::OutOfMemory => VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY,
Self::InvalidParam => VP8StatusCode::VP8_STATUS_INVALID_PARAM,
Self::BitstreamError => VP8StatusCode::VP8_STATUS_BITSTREAM_ERROR,
Self::UnsupportedFeature => VP8StatusCode::VP8_STATUS_UNSUPPORTED_FEATURE,
Self::Suspended => VP8StatusCode::VP8_STATUS_SUSPENDED,
Self::UserAbort => VP8StatusCode::VP8_STATUS_USER_ABORT,
Self::NotEnoughData => VP8StatusCode::VP8_STATUS_NOT_ENOUGH_DATA,
Self::FrameFailed
| Self::InvalidCrop { .. }
| Self::InvalidScale { .. }
| Self::InvalidStride { .. }
| Self::BufferTooShort { .. }
| Self::OutputMismatch { .. }
| Self::InvalidParameter { .. } => return None,
})
}
const fn from_status(status: VP8StatusCode) -> Self {
match status {
VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY => Self::OutOfMemory,
VP8StatusCode::VP8_STATUS_INVALID_PARAM => Self::InvalidParam,
VP8StatusCode::VP8_STATUS_UNSUPPORTED_FEATURE => Self::UnsupportedFeature,
VP8StatusCode::VP8_STATUS_SUSPENDED => Self::Suspended,
VP8StatusCode::VP8_STATUS_USER_ABORT => Self::UserAbort,
VP8StatusCode::VP8_STATUS_NOT_ENOUGH_DATA => Self::NotEnoughData,
_ => Self::BitstreamError,
}
}
}
impl fmt::Display for DecodeError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::OutOfMemory => f.write_str("out of memory"),
Self::InvalidParam => f.write_str("invalid parameter"),
Self::BitstreamError => f.write_str("invalid bitstream"),
Self::UnsupportedFeature => f.write_str("unsupported feature"),
Self::Suspended => f.write_str("the decoding has not completed"),
Self::UserAbort => f.write_str("aborted"),
Self::NotEnoughData => f.write_str("not enough data"),
Self::FrameFailed => f.write_str("the animation frame could not be decoded"),
Self::InvalidCrop {
left,
top,
width,
height,
} => write!(f, "invalid crop of {width} by {height} at {left},{top}"),
Self::InvalidScale { width, height } => write!(
f,
"invalid scale to {width} by {height}: each must be 1 to {MAX_SCALED_DIMENSION}"
),
Self::InvalidStride { plane, stride } => {
write!(f, "invalid stride {stride} for the {plane:?} output")
}
Self::BufferTooShort { plane, len, needed } => write!(
f,
"the {plane:?} output holds {len} bytes, its rows need {needed}"
),
Self::OutputMismatch { mode } => {
write!(f, "the output does not match the color mode {mode:?}")
}
Self::InvalidParameter { name } => write!(f, "invalid parameter: {name}"),
}
}
}
impl std::error::Error for DecodeError {}
fn status(result: Result<(), VP8StatusCode>) -> Result<(), DecodeError> {
result.map_err(DecodeError::from_status)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Format {
Lossy,
Lossless,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Features {
pub width: u32,
pub height: u32,
pub has_alpha: bool,
pub has_animation: bool,
pub format: Option<Format>,
}
impl Features {
pub fn parse(data: &[u8]) -> Result<Self, DecodeError> {
let mut raw = WebPBitstreamFeatures::default();
status(webp_get_features(data, &mut raw))?;
Ok(Self {
width: raw.width.cast_unsigned(),
height: raw.height.cast_unsigned(),
has_alpha: raw.has_alpha != 0,
has_animation: raw.has_animation != 0,
format: match raw.format {
1 => Some(Format::Lossy),
2 => Some(Format::Lossless),
_ => None,
},
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorMode {
Rgb,
Rgba,
Bgr,
Bgra,
Argb,
Rgba4444,
Rgb565,
PremultipliedRgba,
PremultipliedBgra,
PremultipliedArgb,
PremultipliedRgba4444,
Yuv,
Yuva,
}
impl ColorMode {
const fn raw(self) -> WEBP_CSP_MODE {
match self {
Self::Rgb => WEBP_CSP_MODE::MODE_RGB,
Self::Rgba => WEBP_CSP_MODE::MODE_RGBA,
Self::Bgr => WEBP_CSP_MODE::MODE_BGR,
Self::Bgra => WEBP_CSP_MODE::MODE_BGRA,
Self::Argb => WEBP_CSP_MODE::MODE_ARGB,
Self::Rgba4444 => WEBP_CSP_MODE::MODE_RGBA_4444,
Self::Rgb565 => WEBP_CSP_MODE::MODE_RGB_565,
Self::PremultipliedRgba => WEBP_CSP_MODE::MODE_rgbA,
Self::PremultipliedBgra => WEBP_CSP_MODE::MODE_bgrA,
Self::PremultipliedArgb => WEBP_CSP_MODE::MODE_Argb,
Self::PremultipliedRgba4444 => WEBP_CSP_MODE::MODE_rgbA_4444,
Self::Yuv => WEBP_CSP_MODE::MODE_YUV,
Self::Yuva => WEBP_CSP_MODE::MODE_YUVA,
}
}
#[must_use]
pub const fn bytes_per_pixel(self) -> Option<usize> {
match self {
Self::Rgb | Self::Bgr => Some(3),
Self::Rgba
| Self::Bgra
| Self::Argb
| Self::PremultipliedRgba
| Self::PremultipliedBgra
| Self::PremultipliedArgb => Some(4),
Self::Rgba4444 | Self::Rgb565 | Self::PremultipliedRgba4444 => Some(2),
Self::Yuv | Self::Yuva => None,
}
}
#[must_use]
pub const fn has_alpha(self) -> bool {
!matches!(self, Self::Rgb | Self::Bgr | Self::Rgb565 | Self::Yuv)
}
#[must_use]
pub const fn is_premultiplied(self) -> bool {
matches!(
self,
Self::PremultipliedRgba
| Self::PremultipliedBgra
| Self::PremultipliedArgb
| Self::PremultipliedRgba4444
)
}
#[must_use]
pub const fn is_yuv(self) -> bool {
matches!(self, Self::Yuv | Self::Yuva)
}
}
fn to_int(value: u32) -> i32 {
i32::try_from(value).unwrap_or(i32::MAX)
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Config {
mode: ColorMode,
options: WebPDecoderOptions,
crop: Option<[u32; 4]>,
scale: Option<[u32; 2]>,
}
impl Default for Config {
fn default() -> Self {
Self::new(ColorMode::Rgb)
}
}
impl Config {
#[must_use]
pub fn new(mode: ColorMode) -> Self {
let mut raw = WebPDecoderConfig::default();
let initialized = webp_init_decoder_config(&mut raw);
debug_assert!(initialized, "the crate's own ABI version matches");
Self {
mode,
options: raw.options,
crop: None,
scale: None,
}
}
#[must_use]
pub fn crop(mut self, left: u32, top: u32, width: u32, height: u32) -> Self {
self.crop = Some([left, top, width, height]);
self.options.use_cropping = 1;
self.options.crop_left = to_int(left);
self.options.crop_top = to_int(top);
self.options.crop_width = to_int(width);
self.options.crop_height = to_int(height);
self
}
#[must_use]
pub fn scale(mut self, width: u32, height: u32) -> Self {
self.scale = Some([width, height]);
self.options.use_scaling = 1;
self.options.scaled_width = to_int(width);
self.options.scaled_height = to_int(height);
self
}
#[must_use]
pub fn flip(mut self, on: bool) -> Self {
self.options.flip = i32::from(on);
self
}
#[must_use]
pub fn bypass_filtering(mut self, on: bool) -> Self {
self.options.bypass_filtering = i32::from(on);
self
}
#[must_use]
pub fn fancy_upsampling(mut self, on: bool) -> Self {
self.options.no_fancy_upsampling = i32::from(!on);
self
}
#[must_use]
pub fn multithreaded(mut self, on: bool) -> Self {
self.options.use_threads = i32::from(on);
self
}
#[must_use]
pub fn dithering(mut self, strength: u8) -> Self {
self.options.dithering_strength = i32::from(strength);
self
}
#[must_use]
pub fn alpha_dithering(mut self, strength: u8) -> Self {
self.options.alpha_dithering_strength = i32::from(strength);
self
}
#[must_use]
pub const fn mode(&self) -> ColorMode {
self.mode
}
pub fn validate(&self) -> Result<(), DecodeError> {
if let Some([left, top, width, height]) = self.crop {
let too_large = [left, top, width, height]
.iter()
.any(|&value| i32::try_from(value).is_err());
if width == 0 || height == 0 || left % 2 != 0 || top % 2 != 0 || too_large {
return Err(DecodeError::InvalidCrop {
left,
top,
width,
height,
});
}
}
if let Some([width, height]) = self.scale {
let range = 1..=MAX_SCALED_DIMENSION;
if !range.contains(&width) || !range.contains(&height) {
return Err(DecodeError::InvalidScale { width, height });
}
}
if self.options.dithering_strength > 100 {
return Err(DecodeError::InvalidParameter { name: "dithering" });
}
if self.options.alpha_dithering_strength > 100 {
return Err(DecodeError::InvalidParameter {
name: "alpha_dithering",
});
}
if webp_validate_decoder_config(&self.raw_config()) {
Ok(())
} else {
Err(DecodeError::InvalidParam)
}
}
pub fn output_size(&self, features: &Features) -> Result<(u32, u32), DecodeError> {
self.validate()?;
let (mut width, mut height) = (features.width, features.height);
if let Some([left, top, crop_width, crop_height]) = self.crop {
if !webp_check_crop_dimensions(
to_int(features.width),
to_int(features.height),
to_int(left),
to_int(top),
to_int(crop_width),
to_int(crop_height),
) {
return Err(DecodeError::InvalidCrop {
left,
top,
width: crop_width,
height: crop_height,
});
}
(width, height) = (crop_width, crop_height);
}
if let Some([scaled_width, scaled_height]) = self.scale {
(width, height) = (scaled_width, scaled_height);
}
Ok((width, height))
}
#[must_use]
pub const fn as_raw(&self) -> &WebPDecoderOptions {
&self.options
}
fn raw_config<'a>(&self) -> WebPDecoderConfig<'a> {
let mut raw = WebPDecoderConfig::default();
let initialized = webp_init_decoder_config(&mut raw);
debug_assert!(initialized, "the crate's own ABI version matches");
raw.output.colorspace = self.mode.raw();
raw.options = self.options;
raw
}
}
pub struct YuvaPlanes<'a> {
pub y: &'a mut [u8],
pub y_stride: usize,
pub u: &'a mut [u8],
pub v: &'a mut [u8],
pub uv_stride: usize,
pub a: Option<&'a mut [u8]>,
pub a_stride: usize,
}
impl fmt::Debug for YuvaPlanes<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("YuvaPlanes")
.field("y_len", &self.y.len())
.field("y_stride", &self.y_stride)
.field("u_len", &self.u.len())
.field("v_len", &self.v.len())
.field("uv_stride", &self.uv_stride)
.field("a_len", &self.a.as_ref().map(|a| a.len()))
.field("a_stride", &self.a_stride)
.finish()
}
}
pub enum Output<'a> {
Rows {
data: &'a mut [u8],
stride: usize,
},
Planes(YuvaPlanes<'a>),
}
impl fmt::Debug for Output<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Rows { data, stride } => f
.debug_struct("Rows")
.field("data_len", &data.len())
.field("stride", stride)
.finish(),
Self::Planes(planes) => f.debug_tuple("Planes").field(planes).finish(),
}
}
}
fn check_plane(
plane: Plane,
len: usize,
stride: usize,
row: usize,
rows: usize,
) -> Result<(), DecodeError> {
if stride < row || i32::try_from(stride).is_err() {
return Err(DecodeError::InvalidStride { plane, stride });
}
let needed = rows
.saturating_sub(1)
.checked_mul(stride)
.and_then(|extent| extent.checked_add(row))
.ok_or(DecodeError::InvalidStride { plane, stride })?;
if len < needed {
return Err(DecodeError::BufferTooShort { plane, len, needed });
}
Ok(())
}
fn check_shape(mode: ColorMode, output: &Output<'_>) -> Result<(), DecodeError> {
let matches = match output {
Output::Rows { .. } => !mode.is_yuv(),
Output::Planes(planes) => mode.is_yuv() && planes.a.is_some() == (mode == ColorMode::Yuva),
};
if matches {
Ok(())
} else {
Err(DecodeError::OutputMismatch { mode })
}
}
fn check_output(
mode: ColorMode,
width: u32,
height: u32,
output: &Output<'_>,
) -> Result<(), DecodeError> {
check_shape(mode, output)?;
let width = usize::try_from(width).unwrap_or(usize::MAX);
let height = usize::try_from(height).unwrap_or(usize::MAX);
match output {
Output::Rows { data, stride } => {
let bpp = mode.bytes_per_pixel().unwrap_or(1);
let row = width.checked_mul(bpp).ok_or(DecodeError::InvalidStride {
plane: Plane::Rows,
stride: *stride,
})?;
check_plane(Plane::Rows, data.len(), *stride, row, height)
}
Output::Planes(planes) => {
let (uv_width, uv_height) = (width.div_ceil(2), height.div_ceil(2));
check_plane(Plane::Y, planes.y.len(), planes.y_stride, width, height)?;
check_plane(
Plane::U,
planes.u.len(),
planes.uv_stride,
uv_width,
uv_height,
)?;
check_plane(
Plane::V,
planes.v.len(),
planes.uv_stride,
uv_width,
uv_height,
)?;
if let Some(a) = &planes.a {
check_plane(Plane::A, a.len(), planes.a_stride, width, height)?;
}
Ok(())
}
}
}
fn check_output_shape(mode: ColorMode, output: &Output<'_>) -> Result<(), DecodeError> {
check_shape(mode, output)?;
let check = |plane, len: usize, stride: usize| {
if stride == 0 || i32::try_from(stride).is_err() {
Err(DecodeError::InvalidStride { plane, stride })
} else if len == 0 {
Err(DecodeError::BufferTooShort {
plane,
len,
needed: 1,
})
} else {
Ok(())
}
};
match output {
Output::Rows { data, stride } => check(Plane::Rows, data.len(), *stride),
Output::Planes(planes) => {
check(Plane::Y, planes.y.len(), planes.y_stride)?;
check(Plane::U, planes.u.len(), planes.uv_stride)?;
check(Plane::V, planes.v.len(), planes.uv_stride)?;
if let Some(a) = &planes.a {
check(Plane::A, a.len(), planes.a_stride)?;
}
Ok(())
}
}
}
fn stride_int(stride: usize) -> i32 {
i32::try_from(stride).unwrap_or(i32::MAX)
}
fn attach<'a>(buffer: &mut WebPDecBuffer<'a>, output: Output<'a>) {
let plane = |region| PlaneOffset { region, offset: 0 };
match output {
Output::Rows { data, stride } => {
buffer.u = WebPDecBufferPlanes::RGBA(WebPRGBABuffer {
rgba: plane(0),
stride: stride_int(stride),
size: data.len(),
});
buffer.storage = PlaneStorage::External(vec![data]);
}
Output::Planes(planes) => {
let YuvaPlanes {
y,
y_stride,
u,
v,
uv_stride,
a,
a_stride,
} = planes;
buffer.u = WebPDecBufferPlanes::YUVA(WebPYUVABuffer {
y: plane(0),
u: plane(1),
v: plane(2),
a: a.is_some().then(|| plane(3)),
y_stride: stride_int(y_stride),
u_stride: stride_int(uv_stride),
v_stride: stride_int(uv_stride),
a_stride: a.as_ref().map_or(0, |_| stride_int(a_stride)),
y_size: y.len(),
u_size: u.len(),
v_size: v.len(),
a_size: a.as_ref().map_or(0, |a| a.len()),
});
let mut slices = vec![y, u, v];
slices.extend(a);
buffer.storage = PlaneStorage::External(slices);
}
}
buffer.slow_memory = false;
}
#[derive(Clone, Copy)]
pub struct Rows<'s> {
data: &'s [u8],
first: usize,
stride: isize,
row_len: usize,
count: u32,
}
impl fmt::Debug for Rows<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Rows")
.field("region_len", &self.data.len())
.field("first", &self.first)
.field("stride", &self.stride)
.field("row_len", &self.row_len)
.field("count", &self.count)
.finish()
}
}
impl<'s> Rows<'s> {
fn new(data: &'s [u8], first: usize, stride: i32, row_len: usize, count: i32) -> Self {
Self {
data,
first,
stride: isize::try_from(stride).unwrap_or(0),
row_len,
count: u32::try_from(count).unwrap_or(0),
}
}
#[must_use]
pub const fn len(&self) -> u32 {
self.count
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.count == 0
}
#[must_use]
pub fn row(&self, index: u32) -> Option<&'s [u8]> {
if index >= self.count {
return None;
}
let offset = isize::try_from(index).ok()?.checked_mul(self.stride)?;
let start = self.first.checked_add_signed(offset)?;
self.data.get(start..start.checked_add(self.row_len)?)
}
pub fn iter(&self) -> impl Iterator<Item = &'s [u8]> + 's {
let rows = *self;
(0..rows.count).filter_map(move |index| rows.row(index))
}
#[must_use]
pub const fn row_len(&self) -> usize {
self.row_len
}
#[must_use]
pub const fn stride(&self) -> isize {
self.stride
}
}
#[derive(Clone, Copy, Debug)]
pub struct YuvaRows<'s> {
pub y: Rows<'s>,
pub u: Rows<'s>,
pub v: Rows<'s>,
pub a: Option<Rows<'s>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct PlaneLayout {
offset: usize,
stride: i32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Layout {
Packed(PlaneLayout),
Planar {
y: PlaneLayout,
u: PlaneLayout,
v: PlaneLayout,
a: Option<PlaneLayout>,
},
}
#[derive(Clone, PartialEq, Eq)]
pub struct Image {
mode: ColorMode,
width: u32,
height: u32,
samples: Vec<u8>,
layout: Layout,
}
impl fmt::Debug for Image {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Image")
.field("mode", &self.mode)
.field("width", &self.width)
.field("height", &self.height)
.field("samples_len", &self.samples.len())
.field("layout", &self.layout)
.finish()
}
}
impl Image {
fn from_buffer(mode: ColorMode, buffer: WebPDecBuffer<'_>) -> Result<Self, DecodeError> {
let width = u32::try_from(buffer.width).map_err(|_| DecodeError::InvalidParam)?;
let height = u32::try_from(buffer.height).map_err(|_| DecodeError::InvalidParam)?;
let PlaneStorage::Internal(samples) = buffer.storage else {
return Err(DecodeError::OutputMismatch { mode });
};
if samples.is_empty() {
return Err(DecodeError::Suspended);
}
let plane = |offset: PlaneOffset, stride: i32| PlaneLayout {
offset: offset.offset,
stride,
};
let layout = match buffer.u {
WebPDecBufferPlanes::RGBA(rgba) => Layout::Packed(plane(rgba.rgba, rgba.stride)),
WebPDecBufferPlanes::YUVA(yuva) => Layout::Planar {
y: plane(yuva.y, yuva.y_stride),
u: plane(yuva.u, yuva.u_stride),
v: plane(yuva.v, yuva.v_stride),
a: yuva.a.map(|a| plane(a, yuva.a_stride)),
},
};
Ok(Self {
mode,
width,
height,
samples,
layout,
})
}
#[must_use]
pub const fn mode(&self) -> ColorMode {
self.mode
}
#[must_use]
pub const fn width(&self) -> u32 {
self.width
}
#[must_use]
pub const fn height(&self) -> u32 {
self.height
}
#[must_use]
pub fn rows(&self) -> Option<Rows<'_>> {
let Layout::Packed(plane) = self.layout else {
return None;
};
let row_len = usize::try_from(self.width)
.ok()?
.checked_mul(self.mode.bytes_per_pixel()?)?;
Some(Rows::new(
&self.samples,
plane.offset,
plane.stride,
row_len,
i32::try_from(self.height).ok()?,
))
}
#[must_use]
pub fn planes(&self) -> Option<YuvaRows<'_>> {
let Layout::Planar { y, u, v, a } = self.layout else {
return None;
};
let width = usize::try_from(self.width).ok()?;
let height = i32::try_from(self.height).ok()?;
let (uv_width, uv_height) = (width.div_ceil(2), (height + 1) / 2);
let rows = |plane: PlaneLayout, row_len, count| {
Rows::new(&self.samples, plane.offset, plane.stride, row_len, count)
};
Some(YuvaRows {
y: rows(y, width, height),
u: rows(u, uv_width, uv_height),
v: rows(v, uv_width, uv_height),
a: a.map(|a| rows(a, width, height)),
})
}
#[must_use]
pub fn samples(&self) -> &[u8] {
&self.samples
}
#[must_use]
pub fn into_samples(self) -> Vec<u8> {
self.samples
}
}
fn prepare(data: &[u8], config: &Config) -> Result<(u32, u32), DecodeError> {
config.validate()?;
let features = match Features::parse(data) {
Ok(features) => features,
Err(DecodeError::NotEnoughData) => return Err(DecodeError::BitstreamError),
Err(error) => return Err(error),
};
if features.has_animation {
return Err(DecodeError::UnsupportedFeature);
}
config.output_size(&features)
}
pub fn decode(data: &[u8], config: &Config) -> Result<Image, DecodeError> {
prepare(data, config)?;
let mut raw = config.raw_config();
status(webp_decode(data, &mut raw))?;
Image::from_buffer(config.mode, raw.output)
}
pub fn decode_into(
data: &[u8],
config: &Config,
output: Output<'_>,
) -> Result<(u32, u32), DecodeError> {
let (width, height) = prepare(data, config)?;
check_output(config.mode, width, height, &output)?;
let mut raw = config.raw_config();
attach(&mut raw.output, output);
status(webp_decode(data, &mut raw))?;
Ok((width, height))
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Status {
NeedsMoreData,
Complete,
}
pub struct IncrementalDecoder<'a> {
idec: WebPIDecoder<'a, 'a>,
mode: ColorMode,
library_memory: bool,
complete: bool,
started: bool,
}
impl fmt::Debug for IncrementalDecoder<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("IncrementalDecoder")
.field("mode", &self.mode)
.field("library_memory", &self.library_memory)
.field("complete", &self.complete)
.field("decoded_rows", &self.decoded_rows())
.finish()
}
}
impl<'a> IncrementalDecoder<'a> {
pub fn new(config: &'a Config) -> Result<Self, DecodeError> {
config.validate()?;
let mut idec = webp_i_new_decoder(None).ok_or(DecodeError::OutOfMemory)?;
idec.own_output_mut().colorspace = config.mode.raw();
idec.set_options(&config.options);
Ok(Self {
idec,
mode: config.mode,
library_memory: true,
complete: false,
started: false,
})
}
pub fn with_output(config: &'a Config, output: Output<'a>) -> Result<Self, DecodeError> {
config.validate()?;
check_output_shape(config.mode, &output)?;
let idec = match output {
Output::Rows { data, stride } => {
webp_i_new_rgb(config.mode.raw(), Some(data), stride_int(stride))
}
Output::Planes(planes) => {
let a_stride = planes.a.as_ref().map_or(0, |_| stride_int(planes.a_stride));
webp_i_new_yuva(
Some(planes.y),
stride_int(planes.y_stride),
Some(planes.u),
stride_int(planes.uv_stride),
Some(planes.v),
stride_int(planes.uv_stride),
planes.a,
a_stride,
)
}
};
let mut idec = idec.ok_or(DecodeError::InvalidParam)?;
idec.set_options(&config.options);
Ok(Self {
idec,
mode: config.mode,
library_memory: false,
complete: false,
started: false,
})
}
fn step(&mut self, result: Result<(), VP8StatusCode>) -> Result<Status, DecodeError> {
match result {
Ok(()) => {
self.complete = true;
Ok(Status::Complete)
}
Err(VP8StatusCode::VP8_STATUS_SUSPENDED) => Ok(Status::NeedsMoreData),
Err(code) => Err(DecodeError::from_status(code)),
}
}
pub fn append(&mut self, data: &[u8]) -> Result<Status, DecodeError> {
if data.is_empty() && !self.started {
return Ok(Status::NeedsMoreData);
}
let result = webp_i_append(&mut self.idec, data);
if result != Err(VP8StatusCode::VP8_STATUS_OUT_OF_MEMORY) {
self.started = true;
}
self.step(result)
}
pub fn update(&mut self, data: &[u8]) -> Result<Status, DecodeError> {
self.started = true;
let result = webp_i_update(&mut self.idec, data);
self.step(result)
}
#[must_use]
pub fn output_size(&self) -> Option<(u32, u32)> {
let buffer = webp_i_decoded_area(&self.idec, None, None, None, None)?;
let width = u32::try_from(buffer.width)
.ok()
.filter(|&width| width > 0)?;
let height = u32::try_from(buffer.height)
.ok()
.filter(|&height| height > 0)?;
Some((width, height))
}
#[must_use]
pub fn decoded_rows(&self) -> u32 {
let mut rows = 0;
let _ = webp_i_decoded_area(&self.idec, None, None, None, Some(&mut rows));
u32::try_from(rows).unwrap_or(0)
}
#[must_use]
pub fn rows(&self) -> Option<Rows<'_>> {
let (mut last_y, mut width, mut stride) = (0, 0, 0);
let (region, first) = webp_i_dec_get_rgb(
&self.idec,
Some(&mut last_y),
Some(&mut width),
None,
Some(&mut stride),
)?;
let row_len = usize::try_from(width)
.ok()?
.checked_mul(self.mode.bytes_per_pixel()?)?;
Some(Rows::new(region, first, stride, row_len, last_y))
}
#[must_use]
pub fn planes(&self) -> Option<YuvaRows<'_>> {
let (mut last_y, mut width, mut stride, mut uv_stride, mut a_stride) = (0, 0, 0, 0, 0);
let (mut u, mut v, mut a) = (None, None, None);
let (y_region, y_first) = webp_i_dec_get_yuva(
&self.idec,
Some(&mut last_y),
Some(&mut u),
Some(&mut v),
Some(&mut a),
Some(&mut width),
None,
Some(&mut stride),
Some(&mut uv_stride),
Some(&mut a_stride),
)?;
let width = usize::try_from(width).ok()?;
let (uv_width, uv_rows) = (width.div_ceil(2), (last_y + 1) / 2);
let ((u_region, u_first), (v_region, v_first)) = (u?, v?);
Some(YuvaRows {
y: Rows::new(y_region, y_first, stride, width, last_y),
u: Rows::new(u_region, u_first, uv_stride, uv_width, uv_rows),
v: Rows::new(v_region, v_first, uv_stride, uv_width, uv_rows),
a: a.map(|(region, first)| Rows::new(region, first, a_stride, width, last_y)),
})
}
pub fn into_image(mut self) -> Result<Image, DecodeError> {
if !self.library_memory {
return Err(DecodeError::OutputMismatch { mode: self.mode });
}
if !self.complete {
return Err(DecodeError::Suspended);
}
let buffer = std::mem::take(self.idec.own_output_mut());
Image::from_buffer(self.mode, buffer)
}
}
fn payload<'s>(bytes: &Cow<'s, [u8]>) -> Option<&'s [u8]> {
match bytes {
Cow::Borrowed(bytes) => Some(bytes),
Cow::Owned(_) => None,
}
}
fn demux_error(data: &[u8]) -> DecodeError {
if let Err(error) = Features::parse(data) {
return error;
}
match demux_bytes(data, true, WEBP_DEMUX_ABI_VERSION) {
(Some(_), _) | (None, WebPDemuxState::WEBP_DEMUX_PARSING_HEADER) => {
DecodeError::NotEnoughData
}
(None, _) => DecodeError::BitstreamError,
}
}
pub struct Container<'d> {
demux: WebPDemuxer<'d>,
state: WebPDemuxState,
}
impl fmt::Debug for Container<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Container")
.field("complete", &self.is_complete())
.field("canvas_width", &self.canvas_width())
.field("canvas_height", &self.canvas_height())
.field("frame_count", &self.frame_count())
.finish_non_exhaustive()
}
}
impl<'d> Container<'d> {
pub fn new(data: &'d [u8]) -> Result<Self, DecodeError> {
match demux_bytes(data, false, WEBP_DEMUX_ABI_VERSION) {
(Some(demux), state) => Ok(Self { demux, state }),
(None, _) => Err(demux_error(data)),
}
}
pub fn partial(data: &'d [u8]) -> Result<Self, DecodeError> {
match demux_bytes(data, true, WEBP_DEMUX_ABI_VERSION) {
(Some(demux), state) => Ok(Self { demux, state }),
(None, _) => Err(demux_error(data)),
}
}
#[must_use]
pub fn is_complete(&self) -> bool {
self.state == WebPDemuxState::WEBP_DEMUX_DONE
}
fn get(&self, feature: WebPFormatFeature) -> u32 {
webp_demux_get_i(&self.demux, feature)
}
#[must_use]
pub fn canvas_width(&self) -> u32 {
self.get(WebPFormatFeature::WEBP_FF_CANVAS_WIDTH)
}
#[must_use]
pub fn canvas_height(&self) -> u32 {
self.get(WebPFormatFeature::WEBP_FF_CANVAS_HEIGHT)
}
#[must_use]
pub fn has_alpha(&self) -> bool {
self.get(WebPFormatFeature::WEBP_FF_FORMAT_FLAGS) & WebPFeatureFlags::ALPHA_FLAG.0 != 0
}
#[must_use]
pub fn has_animation(&self) -> bool {
self.get(WebPFormatFeature::WEBP_FF_FORMAT_FLAGS) & WebPFeatureFlags::ANIMATION_FLAG.0 != 0
}
#[must_use]
pub fn loop_count(&self) -> u32 {
self.get(WebPFormatFeature::WEBP_FF_LOOP_COUNT)
}
#[must_use]
pub fn background_color(&self) -> u32 {
self.get(WebPFormatFeature::WEBP_FF_BACKGROUND_COLOR)
}
#[must_use]
pub fn frame_count(&self) -> u32 {
self.get(WebPFormatFeature::WEBP_FF_FRAME_COUNT)
}
fn first_chunk(&self, fourcc: [u8; 4]) -> Option<&[u8]> {
let iter = webp_demux_get_chunk(&self.demux, fourcc, 1)?;
payload(&iter.chunk.bytes)
}
#[must_use]
pub fn icc_profile(&self) -> Option<&[u8]> {
self.first_chunk(*b"ICCP")
}
#[must_use]
pub fn exif(&self) -> Option<&[u8]> {
self.first_chunk(*b"EXIF")
}
#[must_use]
pub fn xmp(&self) -> Option<&[u8]> {
self.first_chunk(*b"XMP ")
}
#[must_use]
pub fn chunks(&self, fourcc: [u8; 4]) -> Chunks<'_> {
Chunks {
iter: webp_demux_get_chunk(&self.demux, fourcc, 1),
started: false,
}
}
}
pub struct Chunks<'s> {
iter: Option<WebPChunkIterator<'s>>,
started: bool,
}
impl fmt::Debug for Chunks<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Chunks")
.field("chunk_num", &self.iter.as_ref().map(|iter| iter.chunk_num))
.field(
"num_chunks",
&self.iter.as_ref().map(|iter| iter.num_chunks),
)
.finish()
}
}
impl<'s> Iterator for Chunks<'s> {
type Item = &'s [u8];
fn next(&mut self) -> Option<&'s [u8]> {
let iter = self.iter.as_mut()?;
if self.started && !webp_demux_next_chunk(iter) {
self.iter = None;
return None;
}
self.started = true;
payload(&iter.chunk.bytes)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum AnimationMode {
#[default]
Rgba,
Bgra,
PremultipliedRgba,
PremultipliedBgra,
}
impl AnimationMode {
const fn raw(self) -> WEBP_CSP_MODE {
match self {
Self::Rgba => WEBP_CSP_MODE::MODE_RGBA,
Self::Bgra => WEBP_CSP_MODE::MODE_BGRA,
Self::PremultipliedRgba => WEBP_CSP_MODE::MODE_rgbA,
Self::PremultipliedBgra => WEBP_CSP_MODE::MODE_bgrA,
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct AnimationOptions {
pub mode: AnimationMode,
pub multithreaded: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct AnimationInfo {
pub canvas_width: u32,
pub canvas_height: u32,
pub loop_count: u32,
pub background_color: u32,
pub frame_count: u32,
}
#[derive(Clone, Copy)]
pub struct Frame<'s> {
pub canvas: &'s [u8],
pub stride: usize,
pub timestamp_ms: i32,
}
impl fmt::Debug for Frame<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Frame")
.field("canvas_len", &self.canvas.len())
.field("stride", &self.stride)
.field("timestamp_ms", &self.timestamp_ms)
.finish()
}
}
pub struct AnimationDecoder<'d> {
dec: WebPAnimDecoder<'d>,
}
impl fmt::Debug for AnimationDecoder<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("AnimationDecoder")
.field("info", &self.info())
.field("has_more_frames", &self.has_more_frames())
.finish_non_exhaustive()
}
}
impl<'d> AnimationDecoder<'d> {
pub fn new(data: &'d [u8], options: AnimationOptions) -> Result<Self, DecodeError> {
let mut raw = WebPAnimDecoderOptions::default();
let initialized = webp_anim_decoder_options_init(&mut raw);
debug_assert!(initialized, "the crate's own ABI version matches");
raw.color_mode = options.mode.raw();
raw.use_threads = i32::from(options.multithreaded);
if let Some(dec) = anim_decoder_new_bytes(data, Some(&raw), WEBP_DEMUX_ABI_VERSION) {
return Ok(Self { dec });
}
Features::parse(data)?;
if demux_bytes(data, false, WEBP_DEMUX_ABI_VERSION).0.is_none() {
return Err(demux_error(data));
}
Err(DecodeError::OutOfMemory)
}
#[must_use]
pub fn info(&self) -> AnimationInfo {
let info = webp_anim_decoder_get_info(&self.dec);
AnimationInfo {
canvas_width: info.canvas_width,
canvas_height: info.canvas_height,
loop_count: info.loop_count,
background_color: info.bgcolor,
frame_count: info.frame_count,
}
}
#[must_use]
pub fn has_more_frames(&self) -> bool {
webp_anim_decoder_has_more_frames(&self.dec)
}
pub fn next_frame(&mut self) -> Result<Option<Frame<'_>>, DecodeError> {
if !self.has_more_frames() {
return Ok(None);
}
let stride = usize::try_from(self.info().canvas_width)
.unwrap_or(usize::MAX)
.saturating_mul(4);
match webp_anim_decoder_get_next(&mut self.dec) {
Some((canvas, timestamp_ms)) => Ok(Some(Frame {
canvas,
stride,
timestamp_ms,
})),
None => Err(DecodeError::FrameFailed),
}
}
pub fn reset(&mut self) {
webp_anim_decoder_reset(&mut self.dec);
}
}