feat(imaging): add pure-Rust Skia backend (#112)
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
//! Optional Skia imaging adapter corresponding to `LibreMetaverse.Imaging.Skia`.
|
||||
//!
|
||||
//! Enable `skia` for bounded `BMP`, `GIF`, `ICO`, `JPEG`, `PNG`, `WBMP`, and
|
||||
//! `WebP` decoding.
|
||||
//! Enable `skia` or the fully native-Rust `rust-skia` alternative for bounded
|
||||
//! `BMP`, `GIF`, `ICO`, `JPEG`, `PNG`, `WBMP`, and `WebP` decoding.
|
||||
//! The default build remains inert. See the crate README for native cache,
|
||||
//! source-build, licensing, and cross-platform prerequisite details.
|
||||
|
||||
@@ -15,6 +15,7 @@ mod skia_codec;
|
||||
pub use generated::*;
|
||||
pub use libremetaverse_imaging as imaging;
|
||||
pub use libremetaverse_types::Error;
|
||||
pub use skia_codec::RustSkiaTextureCodec;
|
||||
|
||||
impl libremetaverse_imaging::ITextureCodec for SkiaTextureCodec {
|
||||
fn decode(
|
||||
@@ -24,3 +25,12 @@ impl libremetaverse_imaging::ITextureCodec for SkiaTextureCodec {
|
||||
Self::decode(self, stream)
|
||||
}
|
||||
}
|
||||
|
||||
impl libremetaverse_imaging::ITextureCodec for RustSkiaTextureCodec {
|
||||
fn decode(
|
||||
&self,
|
||||
stream: Box<dyn libremetaverse_types::compat::ReadWrite + Send>,
|
||||
) -> Result<libremetaverse_imaging::ManagedImage, Error> {
|
||||
Self::decode(self, stream)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,17 +2,24 @@
|
||||
|
||||
use crate::Error;
|
||||
use crate::backend::{SKAlphaType, SKBitmap, SKColorType};
|
||||
#[cfg(feature = "skia")]
|
||||
#[cfg(any(feature = "rust-skia", feature = "skia"))]
|
||||
use libremetaverse_imaging::{DEFAULT_MAX_ENCODED_BYTES, DEFAULT_MAX_PIXELS};
|
||||
use libremetaverse_imaging::{ManagedImage, ManagedImageImageChannels};
|
||||
use libremetaverse_types::compat::ReadWrite;
|
||||
#[cfg(feature = "skia")]
|
||||
#[cfg(any(feature = "rust-skia", feature = "skia"))]
|
||||
use std::io::Read;
|
||||
|
||||
/// Optional Skia-backed decoder and format-neutral bitmap converter.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct SkiaTextureCodec;
|
||||
|
||||
/// Pure-Rust alternative to [`SkiaTextureCodec`] with the same image boundary.
|
||||
///
|
||||
/// Enable the `rust-skia` feature to decode the common Skia codec formats
|
||||
/// without a native library, build script, system package lookup, or download.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct RustSkiaTextureCodec;
|
||||
|
||||
impl SkiaTextureCodec {
|
||||
/// Creates the stateless codec adapter.
|
||||
///
|
||||
@@ -33,17 +40,7 @@ impl SkiaTextureCodec {
|
||||
pub fn decode(&self, mut stream: Box<dyn ReadWrite + Send>) -> Result<ManagedImage, Error> {
|
||||
#[cfg(feature = "skia")]
|
||||
{
|
||||
let mut encoded = Vec::new();
|
||||
Read::by_ref(&mut stream)
|
||||
.take((DEFAULT_MAX_ENCODED_BYTES + 1) as u64)
|
||||
.read_to_end(&mut encoded)
|
||||
.map_err(|_| Error::InvalidOperation)?;
|
||||
if encoded.is_empty() {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
if encoded.len() > DEFAULT_MAX_ENCODED_BYTES {
|
||||
return Err(Error::Argument);
|
||||
}
|
||||
let encoded = read_bounded(&mut stream)?;
|
||||
decode_with_skia(&encoded)
|
||||
}
|
||||
#[cfg(not(feature = "skia"))]
|
||||
@@ -65,6 +62,55 @@ impl SkiaTextureCodec {
|
||||
}
|
||||
}
|
||||
|
||||
impl RustSkiaTextureCodec {
|
||||
/// Creates the stateless pure-Rust codec adapter.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This fixed compatibility constructor cannot fail.
|
||||
pub const fn new() -> Result<Self, Error> {
|
||||
Ok(Self)
|
||||
}
|
||||
|
||||
/// Decodes a bounded stream with Rust-only BMP, GIF, ICO, JPEG, PNG,
|
||||
/// WBMP, and WebP codecs.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// With `rust-skia`, returns [`Error::Argument`] for an input or decoded
|
||||
/// canvas above the documented limits and [`Error::InvalidOperation`] for
|
||||
/// malformed or unsupported images. Without the feature it returns
|
||||
/// [`Error::InvalidOperation`].
|
||||
pub fn decode(&self, mut stream: Box<dyn ReadWrite + Send>) -> Result<ManagedImage, Error> {
|
||||
#[cfg(feature = "rust-skia")]
|
||||
{
|
||||
let encoded = read_bounded(&mut stream)?;
|
||||
decode_with_rust_skia(&encoded)
|
||||
}
|
||||
#[cfg(not(feature = "rust-skia"))]
|
||||
{
|
||||
let _ = &mut stream;
|
||||
Err(Error::InvalidOperation)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "rust-skia", feature = "skia"))]
|
||||
fn read_bounded(stream: &mut (dyn ReadWrite + Send)) -> Result<Vec<u8>, Error> {
|
||||
let mut encoded = Vec::new();
|
||||
stream
|
||||
.take((DEFAULT_MAX_ENCODED_BYTES + 1) as u64)
|
||||
.read_to_end(&mut encoded)
|
||||
.map_err(|_| Error::InvalidOperation)?;
|
||||
if encoded.is_empty() {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
if encoded.len() > DEFAULT_MAX_ENCODED_BYTES {
|
||||
return Err(Error::Argument);
|
||||
}
|
||||
Ok(encoded)
|
||||
}
|
||||
|
||||
// Keeping the format branches together makes comparison with the pinned C#
|
||||
// color switch auditable and prevents subtly different indexing paths.
|
||||
#[allow(clippy::too_many_lines)]
|
||||
@@ -238,6 +284,404 @@ fn normalize_10bit_alpha(
|
||||
(normalize(red), normalize(green), normalize(blue))
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn decode_with_rust_skia(encoded: &[u8]) -> Result<ManagedImage, Error> {
|
||||
use skia_rs_codec::{ImageDecoder, ImageFormat};
|
||||
|
||||
let format = if wbmp_dimensions(encoded).is_ok() {
|
||||
ImageFormat::Wbmp
|
||||
} else {
|
||||
ImageFormat::from_magic(encoded)
|
||||
};
|
||||
if format == ImageFormat::WebP {
|
||||
return decode_webp_with_rust(encoded);
|
||||
}
|
||||
if !matches!(
|
||||
format,
|
||||
ImageFormat::Bmp
|
||||
| ImageFormat::Gif
|
||||
| ImageFormat::Ico
|
||||
| ImageFormat::Jpeg
|
||||
| ImageFormat::Png
|
||||
| ImageFormat::Wbmp
|
||||
) {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
|
||||
let (width, height) = match format {
|
||||
ImageFormat::Gif => gif_dimensions(encoded)?,
|
||||
ImageFormat::Ico => ico_dimensions(encoded)?,
|
||||
ImageFormat::Wbmp => wbmp_dimensions(encoded)?,
|
||||
_ => skia_rs_codec::get_image_dimensions(encoded).map_err(|_| Error::InvalidOperation)?,
|
||||
};
|
||||
validate_dimensions(width, height)?;
|
||||
|
||||
let decoded = if format == ImageFormat::Wbmp {
|
||||
skia_rs_codec::WbmpDecoder::new().decode_bytes(encoded)
|
||||
} else {
|
||||
skia_rs_codec::decode_image(encoded)
|
||||
}
|
||||
.map_err(|_| Error::InvalidOperation)?;
|
||||
validate_dimensions(decoded.width(), decoded.height())?;
|
||||
if decoded.width() != width || decoded.height() != height {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
let width_usize = usize::try_from(width).map_err(|_| Error::Argument)?;
|
||||
if decoded.row_bytes() != width_usize.checked_mul(4).ok_or(Error::Argument)? {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
let source_pixels = decoded.peek_pixels().ok_or(Error::InvalidOperation)?;
|
||||
let grayscale = match format {
|
||||
ImageFormat::Jpeg => jpeg_is_grayscale(encoded)?,
|
||||
ImageFormat::Png => encoded.get(25) == Some(&0),
|
||||
ImageFormat::Wbmp => true,
|
||||
_ => false,
|
||||
};
|
||||
let (row_bytes, color_type, alpha_type, pixels) = if grayscale {
|
||||
let pixel_count = width_usize
|
||||
.checked_mul(usize::try_from(height).map_err(|_| Error::Argument)?)
|
||||
.ok_or(Error::Argument)?;
|
||||
let mut gray = Vec::new();
|
||||
gray.try_reserve_exact(pixel_count)
|
||||
.map_err(|_| Error::InvalidOperation)?;
|
||||
gray.extend(source_pixels.chunks_exact(4).map(|rgba| rgba[0]));
|
||||
if gray.len() != pixel_count {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
(width_usize, SKColorType::Gray8, SKAlphaType::Opaque, gray)
|
||||
} else {
|
||||
let mut rgba = Vec::new();
|
||||
rgba.try_reserve_exact(source_pixels.len())
|
||||
.map_err(|_| Error::InvalidOperation)?;
|
||||
rgba.extend_from_slice(source_pixels);
|
||||
(
|
||||
decoded.row_bytes(),
|
||||
SKColorType::Rgba8888,
|
||||
if decoded.is_opaque() {
|
||||
SKAlphaType::Opaque
|
||||
} else {
|
||||
SKAlphaType::Unpremul
|
||||
},
|
||||
rgba,
|
||||
)
|
||||
};
|
||||
let bitmap = SKBitmap::new(width, height, row_bytes, color_type, alpha_type, pixels)?;
|
||||
bitmap_to_managed(&bitmap)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn jpeg_is_grayscale(encoded: &[u8]) -> Result<bool, Error> {
|
||||
let mut offset = 2;
|
||||
while offset + 1 < encoded.len() {
|
||||
if encoded[offset] != 0xff {
|
||||
offset += 1;
|
||||
continue;
|
||||
}
|
||||
let mut marker_offset = offset + 1;
|
||||
while encoded.get(marker_offset) == Some(&0xff) {
|
||||
marker_offset += 1;
|
||||
}
|
||||
let marker = *encoded.get(marker_offset).ok_or(Error::InvalidOperation)?;
|
||||
if marker == 0 || marker == 1 || (0xd0..=0xd9).contains(&marker) {
|
||||
offset = marker_offset + 1;
|
||||
continue;
|
||||
}
|
||||
let length_bytes = encoded
|
||||
.get(marker_offset + 1..marker_offset + 3)
|
||||
.ok_or(Error::InvalidOperation)?;
|
||||
let length = usize::from(u16::from_be_bytes(
|
||||
length_bytes
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidOperation)?,
|
||||
));
|
||||
if matches!(
|
||||
marker,
|
||||
0xc0..=0xc3 | 0xc5..=0xc7 | 0xc9..=0xcb | 0xcd..=0xcf
|
||||
) {
|
||||
let components = *encoded
|
||||
.get(marker_offset + 8)
|
||||
.ok_or(Error::InvalidOperation)?;
|
||||
return match components {
|
||||
1 => Ok(true),
|
||||
3 => Ok(false),
|
||||
_ => Err(Error::InvalidOperation),
|
||||
};
|
||||
}
|
||||
if length < 2 {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
offset = marker_offset
|
||||
.checked_add(1)
|
||||
.and_then(|offset| offset.checked_add(length))
|
||||
.ok_or(Error::InvalidOperation)?;
|
||||
}
|
||||
Err(Error::InvalidOperation)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn gif_dimensions(encoded: &[u8]) -> Result<(i32, i32), Error> {
|
||||
if encoded.len() < 13 || !(encoded.starts_with(b"GIF87a") || encoded.starts_with(b"GIF89a")) {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
let canvas = (
|
||||
i32::from(u16::from_le_bytes([encoded[6], encoded[7]])),
|
||||
i32::from(u16::from_le_bytes([encoded[8], encoded[9]])),
|
||||
);
|
||||
validate_dimensions(canvas.0, canvas.1)?;
|
||||
|
||||
let global_table_bytes = if encoded[10] & 0x80 == 0 {
|
||||
0
|
||||
} else {
|
||||
3_usize
|
||||
.checked_mul(1_usize << (usize::from(encoded[10] & 0x07) + 1))
|
||||
.ok_or(Error::InvalidOperation)?
|
||||
};
|
||||
let mut offset = 13_usize
|
||||
.checked_add(global_table_bytes)
|
||||
.filter(|offset| *offset <= encoded.len())
|
||||
.ok_or(Error::InvalidOperation)?;
|
||||
loop {
|
||||
let marker = *encoded.get(offset).ok_or(Error::InvalidOperation)?;
|
||||
offset += 1;
|
||||
match marker {
|
||||
0x2c => {
|
||||
let end = offset.checked_add(9).ok_or(Error::InvalidOperation)?;
|
||||
let descriptor = encoded.get(offset..end).ok_or(Error::InvalidOperation)?;
|
||||
let frame_width = i32::from(u16::from_le_bytes([descriptor[4], descriptor[5]]));
|
||||
let frame_height = i32::from(u16::from_le_bytes([descriptor[6], descriptor[7]]));
|
||||
validate_dimensions(frame_width, frame_height)?;
|
||||
return Ok(canvas);
|
||||
}
|
||||
0x21 => {
|
||||
offset = offset.checked_add(1).ok_or(Error::InvalidOperation)?;
|
||||
loop {
|
||||
let length = *encoded.get(offset).ok_or(Error::InvalidOperation)?;
|
||||
offset += 1;
|
||||
if length == 0 {
|
||||
break;
|
||||
}
|
||||
offset = offset
|
||||
.checked_add(usize::from(length))
|
||||
.filter(|offset| *offset <= encoded.len())
|
||||
.ok_or(Error::InvalidOperation)?;
|
||||
}
|
||||
}
|
||||
_ => return Err(Error::InvalidOperation),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn wbmp_dimensions(encoded: &[u8]) -> Result<(i32, i32), Error> {
|
||||
if encoded.get(..2) != Some(&[0, 0]) {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
let mut offset = 2;
|
||||
let width =
|
||||
i32::try_from(read_wbmp_integer(encoded, &mut offset)?).map_err(|_| Error::Argument)?;
|
||||
let height =
|
||||
i32::try_from(read_wbmp_integer(encoded, &mut offset)?).map_err(|_| Error::Argument)?;
|
||||
validate_dimensions(width, height)?;
|
||||
Ok((width, height))
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn read_wbmp_integer(encoded: &[u8], offset: &mut usize) -> Result<u32, Error> {
|
||||
let mut value = 0_u32;
|
||||
for _ in 0..5 {
|
||||
let byte = *encoded.get(*offset).ok_or(Error::InvalidOperation)?;
|
||||
*offset += 1;
|
||||
value = value
|
||||
.checked_shl(7)
|
||||
.and_then(|value| value.checked_add(u32::from(byte & 0x7f)))
|
||||
.ok_or(Error::InvalidOperation)?;
|
||||
if byte & 0x80 == 0 {
|
||||
return Ok(value);
|
||||
}
|
||||
}
|
||||
Err(Error::InvalidOperation)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn ico_dimensions(encoded: &[u8]) -> Result<(i32, i32), Error> {
|
||||
if encoded.len() < 6 || encoded.get(..4) != Some(&[0, 0, 1, 0]) {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
let count = usize::from(u16::from_le_bytes([encoded[4], encoded[5]]));
|
||||
let mut best: Option<(u32, usize, usize)> = None;
|
||||
for index in 0..count {
|
||||
let offset = 6_usize
|
||||
.checked_add(index.checked_mul(16).ok_or(Error::InvalidOperation)?)
|
||||
.ok_or(Error::InvalidOperation)?;
|
||||
let end = offset.checked_add(16).ok_or(Error::InvalidOperation)?;
|
||||
let entry = encoded.get(offset..end).ok_or(Error::InvalidOperation)?;
|
||||
let width = if entry[0] == 0 {
|
||||
256
|
||||
} else {
|
||||
u32::from(entry[0])
|
||||
};
|
||||
let height = if entry[1] == 0 {
|
||||
256
|
||||
} else {
|
||||
u32::from(entry[1])
|
||||
};
|
||||
let area = width.checked_mul(height).ok_or(Error::Argument)?;
|
||||
let length = usize::try_from(u32::from_le_bytes(
|
||||
entry[8..12]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidOperation)?,
|
||||
))
|
||||
.map_err(|_| Error::Argument)?;
|
||||
let image_offset = usize::try_from(u32::from_le_bytes(
|
||||
entry[12..16]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidOperation)?,
|
||||
))
|
||||
.map_err(|_| Error::Argument)?;
|
||||
if best.is_none_or(|(best_area, _, _)| area > best_area) {
|
||||
best = Some((area, image_offset, length));
|
||||
}
|
||||
}
|
||||
let (_, offset, length) = best.ok_or(Error::InvalidOperation)?;
|
||||
let end = offset.checked_add(length).ok_or(Error::Argument)?;
|
||||
let image = encoded
|
||||
.get(offset..end)
|
||||
.filter(|image| !image.is_empty())
|
||||
.ok_or(Error::InvalidOperation)?;
|
||||
if image.starts_with(&[0x89, b'P', b'N', b'G']) {
|
||||
return skia_rs_codec::get_image_dimensions(image).map_err(|_| Error::InvalidOperation);
|
||||
}
|
||||
if image.len() < 40 {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
let header_size = u32::from_le_bytes(
|
||||
image[0..4]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidOperation)?,
|
||||
);
|
||||
if header_size < 40 {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
let width = i32::from_le_bytes(
|
||||
image[4..8]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidOperation)?,
|
||||
);
|
||||
let stored_height = i32::from_le_bytes(
|
||||
image[8..12]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidOperation)?,
|
||||
);
|
||||
if stored_height <= 0 || stored_height % 2 != 0 {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
Ok((width, stored_height / 2))
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn validate_dimensions(width: i32, height: i32) -> Result<(), Error> {
|
||||
let width = usize::try_from(width).map_err(|_| Error::Argument)?;
|
||||
let height = usize::try_from(height).map_err(|_| Error::Argument)?;
|
||||
width
|
||||
.checked_mul(height)
|
||||
.filter(|pixels| *pixels > 0 && *pixels <= DEFAULT_MAX_PIXELS)
|
||||
.map(|_| ())
|
||||
.ok_or(Error::Argument)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn decode_webp_with_rust(encoded: &[u8]) -> Result<ManagedImage, Error> {
|
||||
use std::io::{BufReader, Cursor};
|
||||
|
||||
let reader = BufReader::new(Cursor::new(encoded));
|
||||
let mut decoder = image_webp::WebPDecoder::new(reader).map_err(|_| Error::InvalidOperation)?;
|
||||
let (width, height) = decoder.dimensions();
|
||||
let animated = decoder.is_animated();
|
||||
let width_i32 = i32::try_from(width).map_err(|_| Error::Argument)?;
|
||||
let height_i32 = i32::try_from(height).map_err(|_| Error::Argument)?;
|
||||
validate_dimensions(width_i32, height_i32)?;
|
||||
decoder.set_memory_limit(DEFAULT_MAX_PIXELS * 16);
|
||||
|
||||
let output_size = decoder.output_buffer_size().ok_or(Error::Argument)?;
|
||||
if output_size > DEFAULT_MAX_PIXELS * 4 {
|
||||
return Err(Error::Argument);
|
||||
}
|
||||
let mut packed_pixels = Vec::new();
|
||||
packed_pixels
|
||||
.try_reserve_exact(output_size)
|
||||
.map_err(|_| Error::InvalidOperation)?;
|
||||
packed_pixels.resize(output_size, 0);
|
||||
decoder
|
||||
.read_image(&mut packed_pixels)
|
||||
.map_err(|_| Error::InvalidOperation)?;
|
||||
|
||||
let has_alpha = decoder.has_alpha();
|
||||
// image-webp 0.2 uses a divide-by-256 blend fast path for animated
|
||||
// canvases. Its fully opaque nonzero samples are consequently one below
|
||||
// Skia/libwebp's divide-by-255 result. Correct that bounded first-frame
|
||||
// canvas here; partially transparent samples already use the same rounding
|
||||
// as the compatibility backend.
|
||||
if animated {
|
||||
if has_alpha {
|
||||
for rgba in packed_pixels.chunks_exact_mut(4) {
|
||||
if rgba[3] == u8::MAX {
|
||||
for channel in &mut rgba[..3] {
|
||||
if *channel != 0 {
|
||||
*channel = channel.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for channel in &mut packed_pixels {
|
||||
if *channel != 0 {
|
||||
*channel = channel.saturating_add(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let pixels = if has_alpha {
|
||||
packed_pixels
|
||||
} else {
|
||||
let pixel_count = usize::try_from(width)
|
||||
.ok()
|
||||
.and_then(|width| {
|
||||
usize::try_from(height)
|
||||
.ok()
|
||||
.and_then(|height| width.checked_mul(height))
|
||||
})
|
||||
.ok_or(Error::Argument)?;
|
||||
let rgba_size = pixel_count.checked_mul(4).ok_or(Error::Argument)?;
|
||||
let mut rgba = Vec::new();
|
||||
rgba.try_reserve_exact(rgba_size)
|
||||
.map_err(|_| Error::InvalidOperation)?;
|
||||
for rgb in packed_pixels.chunks_exact(3) {
|
||||
rgba.extend_from_slice(&[rgb[0], rgb[1], rgb[2], u8::MAX]);
|
||||
}
|
||||
if rgba.len() != rgba_size {
|
||||
return Err(Error::InvalidOperation);
|
||||
}
|
||||
rgba
|
||||
};
|
||||
let row_bytes = usize::try_from(width)
|
||||
.map_err(|_| Error::Argument)?
|
||||
.checked_mul(4)
|
||||
.ok_or(Error::Argument)?;
|
||||
let bitmap = SKBitmap::new(
|
||||
width_i32,
|
||||
height_i32,
|
||||
row_bytes,
|
||||
SKColorType::Rgba8888,
|
||||
if has_alpha {
|
||||
SKAlphaType::Unpremul
|
||||
} else {
|
||||
SKAlphaType::Opaque
|
||||
},
|
||||
pixels,
|
||||
)?;
|
||||
bitmap_to_managed(&bitmap)
|
||||
}
|
||||
|
||||
#[cfg(feature = "skia")]
|
||||
fn decode_with_skia(encoded: &[u8]) -> Result<ManagedImage, Error> {
|
||||
use skia_safe::Data;
|
||||
@@ -528,6 +972,394 @@ mod tests {
|
||||
SkiaTextureCodec.decode(Box::new(std::io::Cursor::new(Vec::new()))),
|
||||
Err(Error::InvalidOperation)
|
||||
);
|
||||
#[cfg(not(feature = "rust-skia"))]
|
||||
assert_eq!(
|
||||
RustSkiaTextureCodec.decode(Box::new(std::io::Cursor::new(Vec::new()))),
|
||||
Err(Error::InvalidOperation)
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "rust-skia", feature = "skia"))]
|
||||
fn hex_fixture(source: &str) -> Vec<u8> {
|
||||
let digits: Vec<_> = source.bytes().filter(u8::is_ascii_hexdigit).collect();
|
||||
assert_eq!(digits.len() % 2, 0, "fixture contains a partial byte");
|
||||
digits
|
||||
.chunks_exact(2)
|
||||
.map(|pair| {
|
||||
let high = (pair[0] as char).to_digit(16).expect("hex digit");
|
||||
let low = (pair[1] as char).to_digit(16).expect("hex digit");
|
||||
u8::try_from(high * 16 + low).expect("hex byte")
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
fn rust_decode(encoded: Vec<u8>) -> Result<ManagedImage, Error> {
|
||||
RustSkiaTextureCodec.decode(Box::new(std::io::Cursor::new(encoded)))
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "rust-skia", feature = "skia"))]
|
||||
fn checked_format_matrix() -> [(&'static str, &'static str, (i32, i32)); 19] {
|
||||
[
|
||||
(
|
||||
"BMP 16-bit RGB555",
|
||||
include_str!("../tests/fixtures/rgb555.bmp.hex"),
|
||||
(2, 1),
|
||||
),
|
||||
(
|
||||
"BMP 24-bit bottom-up",
|
||||
include_str!("../tests/fixtures/bottom-up.bmp.hex"),
|
||||
(8, 8),
|
||||
),
|
||||
(
|
||||
"BMP 32-bit BGRX",
|
||||
include_str!("../tests/fixtures/bgrx32.bmp.hex"),
|
||||
(2, 1),
|
||||
),
|
||||
(
|
||||
"GIF palette and frame offset",
|
||||
include_str!("../tests/fixtures/palette-offset.gif.hex"),
|
||||
(4, 2),
|
||||
),
|
||||
(
|
||||
"ICO largest entry",
|
||||
include_str!("../tests/fixtures/multi.ico.hex"),
|
||||
(2, 2),
|
||||
),
|
||||
(
|
||||
"JPEG baseline RGB",
|
||||
include_str!("../tests/fixtures/baseline.jpg.hex"),
|
||||
(8, 8),
|
||||
),
|
||||
(
|
||||
"JPEG progressive grayscale",
|
||||
include_str!("../tests/fixtures/progressive.jpg.hex"),
|
||||
(128, 128),
|
||||
),
|
||||
(
|
||||
"PNG grayscale",
|
||||
include_str!("../tests/fixtures/gray.png.hex"),
|
||||
(32, 32),
|
||||
),
|
||||
(
|
||||
"PNG grayscale alpha",
|
||||
include_str!("../tests/fixtures/gray-alpha.png.hex"),
|
||||
(32, 32),
|
||||
),
|
||||
(
|
||||
"PNG RGB",
|
||||
include_str!("../tests/fixtures/rgb.png.hex"),
|
||||
(32, 32),
|
||||
),
|
||||
(
|
||||
"PNG RGBA",
|
||||
include_str!("../tests/fixtures/rgba.png.hex"),
|
||||
(32, 32),
|
||||
),
|
||||
(
|
||||
"PNG straight alpha",
|
||||
include_str!("../tests/fixtures/straight-alpha.png.hex"),
|
||||
(1, 1),
|
||||
),
|
||||
(
|
||||
"PNG interlaced palette",
|
||||
include_str!("../tests/fixtures/interlaced-palette.png.hex"),
|
||||
(32, 32),
|
||||
),
|
||||
(
|
||||
"WBMP multibyte width",
|
||||
include_str!("../tests/fixtures/multibyte.wbmp.hex"),
|
||||
(130, 1),
|
||||
),
|
||||
(
|
||||
"WBMP minimum-length image",
|
||||
include_str!("../tests/fixtures/small.wbmp.hex"),
|
||||
(2, 2),
|
||||
),
|
||||
(
|
||||
"WebP lossless RGB",
|
||||
include_str!("../tests/fixtures/rgb-lossless.webp.hex"),
|
||||
(2, 2),
|
||||
),
|
||||
(
|
||||
"WebP lossless alpha",
|
||||
include_str!("../tests/fixtures/alpha.webp.hex"),
|
||||
(1, 1),
|
||||
),
|
||||
(
|
||||
"WebP lossy",
|
||||
include_str!("../tests/fixtures/lossy-red.webp.hex"),
|
||||
(8, 8),
|
||||
),
|
||||
(
|
||||
"WebP animated first frame",
|
||||
include_str!("../tests/fixtures/animated.webp.hex"),
|
||||
(11, 29),
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "rust-skia", feature = "skia"))]
|
||||
fn assert_checked_format_matrix(codec: &dyn libremetaverse_imaging::ITextureCodec) {
|
||||
for (name, fixture, dimensions) in checked_format_matrix() {
|
||||
let image = codec
|
||||
.decode(Box::new(std::io::Cursor::new(hex_fixture(fixture))))
|
||||
.unwrap_or_else(|error| panic!("{name} failed to decode: {error:?}"));
|
||||
assert_eq!((image.width, image.height), dimensions, "{name}");
|
||||
assert_eq!(
|
||||
image.channels,
|
||||
if matches!(
|
||||
name,
|
||||
"JPEG progressive grayscale"
|
||||
| "PNG grayscale"
|
||||
| "WBMP multibyte width"
|
||||
| "WBMP minimum-length image"
|
||||
) {
|
||||
ManagedImageImageChannels::GRAY
|
||||
} else {
|
||||
ManagedImageImageChannels::COLOR | ManagedImageImageChannels::ALPHA
|
||||
},
|
||||
"{name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
#[test]
|
||||
fn rust_feature_decodes_the_checked_format_matrix() {
|
||||
assert_checked_format_matrix(&RustSkiaTextureCodec);
|
||||
}
|
||||
|
||||
#[cfg(feature = "skia")]
|
||||
#[test]
|
||||
fn native_feature_decodes_the_checked_format_matrix() {
|
||||
assert_checked_format_matrix(&SkiaTextureCodec);
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "rust-skia", feature = "skia"))]
|
||||
#[test]
|
||||
fn native_and_rust_backends_match_the_shared_contract_matrix() {
|
||||
fn assert_plane(name: &str, plane: &str, native: &[u8], rust: &[u8], tolerance: u8) {
|
||||
assert_eq!(native.len(), rust.len(), "{name} {plane} length");
|
||||
for (index, (&native, &rust)) in native.iter().zip(rust).enumerate() {
|
||||
assert!(
|
||||
native.abs_diff(rust) <= tolerance,
|
||||
"{name} {plane}[{index}]: native={native}, rust={rust}, tolerance={tolerance}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
for (name, fixture, _) in checked_format_matrix() {
|
||||
let bytes = hex_fixture(fixture);
|
||||
let native = SkiaTextureCodec
|
||||
.decode(Box::new(std::io::Cursor::new(bytes.clone())))
|
||||
.unwrap_or_else(|error| panic!("native {name}: {error:?}"));
|
||||
let rust = RustSkiaTextureCodec
|
||||
.decode(Box::new(std::io::Cursor::new(bytes)))
|
||||
.unwrap_or_else(|error| panic!("Rust {name}: {error:?}"));
|
||||
assert_eq!(native.width, rust.width, "{name} width");
|
||||
assert_eq!(native.height, rust.height, "{name} height");
|
||||
assert_eq!(native.channels, rust.channels, "{name} channels");
|
||||
let tolerance = if name.starts_with("JPEG") {
|
||||
8
|
||||
} else if name == "WebP lossy" {
|
||||
10
|
||||
} else {
|
||||
0
|
||||
};
|
||||
assert_plane(name, "red", &native.red, &rust.red, tolerance);
|
||||
assert_plane(name, "green", &native.green, &rust.green, tolerance);
|
||||
assert_plane(name, "blue", &native.blue, &rust.blue, tolerance);
|
||||
assert_plane(name, "alpha", &native.alpha, &rust.alpha, tolerance);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
#[test]
|
||||
fn rust_feature_preserves_canvas_orientation_selection_and_alpha() {
|
||||
for fixture in [
|
||||
include_str!("../tests/fixtures/two-by-two-bottom-up.bmp.hex"),
|
||||
include_str!("../tests/fixtures/two-by-two-top-down.bmp.hex"),
|
||||
] {
|
||||
let bitmap = rust_decode(hex_fixture(fixture)).expect("oriented BMP");
|
||||
assert_eq!(bitmap.red, [255, 0, 0, 255]);
|
||||
assert_eq!(bitmap.green, [0, 255, 0, 255]);
|
||||
assert_eq!(bitmap.blue, [0, 0, 255, 255]);
|
||||
}
|
||||
|
||||
let gif = rust_decode(hex_fixture(include_str!(
|
||||
"../tests/fixtures/palette-offset.gif.hex"
|
||||
)))
|
||||
.expect("GIF logical canvas");
|
||||
assert_eq!((gif.width, gif.height), (4, 2));
|
||||
|
||||
let icon = rust_decode(hex_fixture(include_str!("../tests/fixtures/multi.ico.hex")))
|
||||
.expect("largest ICO entry");
|
||||
assert_eq!(icon.red, [255, 0, 0, 255]);
|
||||
assert_eq!(icon.green, [0, 255, 0, 255]);
|
||||
assert_eq!(icon.blue, [0, 0, 255, 255]);
|
||||
|
||||
let alpha = rust_decode(hex_fixture(include_str!(
|
||||
"../tests/fixtures/alpha.webp.hex"
|
||||
)))
|
||||
.expect("alpha WebP");
|
||||
assert_eq!(
|
||||
(alpha.red[0], alpha.green[0], alpha.blue[0]),
|
||||
(255, 255, 255)
|
||||
);
|
||||
assert!((127..=128).contains(&alpha.alpha[0]));
|
||||
|
||||
let lossy = rust_decode(hex_fixture(include_str!(
|
||||
"../tests/fixtures/lossy-red.webp.hex"
|
||||
)))
|
||||
.expect("lossy WebP");
|
||||
assert!(lossy.red.iter().all(|red| *red >= 245));
|
||||
assert!(lossy.green.iter().all(|green| *green <= 10));
|
||||
assert!(lossy.blue.iter().all(|blue| *blue <= 10));
|
||||
assert!(lossy.alpha.iter().all(|alpha| *alpha == u8::MAX));
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
#[test]
|
||||
fn rust_feature_rejects_invalid_truncated_and_oversized_input_without_panicking() {
|
||||
for malformed in [Vec::new(), b"not an image".to_vec(), b"GIF89a".to_vec()] {
|
||||
let result =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rust_decode(malformed)));
|
||||
assert!(result.is_ok(), "malformed input panicked");
|
||||
assert_eq!(result.expect("checked above"), Err(Error::InvalidOperation));
|
||||
}
|
||||
|
||||
let mut pixel_bomb =
|
||||
hex_fixture(include_str!("../tests/fixtures/interlaced-palette.png.hex"));
|
||||
pixel_bomb[16..20].copy_from_slice(&4097_u32.to_be_bytes());
|
||||
pixel_bomb[20..24].copy_from_slice(&4097_u32.to_be_bytes());
|
||||
assert_eq!(rust_decode(pixel_bomb), Err(Error::Argument));
|
||||
|
||||
let mut gif_frame_bomb =
|
||||
hex_fixture(include_str!("../tests/fixtures/palette-offset.gif.hex"));
|
||||
let descriptor = gif_frame_bomb[109..]
|
||||
.iter()
|
||||
.position(|byte| *byte == 0x2c)
|
||||
.map(|offset| offset + 109)
|
||||
.expect("first GIF image descriptor");
|
||||
gif_frame_bomb[descriptor + 5..descriptor + 7].copy_from_slice(&u16::MAX.to_le_bytes());
|
||||
gif_frame_bomb[descriptor + 7..descriptor + 9].copy_from_slice(&u16::MAX.to_le_bytes());
|
||||
assert_eq!(rust_decode(gif_frame_bomb), Err(Error::Argument));
|
||||
|
||||
let mut malformed_gif_palette =
|
||||
hex_fixture(include_str!("../tests/fixtures/palette-offset.gif.hex"));
|
||||
// Advertise a 256-entry global palette while retaining the fixture's
|
||||
// much smaller checked table. Preflight must reject the missing table
|
||||
// before the decoder can allocate or index palette storage.
|
||||
malformed_gif_palette[10] = (malformed_gif_palette[10] & 0xf8) | 0x07;
|
||||
assert_eq!(
|
||||
rust_decode(malformed_gif_palette),
|
||||
Err(Error::InvalidOperation)
|
||||
);
|
||||
|
||||
let mut icon_embedded_bomb = hex_fixture(include_str!("../tests/fixtures/multi.ico.hex"));
|
||||
icon_embedded_bomb[86..90].copy_from_slice(&4097_i32.to_le_bytes());
|
||||
icon_embedded_bomb[90..94].copy_from_slice(&8194_i32.to_le_bytes());
|
||||
assert_eq!(rust_decode(icon_embedded_bomb), Err(Error::Argument));
|
||||
|
||||
let over_limit = vec![0_u8; DEFAULT_MAX_ENCODED_BYTES + 1];
|
||||
assert_eq!(rust_decode(over_limit), Err(Error::Argument));
|
||||
|
||||
for fixture in [
|
||||
include_str!("../tests/fixtures/bottom-up.bmp.hex"),
|
||||
include_str!("../tests/fixtures/palette-offset.gif.hex"),
|
||||
include_str!("../tests/fixtures/multi.ico.hex"),
|
||||
include_str!("../tests/fixtures/interlaced-palette.png.hex"),
|
||||
include_str!("../tests/fixtures/alpha.webp.hex"),
|
||||
] {
|
||||
let mut bytes = hex_fixture(fixture);
|
||||
bytes.truncate(bytes.len() / 2);
|
||||
let result =
|
||||
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rust_decode(bytes)));
|
||||
assert!(result.is_ok(), "truncated input panicked");
|
||||
assert!(result.expect("checked above").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
struct DropStream {
|
||||
cursor: std::io::Cursor<Vec<u8>>,
|
||||
drops: std::sync::Arc<std::sync::atomic::AtomicUsize>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
impl std::io::Read for DropStream {
|
||||
fn read(&mut self, buffer: &mut [u8]) -> std::io::Result<usize> {
|
||||
std::io::Read::read(&mut self.cursor, buffer)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
impl std::io::Write for DropStream {
|
||||
fn write(&mut self, buffer: &[u8]) -> std::io::Result<usize> {
|
||||
std::io::Write::write(&mut self.cursor, buffer)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
impl std::io::Seek for DropStream {
|
||||
fn seek(&mut self, position: std::io::SeekFrom) -> std::io::Result<u64> {
|
||||
std::io::Seek::seek(&mut self.cursor, position)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
impl Drop for DropStream {
|
||||
fn drop(&mut self) {
|
||||
self.drops.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rust-skia")]
|
||||
#[test]
|
||||
fn rust_feature_is_thread_safe_across_repeated_decode_and_drop() {
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
fn assert_texture_codec<T: libremetaverse_imaging::ITextureCodec + Send + Sync>() {}
|
||||
assert_texture_codec::<RustSkiaTextureCodec>();
|
||||
|
||||
let codec = Arc::new(RustSkiaTextureCodec);
|
||||
let png = Arc::new(hex_fixture(include_str!(
|
||||
"../tests/fixtures/interlaced-palette.png.hex"
|
||||
)));
|
||||
let mut workers = Vec::new();
|
||||
for _ in 0..8 {
|
||||
let codec = Arc::clone(&codec);
|
||||
let png = Arc::clone(&png);
|
||||
workers.push(std::thread::spawn(move || {
|
||||
for _ in 0..16 {
|
||||
let image = codec
|
||||
.decode(Box::new(std::io::Cursor::new((*png).clone())))
|
||||
.expect("concurrent PNG decode");
|
||||
assert_eq!((image.width, image.height), (32, 32));
|
||||
let repeated = codec
|
||||
.decode(Box::new(std::io::Cursor::new((*png).clone())))
|
||||
.expect("repeated concurrent PNG decode");
|
||||
assert_eq!(image, repeated);
|
||||
}
|
||||
}));
|
||||
}
|
||||
for worker in workers {
|
||||
worker.join().expect("decoder worker did not panic");
|
||||
}
|
||||
|
||||
let drops = Arc::new(AtomicUsize::new(0));
|
||||
let stream = DropStream {
|
||||
cursor: std::io::Cursor::new((*png).clone()),
|
||||
drops: Arc::clone(&drops),
|
||||
};
|
||||
codec.decode(Box::new(stream)).expect("drop-probe decode");
|
||||
assert_eq!(drops.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[cfg(feature = "skia")]
|
||||
|
||||
Reference in New Issue
Block a user