use std::fmt;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use unityrs_core::limits::{Charge, ChargeError, Meter, MeteredVec, heap_cost};
use crate::contain::Payload;
use crate::format::{Format, Library, Mode};
use crate::{astc, atc, bcn, crunch, etc, pvrtc, raw};
pub const MAX_PIXELS: u64 = 1 << 28;
pub const MAX_CROP_PIXELS: u64 = 2 * 89_478_485;
const INT_MAX: u32 = 0x7FFF_FFFF;
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum DecodeError {
#[error(transparent)]
Hdr(#[from] crate::HdrError),
#[error(transparent)]
Platform(#[from] crate::PlatformError),
#[error("unsupported texture layout: {format:?} at width {width}")]
Unsupported {
format: Format,
width: i32,
},
#[error(transparent)]
Crunch(crunch::CrunchError),
#[error("the texture has no image data")]
NoImageData,
#[error("the texture's size {width}x{height} has a negative side")]
NegativeSize {
width: i32,
height: i32,
},
#[error("the texture's {pixels} pixels pass the decoders' bound of {max}")]
TooLarge {
pixels: u64,
max: u64,
},
#[error("Pillow's raw decoder refuses a row of {width} pixels, past {max} (MemoryError)")]
PillowMemoryError {
width: u32,
max: u32,
},
#[error("not enough image data: {needed} bytes needed, {got} given")]
NotEnoughData {
needed: u64,
got: u64,
},
#[error(
"Image size ({pixels} pixels) exceeds limit of {max} pixels, could be decompression bomb DOS attack."
)]
DecompressionBomb {
pixels: u64,
max: u64,
},
#[error("PVRTC block counts must be powers of two")]
PvrtcBlockCount,
#[error(transparent)]
Charge(#[from] ChargeError),
#[error("the decoder panicked: {payload}")]
Panicked {
payload: Payload,
},
}
const _: () = crate::send_sync::<DecodeError>();
impl From<crunch::CrunchError> for DecodeError {
fn from(error: crunch::CrunchError) -> Self {
match error {
crunch::CrunchError::Charge(charge) => Self::Charge(charge),
other => Self::Crunch(other),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Plan {
pub mode: Mode,
pub width: u32,
pub height: u32,
pub input_bytes: u64,
pub output_bytes: u64,
pub scratch: u64,
}
const _: () = crate::send_sync::<Plan>();
impl Plan {
#[must_use]
pub const fn charge(&self) -> u64 {
heap_cost(self.output_bytes)
}
#[must_use]
pub const fn peak_charge(&self) -> u64 {
self.charge().saturating_add(self.scratch)
}
}
pub fn plan(format: Format, data_len: usize, width: i32, height: i32) -> Result<Plan, DecodeError> {
if width == 0 || height == 0 {
return Ok(Plan {
mode: Mode::Rgba,
width: 0,
height: 0,
input_bytes: 0,
output_bytes: 0,
scratch: 0,
});
}
if format == Format::ArgbFloat || (format == Format::Yuy2 && width % 2 != 0) {
return Err(DecodeError::Unsupported { format, width });
}
if data_len == 0 {
return Err(DecodeError::NoImageData);
}
let (Ok(w), Ok(h)) = (u32::try_from(width), u32::try_from(height)) else {
return Err(DecodeError::NegativeSize { width, height });
};
let (w64, h64) = (u64::from(w), u64::from(h));
let block = format.block_bytes();
let (padded_w, padded_h) = match format.block_size() {
Some((bw, bh)) => {
let (bw, bh) = (u64::from(bw), u64::from(bh));
(w64.div_ceil(bw) * bw, h64.div_ceil(bh) * bh)
}
None => (w64, h64),
};
let pixels = padded_w * padded_h;
if pixels > MAX_PIXELS {
return Err(DecodeError::TooLarge {
pixels,
max: MAX_PIXELS,
});
}
if let Some(is2) = format.pvrtc_2bpp() {
let bx = padded_w / if is2 { 8 } else { 4 };
let by = padded_h / 4;
if !bx.is_power_of_two() || !by.is_power_of_two() {
return Err(DecodeError::PvrtcBlockCount);
}
}
let mode = format.mode();
let library = format.library();
let len = u64::try_from(data_len).unwrap_or(u64::MAX);
let unpacked_bytes = block.map_or(0, |b| padded_w / 4 * (padded_h / 4) * b);
let (input_bytes, seen) = if format.is_crunched() {
(75, len)
} else {
match (block, format.block_size(), library) {
(Some(b), Some((bw, bh)), _) => {
let blocks = padded_w / u64::from(bw) * (padded_h / u64::from(bh));
let seen = if library == Library::PillowBcn {
bcn_length(data_len)
} else {
len
};
(blocks * b, seen)
}
(Some(b), None, _) => (w64.div_ceil(4) * h64.div_ceil(4) * b, len),
_ => (pixels * raw_pixel_bytes(format), len),
}
};
let short = seen < input_bytes;
let not_enough = || DecodeError::NotEnoughData {
needed: input_bytes,
got: len,
};
if library == Library::Astcenc && short {
return Err(not_enough());
}
if let Some(bits) = format.raw_bits() {
let row = u32::try_from(padded_w).unwrap_or(u32::MAX);
let max = INT_MAX / bits - 7;
if row > max {
return Err(DecodeError::PillowMemoryError { width: row, max });
}
}
if short {
return Err(not_enough());
}
let shown = w64 * h64;
if (padded_w, padded_h) != (w64, h64) && shown > MAX_CROP_PIXELS {
return Err(DecodeError::DecompressionBomb {
pixels: shown,
max: MAX_CROP_PIXELS,
});
}
Ok(Plan {
mode,
width: w,
height: h,
input_bytes,
output_bytes: shown * mode.bytes_per_pixel(),
scratch: scratch_charge(format, unpacked_bytes, w64),
})
}
pub struct Image {
mode: Mode,
width: u32,
height: u32,
pixels: Vec<u8>,
charge: Charge,
}
const _: () = crate::send_sync::<Image>();
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("bytes", &self.pixels.len())
.field("charge", &self.charge)
.finish()
}
}
impl Image {
pub(crate) fn from_parts(
mode: Mode,
width: u32,
height: u32,
pixels: Vec<u8>,
charge: Charge,
) -> Self {
Self {
mode,
width,
height,
pixels,
charge,
}
}
#[must_use]
pub fn mode(&self) -> Mode {
self.mode
}
#[must_use]
pub fn width(&self) -> u32 {
self.width
}
#[must_use]
pub fn height(&self) -> u32 {
self.height
}
#[must_use]
pub fn pixels(&self) -> &[u8] {
&self.pixels
}
#[must_use]
pub fn charge(&self) -> &Charge {
&self.charge
}
pub fn into_parts(self) -> (Vec<u8>, Charge) {
(self.pixels, self.charge)
}
}
pub fn decode(
format: Format,
data: &[u8],
width: i32,
height: i32,
meter: &Arc<Meter>,
) -> Result<Image, DecodeError> {
decode_with(format, data, width, height, meter, fill, false)
}
pub fn decode_bc6h_signed(
data: &[u8],
width: i32,
height: i32,
meter: &Arc<Meter>,
) -> Result<Image, DecodeError> {
decode_with(Format::Bc6h, data, width, height, meter, fill, true)
}
type Fill = fn(Format, &[u8], usize, usize, &mut [u8], Option<&mut astc::Tables>);
fn decode_with(
format: Format,
data: &[u8],
width: i32,
height: i32,
meter: &Arc<Meter>,
fill: Fill,
signed_bc6h: bool,
) -> Result<Image, DecodeError> {
let plan = plan(format, data.len(), width, height)?;
meter.count_decode(plan.output_bytes)?;
let (Ok(out_len), Ok(w), Ok(h)) = (
usize::try_from(plan.output_bytes),
usize::try_from(plan.width),
usize::try_from(plan.height),
) else {
return Err(DecodeError::TooLarge {
pixels: u64::from(plan.width) * u64::from(plan.height),
max: MAX_PIXELS,
});
};
if out_len > 0 && format.is_crunched() {
if format.is_unity_crunched() {
crunch::unity::validate(data, format, (w, h))?;
} else {
crunch::validate(data, format == Format::Dxt5Crunched, (w, h))?;
}
}
let (pixels, charge) = MeteredVec::<u8>::with_capacity(meter, out_len)?.into_parts();
let mut image = Image {
mode: plan.mode,
width: plan.width,
height: plan.height,
pixels,
charge,
};
image.pixels.resize(out_len, 0);
if out_len > 0 {
if format.is_crunched() {
crate::contain(AssertUnwindSafe(|| {
let blocks = if format.is_unity_crunched() {
crunch::unity::unpack(data, format, (w, h), 0, meter)?
} else {
crunch::unpack(data, format == Format::Dxt5Crunched, (w, h), 0, meter)?
};
fill(format, blocks.as_slice(), w, h, &mut image.pixels, None);
Ok(())
}))?;
return Ok(image);
}
let mut tables = match astc_footprint(format) {
Some(fp) => Some(astc::Tables::new(fp, meter)?),
None => None,
};
let out = &mut image.pixels;
crate::contain(AssertUnwindSafe(|| {
if format.is_astc_hdr() {
let tables = tables.as_mut().ok_or(crate::HdrError::InvalidBlock)?;
astc::hdr::decode_image(tables, data, w, h, out)?;
return Ok(());
}
if format == Format::Bc6h {
if signed_bc6h {
crate::bc6h::decode_signed(data, w, h, out)?;
} else {
crate::bc6h::decode(data, w, h, out)?;
}
return Ok(());
}
fill(format, data, w, h, out, tables.as_mut());
Ok(())
}))?;
}
Ok(image)
}
fn fill(
format: Format,
data: &[u8],
w: usize,
h: usize,
out: &mut [u8],
tables: Option<&mut astc::Tables>,
) {
if let Some(tables) = tables {
astc::decode_image(tables, data, (w, h), true, astc::ERROR, out);
return;
}
if crate::tierb::layout(format).is_some() {
crate::tierb::decode(format, data, w, h, out);
return;
}
match format {
Format::Alpha8 => raw::decode(raw::Kind::A, data, w, h, out),
Format::Argb4444 => raw::decode(raw::Kind::Rgba4BArgb, data, w, h, out),
Format::Rgb24 => raw::decode(raw::Kind::Rgb, data, w, h, out),
Format::Rgba32 => raw::decode(raw::Kind::Rgba, data, w, h, out),
Format::Argb32 => raw::decode(raw::Kind::Argb, data, w, h, out),
Format::Rgb565 => raw::decode(raw::Kind::Bgr16, data, w, h, out),
Format::Bgr24 => raw::decode(raw::Kind::Bgr, data, w, h, out),
Format::Rgba4444 => raw::decode(raw::Kind::Rgba4BRgba, data, w, h, out),
Format::Bgra32 => raw::decode(raw::Kind::Bgra, data, w, h, out),
Format::R8 => raw::decode(raw::Kind::R, data, w, h, out),
Format::Dxt1 | Format::Dxt1Crunched | Format::UnityDxt1Crunched => {
bcn::decode(bcn::Kind::Bc1, data, w, h, out);
}
Format::Dxt3 => bcn::decode(bcn::Kind::Bc2, data, w, h, out),
Format::Dxt5 | Format::Dxt5Crunched | Format::UnityDxt5Crunched => {
bcn::decode(bcn::Kind::Bc3, data, w, h, out);
}
Format::Bc4 => bcn::decode(bcn::Kind::Bc4, data, w, h, out),
Format::Bc5 => bcn::decode(bcn::Kind::Bc5, data, w, h, out),
Format::Bc7 => bcn::decode(bcn::Kind::Bc7, data, w, h, out),
Format::PvrtcRgb2 | Format::PvrtcRgba2 => pvrtc::decode(data, w, h, true, out),
Format::PvrtcRgb4 | Format::PvrtcRgba4 => pvrtc::decode(data, w, h, false, out),
Format::AtcRgb4 => atc::decode(data, w, h, false, out),
Format::AtcRgba8 => atc::decode(data, w, h, true, out),
Format::EtcRgb4 | Format::EtcRgb4Crunched => etc::decode(etc::Kind::Etc1, data, w, h, out),
Format::EacR => etc::decode(etc::Kind::EacR, data, w, h, out),
Format::EacRSigned => etc::decode(etc::Kind::EacRSigned, data, w, h, out),
Format::EacRg => etc::decode(etc::Kind::EacRg, data, w, h, out),
Format::EacRgSigned => etc::decode(etc::Kind::EacRgSigned, data, w, h, out),
Format::Etc2Rgb => etc::decode(etc::Kind::Etc2, data, w, h, out),
Format::Etc2Rgba1 => etc::decode(etc::Kind::Etc2A1, data, w, h, out),
Format::Etc2Rgba8 | Format::Etc2Rgba8Crunched => {
etc::decode(etc::Kind::Etc2A8, data, w, h, out);
}
Format::Bc6h
| Format::AstcHdr4x4
| Format::AstcHdr5x5
| Format::AstcHdr6x6
| Format::AstcHdr8x8
| Format::AstcHdr10x10
| Format::AstcHdr12x12
| Format::R16
| Format::RHalf
| Format::RgHalf
| Format::RgbaHalf
| Format::RFloat
| Format::RgFloat
| Format::RgbaFloat
| Format::Yuy2
| Format::Rgb9e5Float
| Format::RgbFloat
| Format::Rg16
| Format::Rg32
| Format::Rgb48
| Format::Rgba64
| Format::R8Signed
| Format::Rg16Signed
| Format::Rgb24Signed
| Format::Rgba32Signed
| Format::R16Signed
| Format::Rg32Signed
| Format::Rgb48Signed
| Format::Rgba64Signed
| Format::ArgbFloat
| Format::AstcRgb4x4
| Format::AstcRgb5x5
| Format::AstcRgb6x6
| Format::AstcRgb8x8
| Format::AstcRgb10x10
| Format::AstcRgb12x12
| Format::AstcRgba4x4
| Format::AstcRgba5x5
| Format::AstcRgba6x6
| Format::AstcRgba8x8
| Format::AstcRgba10x10
| Format::AstcRgba12x12 => {}
}
}
mod length;
pub use length::bcn_length;
use length::{astc_footprint, raw_pixel_bytes, scratch_charge};
#[cfg(test)]
mod tests;