use std::sync::OnceLock;
use anyhow::{Context, Result, bail};
use resvg::{tiny_skia, usvg};
use crate::turbo::Bgra;
pub const RAW: [&str; 4] = ["cr2", "nef", "arw", "dng"];
pub fn decode_svg(data: &[u8], max_long: u32) -> Result<Bgra> {
let tree = usvg::Tree::from_data(data, &svg_options()).context("reading the SVG")?;
let size = tree.size();
let (w, h) = (size.width(), size.height());
if !(w > 0.0 && h > 0.0) {
bail!("the SVG has no size");
}
let scale = max_long.clamp(1, 4096) as f32 / w.max(h);
let (pw, ph) = (((w * scale).round() as u32).max(1), ((h * scale).round() as u32).max(1));
let mut pixmap = tiny_skia::Pixmap::new(pw, ph).context("allocating the SVG canvas")?;
resvg::render(&tree, tiny_skia::Transform::from_scale(scale, scale), &mut pixmap.as_mut());
let mut pixels = pixmap.take();
for px in pixels.as_chunks_mut::<4>().0 {
let a = px[3] as u32;
if a > 0 && a < 255 {
for c in &mut px[..3] {
*c = ((*c as u32 * 255 + a / 2) / a).min(255) as u8;
}
}
px.swap(0, 2);
}
Ok(Bgra { width: pw, height: ph, pixels })
}
fn svg_options() -> usvg::Options<'static> {
static FONTS: OnceLock<std::sync::Arc<usvg::fontdb::Database>> = OnceLock::new();
let fonts = FONTS.get_or_init(|| {
let mut db = usvg::fontdb::Database::new();
db.load_system_fonts();
std::sync::Arc::new(db)
});
usvg::Options { fontdb: fonts.clone(), ..Default::default() }
}
pub fn is_webp(data: &[u8]) -> bool {
data.len() >= 12 && &data[..4] == b"RIFF" && &data[8..12] == b"WEBP"
}
pub fn decode_webp(data: &[u8], min_long: u32) -> Option<Result<(Bgra, (u32, u32))>> {
use libwebp_sys as w;
unsafe {
let mut cfg: w::WebPDecoderConfig = std::mem::zeroed();
if !w::WebPInitDecoderConfig(&mut cfg) {
return Some(Err(anyhow::anyhow!("libwebp version mismatch")));
}
if w::WebPGetFeatures(data.as_ptr(), data.len(), &mut cfg.input) != w::VP8StatusCode::VP8_STATUS_OK {
return Some(Err(anyhow::anyhow!("not a WebP picture")));
}
if cfg.input.has_animation != 0 {
return None;
}
let (fw, fh) = (cfg.input.width.max(1) as u32, cfg.input.height.max(1) as u32);
let long = fw.max(fh);
if min_long < long {
let s = min_long as f64 / long as f64;
cfg.options.use_scaling = 1;
cfg.options.scaled_width = ((fw as f64 * s).round() as i32).max(1);
cfg.options.scaled_height = ((fh as f64 * s).round() as i32).max(1);
}
cfg.options.use_threads = 1;
cfg.output.colorspace = w::WEBP_CSP_MODE::MODE_BGRA;
if w::WebPDecode(data.as_ptr(), data.len(), &mut cfg) != w::VP8StatusCode::VP8_STATUS_OK {
w::WebPFreeDecBuffer(&mut cfg.output);
return Some(Err(anyhow::anyhow!("decoding the WebP picture")));
}
let rgba = cfg.output.u.RGBA;
let (width, height) = (cfg.output.width as u32, cfg.output.height as u32);
let mut pixels = Vec::with_capacity((width * height * 4) as usize);
for y in 0..height as usize {
let row = std::slice::from_raw_parts(rgba.rgba.add(y * rgba.stride as usize), width as usize * 4);
pixels.extend_from_slice(row);
}
w::WebPFreeDecBuffer(&mut cfg.output);
Some(Ok((Bgra { width, height, pixels }, (fw, fh))))
}
}
pub fn decode_psd(d: &[u8]) -> Result<Bgra> {
let be16 = |o: usize| d.get(o..o + 2).map(|b| u16::from_be_bytes([b[0], b[1]]) as usize);
let be32 = |o: usize| d.get(o..o + 4).map(|b| u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize);
let be64 = |o: usize| d.get(o..o + 8).map(|b| u64::from_be_bytes(b.try_into().unwrap()) as usize);
if !d.starts_with(b"8BPS") {
bail!("not a Photoshop file");
}
let psb = match be16(4) {
Some(1) => false,
Some(2) => true,
_ => bail!("unknown Photoshop version"),
};
let short = || anyhow::anyhow!("the Photoshop file is cut short");
let channels = be16(12).ok_or_else(short)?;
let height = be32(14).ok_or_else(short)?;
let width = be32(18).ok_or_else(short)?;
let depth = be16(22).ok_or_else(short)?;
let mode = be16(24).ok_or_else(short)?;
let colors = match mode {
1 => 1,
3 => 3,
_ => bail!("Photoshop color mode {mode} is not supported"),
};
if !matches!(depth, 8 | 16) || channels < colors || width == 0 || height == 0 {
bail!("Photoshop {depth}-bit pictures are not supported");
}
if width.checked_mul(height).is_none_or(|n| n > 200_000_000) {
bail!("the Photoshop picture is too large");
}
let skip = |at: usize, len: Option<usize>, field: usize| {
len.and_then(|n| at.checked_add(field)?.checked_add(n)).filter(|&e| e <= d.len()).ok_or_else(short)
};
let mut at = 26;
at = skip(at, be32(at), 4)?;
at = skip(at, be32(at), 4)?;
at = if psb { skip(at, be64(at), 8)? } else { skip(at, be32(at), 4)? };
let compression = be16(at).ok_or_else(short)?;
at += 2;
let bps = depth / 8;
let row_len = width * bps;
let alpha = channels > colors;
let rows = height * (colors + usize::from(alpha));
let size = rows * row_len;
let rest = d.len().saturating_sub(at);
let fits = match compression {
0 => size <= rest,
1 => size / 64 <= rest,
_ => bail!("Photoshop compression {compression} is not supported"),
};
if !fits {
return Err(short());
}
let mut planes = vec![0u8; size];
match compression {
0 => {
let n = planes.len();
planes.copy_from_slice(d.get(at..at + n).ok_or_else(short)?);
}
_ => {
let len_size = if psb { 4 } else { 2 };
let mut src = at + height * channels * len_size;
for r in 0..rows {
let n = if psb { be32(at + r * 4) } else { be16(at + r * 2) }.ok_or_else(short)?;
let line = d.get(src..src + n).ok_or_else(short)?;
unpack_bits(line, &mut planes[r * row_len..(r + 1) * row_len]);
src += n;
}
}
}
let sample = |ch: usize, i: usize| planes[(ch * height * width + i) * bps];
let mut pixels = Vec::with_capacity(width * height * 4);
for i in 0..width * height {
let (r, g, b) = if colors == 1 {
let v = sample(0, i);
(v, v, v)
} else {
(sample(0, i), sample(1, i), sample(2, i))
};
pixels.extend_from_slice(&[b, g, r, if alpha { sample(colors, i) } else { 255 }]);
}
Ok(Bgra { width: width as u32, height: height as u32, pixels })
}
fn unpack_bits(mut src: &[u8], out: &mut [u8]) {
let mut o = 0;
while let Some((&n, rest)) = src.split_first() {
src = rest;
if n < 128 {
let k = n as usize + 1;
let (Some(lit), Some(dst)) = (src.get(..k), out.get_mut(o..o + k)) else { return };
dst.copy_from_slice(lit);
src = &src[k..];
o += k;
} else if n > 128 {
let k = 257 - n as usize;
let (Some(&v), Some(dst)) = (src.first(), out.get_mut(o..o + k)) else { return };
dst.fill(v);
src = &src[1..];
o += k;
}
}
}
pub fn raw_preview(data: &[u8]) -> Option<(&[u8], u8)> {
let t = Tiff::new(data)?;
let mut best: Option<&[u8]> = None;
let mut orientation = 1;
let mut queue = vec![t.u32(4)? as usize];
let mut seen = 0;
while let Some(ifd) = queue.pop() {
seen += 1;
if seen > 64 || ifd == 0 {
continue;
}
let Some(count) = t.u16(ifd) else { continue };
let entries = (0..count as usize).map(|k| ifd + 2 + k * 12);
let (mut jpeg_at, mut jpeg_len, mut strip_at, mut strip_len, mut compression) = (None, None, None, None, None);
for e in entries {
let Some(tag) = t.u16(e) else { break };
let value = t.value(e);
match tag {
0x0112 if seen == 1 => orientation = value.unwrap_or(1).clamp(1, 8) as u8,
0x0103 => compression = value,
0x0111 => strip_at = value,
0x0117 => strip_len = value,
0x0201 => jpeg_at = value,
0x0202 => jpeg_len = value,
0x014A => queue.extend(t.offsets(e)),
_ => {}
}
}
if let Some(next) = t.u32(ifd + 2 + count as usize * 12) {
queue.push(next as usize);
}
let mut candidates = vec![(jpeg_at, jpeg_len)];
if matches!(compression, Some(6 | 7)) {
candidates.push((strip_at, strip_len));
}
for (at, len) in candidates {
let (Some(at), Some(len)) = (at, len) else { continue };
let Some(end) = (at as usize).checked_add(len as usize) else { continue };
let Some(jpeg) = data.get(at as usize..end) else { continue };
if jpeg.starts_with(&[0xFF, 0xD8]) && is_plain_jpeg(jpeg) && best.is_none_or(|b| jpeg.len() > b.len()) {
best = Some(jpeg);
}
}
}
best.map(|j| (j, orientation))
}
fn is_plain_jpeg(j: &[u8]) -> bool {
let mut i = 2;
while i + 4 <= j.len() {
if j[i] != 0xFF {
return false;
}
let marker = j[i + 1];
if matches!(marker, 0xC0..=0xC2) {
return true;
}
if matches!(marker, 0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF | 0xDA | 0xD9) {
return false;
}
i += 2 + u16::from_be_bytes([j[i + 2], j[i + 3]]) as usize;
}
false
}
struct Tiff<'a> {
t: &'a [u8],
le: bool,
}
impl<'a> Tiff<'a> {
fn new(t: &'a [u8]) -> Option<Self> {
let le = match t.get(..4)? {
b"II*\0" => true,
b"MM\0*" => false,
_ => return None,
};
Some(Tiff { t, le })
}
fn u16(&self, o: usize) -> Option<u16> {
let b = [*self.t.get(o)?, *self.t.get(o + 1)?];
Some(if self.le { u16::from_le_bytes(b) } else { u16::from_be_bytes(b) })
}
fn u32(&self, o: usize) -> Option<u32> {
let b = [*self.t.get(o)?, *self.t.get(o + 1)?, *self.t.get(o + 2)?, *self.t.get(o + 3)?];
Some(if self.le { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) })
}
fn value(&self, e: usize) -> Option<u32> {
match self.u16(e + 2)? {
3 => self.u16(e + 8).map(u32::from),
4 | 13 => self.u32(e + 8),
_ => None,
}
}
fn offsets(&self, e: usize) -> Vec<usize> {
let n = self.u32(e + 4).unwrap_or(0).min(16) as usize;
let at = if n <= 1 { e + 8 } else { self.u32(e + 8).unwrap_or(0) as usize };
(0..n).filter_map(|k| self.u32(at + k * 4).map(|v| v as usize)).collect()
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
pub fn jpeg(w: u32, h: u32) -> Vec<u8> {
let b = Bgra { width: w, height: h, pixels: vec![128; (w * h * 4) as usize] };
crate::turbo::encode(&b, 80).unwrap()
}
pub fn tiff(ifd0: &[(u16, u16, u32, u32)], subs: &[Vec<(u16, u16, u32, u32)>], blobs: &[Vec<u8>]) -> Vec<u8> {
let ifd_len = |n: usize| 2 + n * 12 + 4;
let mut ifds = vec![ifd0.to_vec()];
ifds.extend(subs.iter().cloned());
let mut at = 8;
let ifd_at: Vec<usize> = ifds
.iter()
.map(|i| {
let here = at;
at += ifd_len(i.len());
here
})
.collect();
let blob_at: Vec<usize> = blobs
.iter()
.map(|b| {
let here = at;
at += b.len();
here
})
.collect();
let mut out = b"II*\0".to_vec();
out.extend_from_slice(&8u32.to_le_bytes());
for (k, ifd) in ifds.iter().enumerate() {
out.extend_from_slice(&(ifd.len() as u16).to_le_bytes());
for &(tag, ty, count, value) in ifd {
let v = match value {
v if v >= u32::MAX - 8 => blob_at[(u32::MAX - v) as usize] as u32,
v if v >= u32::MAX - 200 => ifd_at[(u32::MAX - 100 - v) as usize + 1] as u32,
v => v,
};
out.extend_from_slice(&tag.to_le_bytes());
out.extend_from_slice(&ty.to_le_bytes());
out.extend_from_slice(&count.to_le_bytes());
out.extend_from_slice(&v.to_le_bytes());
}
let _ = k;
out.extend_from_slice(&0u32.to_le_bytes());
}
for b in blobs {
out.extend_from_slice(b);
}
out
}
const BLOB0: u32 = u32::MAX;
const BLOB1: u32 = u32::MAX - 1;
const SUB0: u32 = u32::MAX - 100;
#[test]
fn the_largest_jpeg_preview_is_picked_from_ifd0_and_sub_ifds() {
let (small, large) = (jpeg(16, 12), jpeg(64, 48));
let raw = tiff(
&[(0x0112, 3, 1, 6), (0x0201, 4, 1, BLOB0), (0x0202, 4, 1, small.len() as u32), (0x014A, 4, 1, SUB0)],
&[vec![(0x0103, 3, 1, 7), (0x0111, 4, 1, BLOB1), (0x0117, 4, 1, large.len() as u32)]],
&[small.clone(), large.clone()],
);
let (preview, orientation) = raw_preview(&raw).unwrap();
assert_eq!(preview, &large[..]);
assert_eq!(orientation, 6);
}
#[test]
fn broken_or_lossless_previews_are_skipped() {
let good = jpeg(16, 12);
let mut lossless = vec![0xFF, 0xD8, 0xFF, 0xC3, 0x00, 0x0B];
lossless.extend_from_slice(&[0; 9]);
let raw = tiff(
&[(0x0201, 4, 1, BLOB0), (0x0202, 4, 1, good.len() as u32), (0x014A, 4, 1, SUB0)],
&[vec![(0x0103, 3, 1, 7), (0x0111, 4, 1, BLOB1), (0x0117, 4, 1, lossless.len() as u32 + 4000)]],
&[good.clone(), lossless],
);
assert_eq!(raw_preview(&raw).map(|(p, o)| (p.len(), o)), Some((good.len(), 1)));
assert_eq!(raw_preview(b"II*\0\xff\xff\xff\xff"), None);
assert_eq!(raw_preview(b"not a tiff"), None);
let looped = tiff(&[(0x014A, 4, 1, 8)], &[], &[]);
assert_eq!(raw_preview(&looped), None);
}
#[test]
fn webp_stills_decode_scaled_and_animations_are_left_alone() {
let mut still = Vec::new();
let img = image::RgbaImage::from_fn(80, 40, |x, _| {
if x < 40 { image::Rgba([255, 0, 0, 255]) } else { image::Rgba([0, 0, 255, 255]) }
});
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut still), image::ImageFormat::WebP)
.unwrap();
let (b, full) = decode_webp(&still, 1000).unwrap().unwrap();
assert_eq!((b.width, b.height, full), (80, 40, (80, 40)), "never enlarged");
assert_eq!(&b.pixels[..4], &[0, 0, 255, 255], "red, as BGRA");
let (small, full) = decode_webp(&still, 20).unwrap().unwrap();
assert_eq!((small.width, small.height, full), (20, 10, (80, 40)));
assert!(decode_webp(b"RIFF\0\0\0\0WEBPjunk", 100).unwrap().is_err());
}
#[test]
fn photoshop_files_give_their_flattened_picture() {
let mut psd = b"8BPS\0\x01\0\0\0\0\0\0\0\x03".to_vec();
psd.extend_from_slice(&1u32.to_be_bytes());
psd.extend_from_slice(&2u32.to_be_bytes());
psd.extend_from_slice(&[0, 8, 0, 3]);
psd.extend_from_slice(&[0; 12]); psd.extend_from_slice(&[0, 1]); let lines: [&[u8]; 3] = [&[1, 10, 20], &[255, 30], &[1, 40, 50]];
for l in lines {
psd.extend_from_slice(&(l.len() as u16).to_be_bytes());
}
for l in lines {
psd.extend_from_slice(l);
}
let b = decode_psd(&psd).unwrap();
assert_eq!((b.width, b.height), (2, 1));
assert_eq!(b.pixels, vec![40, 30, 10, 255, 50, 30, 20, 255]);
for n in 0..psd.len() {
assert!(decode_psd(&psd[..n]).is_err(), "cut at {n}");
}
psd[24..26].copy_from_slice(&[0, 4]);
assert!(decode_psd(&psd).is_err(), "CMYK");
}
#[test]
fn a_header_bigger_than_its_file_is_refused_before_allocating() {
let mut d = b"8BPS".to_vec();
d.extend_from_slice(&[0, 1, 0, 0, 0, 0, 0, 0]);
d.extend_from_slice(&255u16.to_be_bytes()); d.extend_from_slice(&10_000u32.to_be_bytes()); d.extend_from_slice(&10_000u32.to_be_bytes()); d.extend_from_slice(&16u16.to_be_bytes());
d.extend_from_slice(&3u16.to_be_bytes()); d.extend_from_slice(&[0; 12]); d.extend_from_slice(&1u16.to_be_bytes()); d.extend_from_slice(&[0; 16]);
assert!(decode_psd(&d).is_err());
let at = d.len() - 18;
d[at..at + 2].copy_from_slice(&0u16.to_be_bytes()); assert!(decode_psd(&d).is_err());
let wrap = include_bytes!("../tests/fixtures/psd-offset-overflow.psd");
assert!(decode_psd(wrap).is_err());
}
#[test]
fn svgs_are_drawn_at_the_size_asked() {
let svg = br##"<svg xmlns="http://www.w3.org/2000/svg" width="40" height="20"><rect width="20" height="20" fill="#ff0000"/><rect x="20" width="20" height="20" fill="#0000ff" fill-opacity="0.5"/></svg>"##;
let b = decode_svg(svg, 200).unwrap();
assert_eq!((b.width, b.height), (200, 100));
let px = |x: u32, y: u32| b.pixels[((y * b.width + x) * 4) as usize..][..4].to_vec();
assert_eq!(px(50, 50), vec![0, 0, 255, 255], "red, as BGRA");
let half = px(150, 50);
assert_eq!((half[0], half[3]), (255, 128), "blue at half opacity, not premultiplied: {half:?}");
assert!(decode_svg(b"<svg", 100).is_err());
}
}