use crate::document::Document;
use crate::error::{Error, Result};
use crate::filters::{self, Cap};
use crate::object::{Dictionary, Object, Stream};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ImageOptions {
pub max_pixels: usize,
pub pad_short_data: bool,
}
impl Default for ImageOptions {
fn default() -> Self {
Self { max_pixels: 100_000_000, pad_short_data: false }
}
}
impl ImageOptions {
#[must_use]
pub fn with_max_pixels(max_pixels: usize) -> Self {
Self { max_pixels, ..Self::default() }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ColorSpace {
Gray,
Rgb,
Cmyk,
Indexed {
base: Box<ColorSpace>,
palette: Vec<u8>,
},
Other {
name: Vec<u8>,
components: usize,
},
}
impl ColorSpace {
#[must_use]
pub fn components(&self) -> usize {
match self {
Self::Gray | Self::Indexed { .. } => 1,
Self::Rgb => 3,
Self::Cmyk => 4,
Self::Other { components, .. } => *components,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Image {
pub width: u32,
pub height: u32,
pub color_space: ColorSpace,
pub stencil: bool,
pub samples: Vec<u8>,
pub alpha: Option<Vec<u8>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LenientImage {
pub image: Image,
pub concealed: Vec<String>,
pub damaged: Vec<String>,
}
impl LenientImage {
#[must_use]
pub fn is_complete(&self) -> bool {
self.concealed.is_empty()
}
}
#[derive(Default)]
struct Report {
concealed: Vec<String>,
damaged: Vec<String>,
}
fn image_error<T>(m: impl Into<String>) -> Result<T> {
Err(Error::Image(m.into()))
}
fn cmyk_to_rgb(c: u8, m: u8, y: u8, k: u8) -> [u8; 3] {
let k = 255 - u16::from(k);
[c, m, y].map(|v| ((255 - u16::from(v)) * k / 255) as u8)
}
fn luma(r: u8, g: u8, b: u8) -> u8 {
((u32::from(r) * 77 + u32::from(g) * 150 + u32::from(b) * 29) >> 8) as u8
}
impl Image {
pub fn to_rgb8(&self) -> Result<Vec<u8>> {
convert_rgb(&self.color_space, &self.samples)
}
pub fn to_gray8(&self) -> Result<Vec<u8>> {
if self.color_space == ColorSpace::Gray {
return Ok(self.samples.clone());
}
let rgb = self.to_rgb8()?;
Ok(rgb.as_chunks::<3>().0.iter().map(|p| luma(p[0], p[1], p[2])).collect())
}
}
fn convert_rgb(space: &ColorSpace, samples: &[u8]) -> Result<Vec<u8>> {
match space {
ColorSpace::Gray => Ok(samples.iter().flat_map(|g| [*g; 3]).collect()),
ColorSpace::Rgb => Ok(samples.to_vec()),
ColorSpace::Cmyk => Ok(samples
.as_chunks::<4>().0.iter()
.flat_map(|p| cmyk_to_rgb(p[0], p[1], p[2], p[3]))
.collect()),
ColorSpace::Indexed { base, palette } => {
let n = base.components();
let mut entries = Vec::with_capacity(samples.len() * n);
for index in samples {
let at = usize::from(*index) * n;
match palette.get(at..at + n) {
Some(entry) => entries.extend_from_slice(entry),
None => entries.extend(std::iter::repeat_n(0, n)),
}
}
convert_rgb(base, &entries)
}
ColorSpace::Other { name, .. } => image_error(format!(
"colour space {} needs a colour-managed conversion",
String::from_utf8_lossy(name)
)),
}
}
fn entry<'a>(doc: &'a Document, dict: &'a Dictionary, long: &[u8], short: &[u8]) -> Result<&'a Object> {
match doc.lookup(dict, long)? {
Object::Null => doc.lookup(dict, short),
o => Ok(o),
}
}
fn dimension(doc: &Document, dict: &Dictionary, long: &'static [u8], short: &[u8]) -> Result<usize> {
let name = String::from_utf8_lossy(long);
let v = entry(doc, dict, long, short)?
.as_i64()
.map_err(|_| Error::Image(format!("missing /{name}")))?;
usize::try_from(v)
.ok()
.filter(|v| *v > 0)
.ok_or_else(|| Error::Image(format!("/{name} {v} is not a positive size")))
}
fn color_space(doc: &Document, object: &Object, resources: Option<&Dictionary>, depth: u8) -> Result<ColorSpace> {
if depth > 4 {
return image_error("colour spaces nested too deeply");
}
let object = doc.resolve(object)?;
let by_name = |name: &[u8]| -> Result<ColorSpace> {
match name {
b"DeviceGray" | b"G" | b"CalGray" => Ok(ColorSpace::Gray),
b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(ColorSpace::Rgb),
b"DeviceCMYK" | b"CMYK" => Ok(ColorSpace::Cmyk),
other => {
let named = resources
.and_then(|r| doc.lookup_dict(r, b"ColorSpace"))
.and_then(|spaces| spaces.get(other));
match named {
Some(o) => color_space(doc, o, None, depth + 1),
None => image_error(format!("unknown colour space {}", String::from_utf8_lossy(other))),
}
}
}
};
let items = match object {
Object::Name(n) => return by_name(n),
Object::Array(a) => a,
_ => return image_error("unrecognised colour space"),
};
let family = match items.first().map(|o| doc.resolve(o)).transpose()? {
Some(Object::Name(n)) => n.as_slice(),
_ => return image_error("unrecognised colour space"),
};
let arg = |i: usize| -> Result<&Object> {
match items.get(i) {
Some(o) => doc.resolve(o),
None => image_error("colour space array is too short"),
}
};
match family {
b"ICCBased" => {
let n = arg(1)?.as_dict().ok().and_then(|d| doc.lookup(d, b"N").ok()).and_then(|o| o.as_i64().ok());
match n {
Some(1) => Ok(ColorSpace::Gray),
Some(3) | None => Ok(ColorSpace::Rgb),
Some(4) => Ok(ColorSpace::Cmyk),
Some(other) => image_error(format!("ICC colour space with {other} components")),
}
}
b"Indexed" | b"I" => {
let base = color_space(doc, arg(1)?, resources, depth + 1)?;
if matches!(base, ColorSpace::Indexed { .. }) {
return image_error("an Indexed colour space cannot be based on another");
}
let hival = arg(2)?.as_i64().ok().and_then(|v| usize::try_from(v).ok()).unwrap_or(255).min(255);
let wanted = (hival + 1) * base.components();
let mut palette = match arg(3)? {
Object::String(s, _) => s.clone(),
Object::Stream(s) => doc.decode_partial(s, Cap::clip(wanted))?.data.into_owned(),
_ => return image_error("Indexed colour space has no lookup table"),
};
palette.truncate(wanted);
Ok(ColorSpace::Indexed { base: Box::new(base), palette })
}
b"Separation" => Ok(ColorSpace::Other { name: family.to_vec(), components: 1 }),
b"DeviceN" => {
let n = arg(1)?.as_array().map(<[Object]>::len).unwrap_or(0);
if (1..=32).contains(&n) {
Ok(ColorSpace::Other { name: family.to_vec(), components: n })
} else {
image_error("DeviceN colour space with an unusable component count")
}
}
b"Lab" => Ok(ColorSpace::Other { name: family.to_vec(), components: 3 }),
b"Pattern" => image_error("an image cannot use a Pattern colour space"),
other => by_name(other),
}
}
fn unpack(raw: &[u8], width: usize, height: usize, components: usize, bits: usize, scale: bool) -> Vec<u8> {
let per_row = width * components;
let row_bytes = (per_row * bits).div_ceil(8);
let mut out = Vec::with_capacity(per_row * height);
for row in raw.chunks(row_bytes).take(height) {
match bits {
8 => out.extend_from_slice(&row[..per_row.min(row.len())]),
16 => out.extend(row.as_chunks::<2>().0.iter().take(per_row).map(|p| p[0])),
1 => {
let table = if scale { &EXPAND_1BIT_SCALED } else { &EXPAND_1BIT_RAW };
let full = per_row / 8;
for &b in row.iter().take(full) {
out.extend_from_slice(&table[usize::from(b)]);
}
let rest = per_row % 8;
if rest > 0 {
if let Some(&b) = row.get(full) {
out.extend_from_slice(&table[usize::from(b)][..rest]);
}
}
}
_ => {
let max = (1u16 << bits) - 1;
for s in 0..per_row {
let bit = s * bits;
let Some(byte) = row.get(bit / 8) else { break };
let v = u16::from(byte >> (8 - bits - bit % 8)) & max;
out.push(if scale { (v * 255 / max) as u8 } else { v as u8 });
}
}
}
}
out
}
const fn expand_1bit(one: u8) -> [[u8; 8]; 256] {
let mut table = [[0u8; 8]; 256];
let mut b = 0;
while b < 256 {
let mut i = 0;
while i < 8 {
if (b >> (7 - i)) & 1 == 1 {
table[b][i] = one;
}
i += 1;
}
b += 1;
}
table
}
static EXPAND_1BIT_SCALED: [[u8; 8]; 256] = expand_1bit(255);
static EXPAND_1BIT_RAW: [[u8; 8]; 256] = expand_1bit(1);
fn apply_decode(samples: &mut [u8], decode: &[f64], components: usize) {
if decode.len() < components * 2 {
return;
}
let maps: Vec<Option<[u8; 256]>> = (0..components)
.map(|c| {
let (lo, hi) = (decode[c * 2], decode[c * 2 + 1]);
if (lo, hi) == (0.0, 1.0) || !lo.is_finite() || !hi.is_finite() {
return None;
}
let mut table = [0u8; 256];
for (v, slot) in table.iter_mut().enumerate() {
#[allow(clippy::cast_precision_loss)]
let x = lo + (v as f64 / 255.0) * (hi - lo);
#[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
{
*slot = (x.clamp(0.0, 1.0) * 255.0).round() as u8;
}
}
Some(table)
})
.collect();
if maps.iter().all(Option::is_none) {
return;
}
for pixel in samples.chunks_exact_mut(components) {
for (sample, map) in pixel.iter_mut().zip(&maps) {
if let Some(table) = map {
*sample = table[usize::from(*sample)];
}
}
}
}
impl Document {
pub fn decode_image(&self, stream: &Stream, options: &ImageOptions) -> Result<Image> {
self.decode_image_with(stream, None, options)
}
pub fn decode_image_with(
&self,
stream: &Stream,
resources: Option<&Dictionary>,
options: &ImageOptions,
) -> Result<Image> {
self.decode_image_inner(stream, resources, options, None)
}
pub fn decode_image_lenient(
&self,
stream: &Stream,
resources: Option<&Dictionary>,
options: &ImageOptions,
) -> Result<LenientImage> {
let mut report = Report::default();
let image = self.decode_image_inner(stream, resources, options, Some(&mut report))?;
Ok(LenientImage { image, concealed: report.concealed, damaged: report.damaged })
}
fn decode_image_inner(
&self,
stream: &Stream,
resources: Option<&Dictionary>,
options: &ImageOptions,
mut conceal: Option<&mut Report>,
) -> Result<Image> {
let dict = &stream.dict;
let width = dimension(self, dict, b"Width", b"W")?;
let height = dimension(self, dict, b"Height", b"H")?;
let pixels = width
.checked_mul(height)
.filter(|p| *p <= options.max_pixels)
.ok_or(Error::Limit { what: "image pixels", limit: options.max_pixels as u64 })?;
let (Ok(w32), Ok(h32)) = (u32::try_from(width), u32::try_from(height)) else {
return image_error("image dimensions out of range");
};
let stencil = entry(self, dict, b"ImageMask", b"IM")?.as_bool().unwrap_or(false);
let declared_space = match entry(self, dict, b"ColorSpace", b"CS")? {
_ if stencil => Some(ColorSpace::Gray),
Object::Null => None,
o => Some(color_space(self, o, resources, 0)?),
};
let decode: Vec<f64> = match entry(self, dict, b"Decode", b"D")? {
Object::Array(a) => a.iter().filter_map(|o| self.resolve(o).ok()?.as_f64().ok()).collect(),
_ => Vec::new(),
};
let encoded_cap = pixels.saturating_mul(8).saturating_add(1 << 20).min(self.limits.max_stream_bytes);
let has_codec = self.filter_chain(dict)?.iter().any(|(name, _)| filters::is_image_filter(name));
let (space, mut samples, alpha) = if has_codec {
let partial = self.decode_partial(stream, Cap::strict(encoded_cap))?;
let Some((codec, parms)) = partial.image else {
return image_error("image codec is not the last filter");
};
if !partial.complete {
match conceal.as_deref_mut() {
Some(r) => r.concealed.push("the filters before the image codec stopped early: the codec gets the data decoded up to that point".into()),
None => return image_error("encoded image data is damaged"),
}
}
let geometry = Geometry { width, height, pixels };
match filters::canonical_name(codec) {
b"DCTDecode" => {
self.decode_dct(&partial.data, parms.as_deref(), declared_space, geometry, conceal.as_deref_mut())?
}
b"JPXDecode" => {
self.decode_jpx(&partial.data, dict, declared_space, geometry, conceal.as_deref_mut())?
}
bilevel => {
let packed = if bilevel == b"CCITTFaxDecode" {
decode_ccitt(&partial.data, parms.as_deref(), geometry, conceal.as_deref_mut())?
} else {
self.decode_jbig2(&partial.data, parms.as_deref(), geometry)?
};
let space = declared_space.unwrap_or(ColorSpace::Gray);
if space.components() != 1 {
return image_error("a bi-level image needs a one-component colour space");
}
let scale = !matches!(space, ColorSpace::Indexed { .. });
(space, unpack(&packed, width, height, 1, 1, scale), None)
}
}
} else {
let Some(space) = declared_space else {
return image_error("missing /ColorSpace");
};
let bits = if stencil {
1
} else {
match entry(self, dict, b"BitsPerComponent", b"BPC")?.as_i64() {
Ok(b @ (1 | 2 | 4 | 8 | 16)) => usize::try_from(b).unwrap_or(8),
Ok(other) => return image_error(format!("{other} bits per component is not supported")),
Err(_) => return image_error("missing /BitsPerComponent"),
}
};
let components = space.components();
let expected = width
.checked_mul(components)
.and_then(|v| v.checked_mul(bits))
.map(|row_bits| row_bits.div_ceil(8))
.and_then(|row| row.checked_mul(height))
.ok_or_else(|| Error::Image("image size overflows".into()))?;
let partial = self.decode_partial(stream, Cap::clip(expected))?;
if partial.data.len() < expected && !options.pad_short_data {
let message = format!("{} bytes of samples, {expected} needed", partial.data.len());
match conceal.as_deref_mut() {
Some(r) => r.concealed.push(format!("{message}: the rest are zero")),
None => return image_error(message),
}
}
let samples = if bits == 8 {
let mut data = partial.data.into_owned();
data.truncate(expected);
data
} else {
let scale = !matches!(space, ColorSpace::Indexed { .. });
unpack(&partial.data, width, height, components, bits, scale)
};
(space, samples, None)
};
let components = space.components();
let wanted = pixels
.checked_mul(components)
.ok_or_else(|| Error::Image("image size overflows".into()))?;
if samples.len() < wanted && !options.pad_short_data {
let message = format!("{} samples decoded, {wanted} needed", samples.len());
match conceal {
Some(_) if !has_codec => {}
Some(r) => r.concealed.push(format!("{message}: the rest are zero")),
None => return image_error(message),
}
}
samples.resize(wanted, 0);
if !matches!(space, ColorSpace::Indexed { .. }) {
apply_decode(&mut samples, &decode, components);
}
Ok(Image { width: w32, height: h32, color_space: space, stencil, samples, alpha })
}
#[cfg(feature = "dct")]
fn decode_dct(
&self,
data: &[u8],
parms: Option<&Dictionary>,
declared: Option<ColorSpace>,
g: Geometry,
mut conceal: Option<&mut Report>,
) -> Result<Decoded> {
use rusty_jpeg::decode::WarningClass;
use rusty_jpeg::{ColorTransform, Decoder, PixelFormat};
let fail = |e: &dyn std::fmt::Display| Error::Image(format!("JPEG: {e}"));
let mut decoder = Decoder::new(data);
decoder.set_max_decoding_buffer_size(g.pixels.saturating_mul(8).saturating_add(1 << 16));
decoder.read_info().map_err(|e| fail(&e))?;
let header = decoder.frame_header().ok_or_else(|| Error::Image("JPEG has no frame".into()))?;
if (usize::from(header.width), usize::from(header.height)) != (g.width, g.height) {
return image_error("JPEG dimensions disagree with /Width and /Height");
}
let transform = parms.and_then(|p| p.get_i64(b"ColorTransform"));
match (header.components, transform) {
(3, Some(0)) => decoder.set_color_transform(ColorTransform::None),
(3, Some(_)) => decoder.set_color_transform(ColorTransform::YCbCr),
(4, Some(0)) => decoder.set_color_transform(ColorTransform::CMYK),
(4, Some(_)) => decoder.set_color_transform(ColorTransform::YCCK),
_ => {}
}
let mut pixels = decoder.decode().map_err(|e| fail(&e))?;
for w in decoder.warnings() {
match (w.class(), conceal.as_deref_mut()) {
(WarningClass::Harmless, _) => {}
(WarningClass::Damaged, Some(r)) => r.damaged.push(jpeg_concealment(w)),
(WarningClass::Damaged, None) => {}
(_, Some(r)) => r.concealed.push(jpeg_concealment(w)),
(_, None) => return image_error(format!("damaged image data ({})", jpeg_concealment(w))),
}
}
let info = decoder.info().ok_or_else(|| Error::Image("JPEG pixel format is not supported".into()))?;
let space = match info.pixel_format {
PixelFormat::L8 => ColorSpace::Gray,
PixelFormat::L16 => {
pixels = pixels.as_chunks::<2>().0.iter().map(|p| p[0]).collect();
ColorSpace::Gray
}
PixelFormat::RGB24 => ColorSpace::Rgb,
PixelFormat::CMYK32 => {
for v in &mut pixels {
*v = 255 - *v;
}
ColorSpace::Cmyk
}
};
let space = match declared {
Some(d) if d.components() == space.components() => d,
Some(_) => return image_error("JPEG component count disagrees with /ColorSpace"),
None => space,
};
Ok((space, pixels, None))
}
#[cfg(feature = "jpx")]
fn decode_jpx(
&self,
data: &[u8],
dict: &Dictionary,
declared: Option<ColorSpace>,
g: Geometry,
conceal: Option<&mut Report>,
) -> Result<Decoded> {
let fail = |e: &dyn std::fmt::Display| Error::Image(format!("JPEG 2000: {e}"));
let indexed = matches!(declared, Some(ColorSpace::Indexed { .. }));
let mut options = rusty_jpx::DecodeOptions::new()
.with_apply_palette(!indexed)
.with_allow_truncated(conceal.is_some());
options.limits.max_samples = (g.pixels as u64).saturating_mul(5);
let image = rusty_jpx::decode_jpx_with(data, &options).map_err(|e| fail(&e))?;
if let Some(r) = conceal {
r.concealed.extend(image.concealed.iter().map(jpx_concealment));
}
if (image.width as usize, image.height as usize) != (g.width, g.height) {
return image_error("JPEG 2000 dimensions disagree with /Width and /Height");
}
let plane = |index: usize, scale: bool| -> Result<Vec<u8>> {
let c = &image.components[index];
let data = image
.upsampled(index)
.ok_or_else(|| Error::Image("JPEG 2000 component has no samples".into()))?;
Ok(data.iter().map(|v| jpx_sample(*v, c.bits, c.signed, scale)).collect())
};
let color: Vec<usize> = (0..image.components.len())
.filter(|i| image.components[*i].role == rusty_jpx::ChannelRole::Color)
.collect();
let color = if color.is_empty() { (0..image.components.len()).collect() } else { color };
let space = match (declared, color.len()) {
(Some(d), n) if d.components() <= n => d,
(Some(_), _) => return image_error("JPEG 2000 has fewer components than /ColorSpace needs"),
(None, 1) => ColorSpace::Gray,
(None, 3) => ColorSpace::Rgb,
(None, 4) => ColorSpace::Cmyk,
(None, n) => return image_error(format!("JPEG 2000 with {n} colour components and no /ColorSpace")),
};
let n = space.components();
let scale = !matches!(space, ColorSpace::Indexed { .. });
let mut samples = vec![0u8; g.pixels * n];
for (k, index) in color.iter().take(n).enumerate() {
let c = &image.components[*index];
let data = image
.upsampled(*index)
.ok_or_else(|| Error::Image("JPEG 2000 component has no samples".into()))?;
for (slot, v) in samples.iter_mut().skip(k).step_by(n).zip(data.iter()) {
*slot = jpx_sample(*v, c.bits, c.signed, scale);
}
}
let wants_alpha = self.lookup(dict, b"SMaskInData")?.as_i64().unwrap_or(0) != 0;
let alpha = if wants_alpha {
let opacity = (0..image.components.len()).find(|i| {
matches!(
image.components[*i].role,
rusty_jpx::ChannelRole::Opacity | rusty_jpx::ChannelRole::PremultipliedOpacity
)
});
opacity.map(|i| plane(i, true)).transpose()?
} else {
None
};
Ok((space, samples, alpha))
}
#[cfg(feature = "jbig2")]
fn decode_jbig2(&self, data: &[u8], parms: Option<&Dictionary>, g: Geometry) -> Result<Vec<u8>> {
let globals = match parms.and_then(|p| p.get(b"JBIG2Globals")) {
Some(o) => match self.resolve(o)? {
Object::Stream(s) => Some(self.decode_stream(s, self.limits.max_stream_bytes.min(64 << 20))?),
_ => None,
},
None => None,
};
let page_pixels = (g.width.div_ceil(8) as u64 * 8).saturating_mul(g.height as u64);
let limits = rusty_jbig2::Limits::default().with_max_pixels(page_pixels.max(1 << 16));
let options = rusty_jbig2::DecodeOptions::new().with_limits(limits);
let bitmap = rusty_jbig2::decode_jbig2_with(data, globals.as_deref(), &options)
.map_err(|e| Error::Image(format!("JBIG2: {e}")))?;
if (bitmap.width as usize, bitmap.height as usize) != (g.width, g.height) {
return image_error("JBIG2 dimensions disagree with /Width and /Height");
}
Ok(bitmap.into_pdf_samples())
}
#[cfg(not(feature = "dct"))]
fn decode_dct(
&self,
_: &[u8],
_: Option<&Dictionary>,
_: Option<ColorSpace>,
_: Geometry,
_: Option<&mut Report>,
) -> Result<Decoded> {
Err(Error::UnsupportedFilter("DCTDecode (the `dct` feature is off)".into()))
}
#[cfg(not(feature = "jpx"))]
fn decode_jpx(
&self,
_: &[u8],
_: &Dictionary,
_: Option<ColorSpace>,
_: Geometry,
_: Option<&mut Report>,
) -> Result<Decoded> {
Err(Error::UnsupportedFilter("JPXDecode (the `jpx` feature is off)".into()))
}
#[cfg(not(feature = "jbig2"))]
fn decode_jbig2(&self, _: &[u8], _: Option<&Dictionary>, _: Geometry) -> Result<Vec<u8>> {
Err(Error::UnsupportedFilter("JBIG2Decode (the `jbig2` feature is off)".into()))
}
}
#[cfg(feature = "dct")]
fn jpeg_concealment(w: &rusty_jpeg::decode::Warning) -> String {
use rusty_jpeg::decode::Warning as W;
let what = match w {
W::Truncated => "the data ends before the end-of-image marker: what was not reached is grey",
W::SegmentEndedEarly => "a scan segment ran out of data: the rest of it is grey (or earlier scans' values)",
W::BadHuffmanCode => "a bad Huffman code: decoding continued out of step until the next restart marker",
W::RestartMarkerMismatch => "a restart marker was out of sequence: decoding resynchronised",
W::ExtraneousBytes => "stray bytes between segments were skipped",
W::MissingScan => "a component has no scan data: its plane is mid-grey",
W::BadArithmeticCode => "a bad arithmetic code: the rest of that segment is not decoded",
W::InvalidScanParameters => "a sequential scan had invalid SOS parameters: decoded as if they were valid",
W::UnknownMarker => "an unknown marker segment (most likely a damaged byte) was skipped",
W::InvalidCoefficient => "the coded data holds values no valid stream can: decoded as read",
W::DefaultHuffmanTable => "a Huffman table was missing: the standard Annex K table stands in",
W::MissingEoi => "only the end-of-image marker is missing: every pixel decoded",
other => return format!("JPEG damage repaired ({other:?})"),
};
format!("JPEG: {what}")
}
#[cfg(feature = "jpx")]
fn jpx_concealment(c: &rusty_jpx::Concealment) -> String {
use rusty_jpx::ConcealmentKind as K;
let what = match c.kind {
K::TileMissing => "has no data: it is the DC level (mid-grey)".to_string(),
K::TilePartSkipped(why) => format!("lost a tile-part ({why}): it was skipped"),
K::PacketsMissing(why) => format!("stops early ({why}): the missing coding passes are zero"),
K::CodeBlocksCut => "has code-blocks cut short: decoded as far as they go".to_string(),
K::TileUnreadable(why) => format!("is unreadable ({why}): it is the DC level (mid-grey)"),
other => format!("was concealed ({other:?})"),
};
match c.tile {
Some(t) => format!("JPEG 2000 tile {t} {what}"),
None => format!("JPEG 2000 data {what}"),
}
}
#[cfg_attr(not(feature = "jpx"), allow(dead_code))]
fn jpx_sample(v: i32, bits: u8, signed: bool, scale: bool) -> u8 {
let bits = u32::from(bits.clamp(1, 31));
let offset = if signed { 1i64 << (bits - 1) } else { 0 };
let max = (1i64 << bits) - 1;
let v = (i64::from(v) + offset).clamp(0, max);
if scale {
(v * 255 / max) as u8
} else {
u8::try_from(v).unwrap_or(u8::MAX)
}
}
type Decoded = (ColorSpace, Vec<u8>, Option<Vec<u8>>);
#[derive(Debug, Clone, Copy)]
#[cfg_attr(not(any(feature = "dct", feature = "jpx", feature = "jbig2", feature = "ccitt")), allow(dead_code))]
struct Geometry {
width: usize,
height: usize,
#[cfg_attr(not(any(feature = "dct", feature = "jpx")), allow(dead_code))]
pixels: usize,
}
const MAX_CCITT_COLUMNS: usize = 100_000;
#[cfg(feature = "ccitt")]
fn decode_ccitt(data: &[u8], parms: Option<&Dictionary>, g: Geometry, conceal: Option<&mut Report>) -> Result<Vec<u8>> {
use rusty_tiff::ccitt::{self, Coding, FilterOptions, Options, Recovery, WarningKind};
let int = |key: &[u8]| parms.and_then(|p| p.get_i64(key));
let flag = |key: &[u8]| parms.and_then(|p| p.get_bool(key)).unwrap_or(false);
let k = int(b"K").unwrap_or(0);
let columns = match int(b"Columns") {
None => 1728,
Some(c) => usize::try_from(c)
.ok()
.filter(|c| (1..=MAX_CCITT_COLUMNS).contains(c))
.ok_or_else(|| Error::Image(format!("CCITT /Columns {c} out of range")))?,
};
let coding = match k {
k if k < 0 => Coding::Group4,
0 => Coding::Group3_1D,
_ => Coding::Group3_2D,
};
let (Ok(columns32), Ok(rows32)) = (u32::try_from(columns), u32::try_from(g.height)) else {
return image_error("CCITT dimensions out of range");
};
let stride = columns.div_ceil(8);
let mut options = Options::new(coding, columns32).with_rows(rows32);
options.encoded_byte_align = flag(b"EncodedByteAlign");
options.black_is_1 = flag(b"BlackIs1");
options.max_output_bytes = stride.saturating_mul(g.height).saturating_add(stride);
let fail = |e: ccitt::CcittError| Error::Image(format!("CCITT: {e}"));
let rows = match conceal {
None => ccitt::decode(data, &options).map_err(fail)?,
Some(report) => {
let mut filter = FilterOptions::new(options.clone())
.with_end_of_line(flag(b"EndOfLine"))
.with_end_of_block(parms.and_then(|p| p.get_bool(b"EndOfBlock")).unwrap_or(true))
.with_damaged_rows_before_error(
int(b"DamagedRowsBeforeError").and_then(|n| u32::try_from(n).ok()).unwrap_or(0),
)
.with_recovery(Recovery::Lenient);
if let Ok(k) = u32::try_from(k) {
filter.options.k = k;
}
let decoding = ccitt::decode_filter(data, &filter).map_err(fail)?;
for w in &decoding.warnings {
let line = match w.kind {
WarningKind::MissingEndOfLine => continue,
WarningKind::Truncated => {
format!("CCITT fax data stops in row {} ({}): the rest is white", w.row, w.message)
}
WarningKind::ConcealedRow => format!(
"CCITT fax row {} is damaged ({}): repaired, and 2-D rows after it up to the next 1-D row may be wrong",
w.row, w.message
),
_ => format!("CCITT fax row {}: {}", w.row, w.message),
};
report.concealed.push(line);
}
decoding.data
}
};
let out_stride = g.width.div_ceil(8);
if stride == out_stride {
return Ok(rows);
}
let white = if options.black_is_1 { 0x00 } else { 0xFF };
let mut out = Vec::with_capacity(out_stride * g.height);
for row in rows.chunks(stride).take(g.height) {
let keep = row.len().min(out_stride);
out.extend_from_slice(&row[..keep]);
out.extend(std::iter::repeat_n(white, out_stride - keep));
}
Ok(out)
}
#[cfg(not(feature = "ccitt"))]
fn decode_ccitt(_: &[u8], _: Option<&Dictionary>, _: Geometry, _: Option<&mut Report>) -> Result<Vec<u8>> {
let _ = MAX_CCITT_COLUMNS;
Err(Error::UnsupportedFilter("CCITTFaxDecode (the `ccitt` feature is off)".into()))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unpack_scales_small_samples() {
assert_eq!(unpack(&[0b0001_1011], 4, 1, 1, 2, true), [0, 85, 170, 255]);
assert_eq!(unpack(&[0b0001_1011], 4, 1, 1, 2, false), [0, 1, 2, 3]);
assert_eq!(unpack(&[0b1010_0000], 3, 1, 1, 1, true), [255, 0, 255]);
assert_eq!(unpack(&[0x12, 0x34, 0xAB, 0xCD], 2, 1, 1, 16, true), [0x12, 0xAB]);
assert_eq!(unpack(&[0b1000_0000, 0b0100_0000], 2, 2, 1, 1, true), [255, 0, 0, 255]);
let data: Vec<u8> = (0..97u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 24) as u8).collect();
for width in [1usize, 7, 8, 9, 15, 16, 17, 33] {
for scale in [true, false] {
let height = 5;
let row_bytes = width.div_ceil(8);
for take in [row_bytes * height, row_bytes * height - 1, row_bytes * 2 + 1] {
let input = &data[..take.min(data.len())];
let mut oracle = Vec::new();
for row in input.chunks(row_bytes).take(height) {
for x in 0..width {
let Some(byte) = row.get(x / 8) else { break };
let bit = (byte >> (7 - x % 8)) & 1;
oracle.push(if scale { bit * 255 } else { bit });
}
}
assert_eq!(unpack(input, width, height, 1, 1, scale), oracle, "width {width} scale {scale} take {take}");
}
}
}
}
#[test]
fn jpx_samples_keep_palette_indexes() {
assert_eq!(jpx_sample(3, 4, false, false), 3);
assert_eq!(jpx_sample(3, 4, false, true), 51);
assert_eq!(jpx_sample(15, 4, false, true), 255);
assert_eq!(jpx_sample(-128, 8, true, true), 0);
assert_eq!(jpx_sample(127, 8, true, true), 255);
assert_eq!(jpx_sample(4000, 12, false, false), 255);
}
#[test]
fn decode_arrays() {
let mut s = [0, 100, 255];
apply_decode(&mut s, &[1.0, 0.0], 1);
assert_eq!(s, [255, 155, 0]);
let mut s = [10, 20, 30];
apply_decode(&mut s, &[0.0, 1.0, 1.0, 0.0, 0.0, 1.0], 3);
assert_eq!(s, [10, 235, 30]);
}
#[test]
fn device_conversions() {
assert_eq!(cmyk_to_rgb(0, 0, 0, 0), [255, 255, 255]);
assert_eq!(cmyk_to_rgb(0, 0, 0, 255), [0, 0, 0]);
assert_eq!(cmyk_to_rgb(255, 0, 0, 0), [0, 255, 255]);
assert_eq!(luma(255, 255, 255), 255);
assert_eq!(luma(0, 0, 0), 0);
let indexed = ColorSpace::Indexed { base: Box::new(ColorSpace::Rgb), palette: vec![1, 2, 3, 4, 5, 6] };
assert_eq!(convert_rgb(&indexed, &[1, 0, 9]).unwrap(), [4, 5, 6, 1, 2, 3, 0, 0, 0]);
}
}