#![forbid(unsafe_code)]
#![deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing,
clippy::unreachable,
clippy::todo,
clippy::unimplemented
)]
pub mod ccitt;
pub mod dct;
pub mod jbig2;
#[cfg(feature = "jpx")]
pub mod jpx;
#[cfg(feature = "jxl")]
pub mod jxl;
mod bilevel;
#[cfg(test)]
pub(crate) mod fixtures;
#[cfg(test)]
mod fixtures_bilevel;
#[cfg(all(test, feature = "jpx"))]
mod fixtures_jpx;
#[cfg(all(test, feature = "jxl"))]
mod fixtures_jxl;
use pdfcer_model::document::Document;
use pdfcer_model::filters::{self, FilterError, FilterNotes};
use pdfcer_model::graph::ObjectGraph;
use pdfcer_model::object::{Dict, Object};
use pdfcer_model::view::DocumentView;
pub const MAX_IMAGE_PIXELS: u64 = 32 * 1024 * 1024;
pub const MAX_IMAGE_DIMENSION: u32 = 65_535;
pub const MAX_IMAGE_SAMPLE_BYTES: usize = 128 * 1024 * 1024;
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
#[non_exhaustive]
pub enum Codec {
Dct,
Ccitt,
Jbig2,
Jpx,
Jxl,
}
impl Codec {
#[must_use]
pub const fn name(self) -> &'static str {
match self {
Self::Dct => "DCTDecode",
Self::Ccitt => "CCITTFaxDecode",
Self::Jbig2 => "JBIG2Decode",
Self::Jpx => "JPXDecode",
Self::Jxl => "JXLDecode",
}
}
#[must_use]
pub const fn is_self_describing(self) -> bool {
matches!(self, Self::Jpx | Self::Jxl)
}
#[must_use]
pub const fn allowed_inline(self) -> bool {
match self {
Self::Dct | Self::Ccitt => true,
Self::Jbig2 | Self::Jpx | Self::Jxl => false,
}
}
const fn from_name(name: &[u8]) -> Option<Self> {
match name {
b"DCTDecode" | b"DCT" => Some(Self::Dct),
b"CCITTFaxDecode" | b"CCF" => Some(Self::Ccitt),
b"JBIG2Decode" => Some(Self::Jbig2),
b"JPXDecode" => Some(Self::Jpx),
b"JXLDecode" => Some(Self::Jxl),
_ => None,
}
}
}
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[non_exhaustive]
pub enum CodecColorModel {
Gray,
Rgb,
Untransformed3,
Cmyk,
Bilevel,
Unspecified,
Unknown {
components: u8,
},
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CodecNotes {
pub geometry_mismatch: bool,
pub cmyk_image: bool,
pub cmyk_polarity_unverifiable: bool,
pub jpx_smask_in_data_preblended: bool,
pub jpx_palette_left_to_pdf: bool,
pub jxl_nonstandard: bool,
pub lzw_framing_anomalies: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct CodedImage {
pub samples: Vec<u8>,
pub codec: Option<Codec>,
pub width: u32,
pub height: u32,
pub components: u8,
pub bits_per_component: u8,
pub color_model: CodecColorModel,
pub icc_profile: Option<Vec<u8>>,
pub embedded_alpha: Option<Vec<u8>>,
pub notes: CodecNotes,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ImageCodecError {
#[error(transparent)]
Filter(#[from] FilterError),
#[error("{} images are not supported in this build", .codec.name())]
Unsupported {
codec: Codec,
},
#[error("unsupported codec feature: {feature}")]
FeatureUnsupported {
feature: &'static str,
},
#[error("corrupt {} data: {detail}", .codec.name())]
Corrupt {
codec: Codec,
detail: String,
},
#[error("image exceeds pdfcer's decode ceilings ({MAX_IMAGE_PIXELS} pixels max)")]
TooLarge,
#[error("{} data may not appear in an inline image", .codec.name())]
NotAllowedInline {
codec: Codec,
},
#[error(
"/BrotliDecode may not appear in an inline image (EXTN-BROTLI-1 \u{a7}5.2); \
it is legal in any other stream"
)]
BrotliNotAllowedInline,
#[error("/Filter chain has an image codec that is not the final filter")]
CodecNotTerminal,
}
pub fn terminal_codec(dict: &Dict) -> Result<Option<Codec>, FilterError> {
let names = filters::filter_names(dict)?;
Ok(names.last().and_then(|n| Codec::from_name(n)))
}
pub fn decode_image(
doc: &Document,
dict: &Dict,
raw: &[u8],
inline: bool,
) -> Result<CodedImage, ImageCodecError> {
decode_image_view(&doc.view(), dict, raw, inline)
}
pub fn decode_image_view(
doc: &DocumentView<'_>,
dict: &Dict,
raw: &[u8],
inline: bool,
) -> Result<CodedImage, ImageCodecError> {
decode_image_view_with(doc, dict, raw, inline, CmykJpegPolarity::default())
}
pub fn decode_image_view_with(
doc: &DocumentView<'_>,
dict: &Dict,
raw: &[u8],
inline: bool,
polarity: CmykJpegPolarity,
) -> Result<CodedImage, ImageCodecError> {
let names = filters::filter_names(dict)?;
let codec = names.last().and_then(|n| Codec::from_name(n));
if names
.iter()
.rev()
.skip(1)
.any(|n| Codec::from_name(n).is_some())
{
return Err(ImageCodecError::CodecNotTerminal);
}
if let Some(codec) = codec
&& inline
&& !codec.allowed_inline()
{
return Err(ImageCodecError::NotAllowedInline { codec });
}
if inline && names.iter().any(|n| n.as_slice() == b"BrotliDecode") {
return Err(ImageCodecError::BrotliNotAllowedInline);
}
let prefix_len = names.len() - usize::from(codec.is_some());
let mut filter_notes = FilterNotes::default();
let data = filters::decode_prefix(dict, raw, prefix_len, &mut filter_notes)?;
let mut notes = CodecNotes {
lzw_framing_anomalies: filter_notes.lzw_framing_anomalies,
..CodecNotes::default()
};
let Some(codec) = codec else {
return Ok(uncoded(doc, dict, data, notes));
};
let parms = codec_parms(dict, names.len());
match codec {
Codec::Dct => dct::decode(doc, &data, parms, dict, polarity, &mut notes),
Codec::Ccitt => ccitt::decode(doc, &data, parms, dict, &mut notes),
Codec::Jbig2 => jbig2::decode(doc, &data, parms, dict, &mut notes),
#[cfg(feature = "jpx")]
Codec::Jpx => jpx::decode(doc, &data, dict, &mut notes),
#[cfg(not(feature = "jpx"))]
Codec::Jpx => Err(ImageCodecError::FeatureUnsupported {
feature: "JPX/not-built",
}),
#[cfg(feature = "jxl")]
Codec::Jxl => jxl::decode(doc, &data, dict, &mut notes),
#[cfg(not(feature = "jxl"))]
Codec::Jxl => Err(ImageCodecError::FeatureUnsupported {
feature: "JXL/not-built",
}),
}
}
fn uncoded(doc: &DocumentView<'_>, dict: &Dict, samples: Vec<u8>, notes: CodecNotes) -> CodedImage {
let int = |key: &[u8]| -> u32 {
dict.get(key)
.map(|o| doc.resolve(o))
.and_then(Object::as_int)
.and_then(|v| u32::try_from(v).ok())
.unwrap_or(0)
};
CodedImage {
samples,
codec: None,
width: int(b"Width"),
height: int(b"Height"),
components: 0,
bits_per_component: u8::try_from(int(b"BitsPerComponent")).unwrap_or(0),
color_model: CodecColorModel::Unspecified,
icc_profile: None,
embedded_alpha: None,
notes,
}
}
fn codec_parms(dict: &Dict, total: usize) -> Option<&Dict> {
let parms = dict.get(b"DecodeParms").or_else(|| dict.get(b"DP"))?;
match parms {
Object::Dict(d) if total == 1 => Some(d),
Object::Array(items) => match items.get(total.checked_sub(1)?) {
Some(Object::Dict(d)) => Some(d),
_ => None,
},
_ => None,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum CmykJpegPolarity {
#[default]
NeverInvert,
InvertOnApp14,
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
mod tests {
use super::*;
use pdfcer_model::object::Name;
fn dict_with(entries: Vec<(&[u8], Object)>) -> Dict {
let mut d = Dict::new();
for (k, v) in entries {
d.insert(Name::from(k), v);
}
d
}
fn name(n: &[u8]) -> Object {
Object::Name(Name::from(n))
}
#[test]
fn terminal_codec_recognizes_all_four_and_their_abbreviations() {
for (spelling, want) in [
(&b"DCTDecode"[..], Codec::Dct),
(b"DCT", Codec::Dct),
(b"CCITTFaxDecode", Codec::Ccitt),
(b"CCF", Codec::Ccitt),
(b"JBIG2Decode", Codec::Jbig2),
(b"JPXDecode", Codec::Jpx),
(b"JXLDecode", Codec::Jxl),
] {
let d = dict_with(vec![(b"Filter", name(spelling))]);
assert_eq!(terminal_codec(&d).unwrap(), Some(want), "{spelling:?}");
}
}
#[test]
fn terminal_codec_is_none_for_byte_stream_chains() {
let d = dict_with(vec![(b"Filter", name(b"FlateDecode"))]);
assert_eq!(terminal_codec(&d).unwrap(), None);
assert_eq!(terminal_codec(&Dict::new()).unwrap(), None);
}
#[test]
fn terminal_codec_sees_through_an_ascii_prefix() {
let d = dict_with(vec![(
b"Filter",
Object::Array(vec![name(b"ASCII85Decode"), name(b"DCTDecode")]),
)]);
assert_eq!(terminal_codec(&d).unwrap(), Some(Codec::Dct));
}
#[test]
fn inline_rules_match_the_spec() {
assert!(Codec::Dct.allowed_inline());
assert!(Codec::Ccitt.allowed_inline());
assert!(!Codec::Jbig2.allowed_inline());
assert!(!Codec::Jpx.allowed_inline());
assert!(!Codec::Jxl.allowed_inline());
}
fn empty_document() -> Document {
let mut buf = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (num, body) in [
(1u32, "<< /Type /Catalog /Pages 2 0 R >>"),
(2, "<< /Type /Pages /Kids [] /Count 0 >>"),
] {
offsets.push(buf.len());
buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
}
let xref_at = buf.len();
buf.extend_from_slice(b"xref\n0 3\n0000000000 65535 f\r\n");
for off in offsets {
buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
}
buf.extend_from_slice(
format!("trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
);
Document::from_bytes(buf).unwrap()
}
fn dct_dict(width: i64, height: i64) -> Dict {
dict_with(vec![
(b"Filter", name(b"DCTDecode")),
(b"Width", Object::Integer(width)),
(b"Height", Object::Integer(height)),
(b"BitsPerComponent", Object::Integer(8)),
])
}
fn decode_fixture(bytes: &[u8], dict: &Dict) -> Result<CodedImage, ImageCodecError> {
decode_image(&empty_document(), dict, bytes, false)
}
#[test]
fn grayscale_jpeg_decodes_to_one_component_per_pixel() {
let img = decode_fixture(fixtures::GRAY_2X2, &dct_dict(2, 2)).unwrap();
assert_eq!(img.codec, Some(Codec::Dct));
assert_eq!((img.width, img.height), (2, 2));
assert_eq!(img.components, 1);
assert_eq!(img.bits_per_component, 8);
assert_eq!(img.color_model, CodecColorModel::Gray);
assert_eq!(img.samples.len(), 4, "2x2 x 1 component");
assert!(img.samples[0] < 20, "{:?}", img.samples);
assert!(img.samples[3] > 235, "{:?}", img.samples);
assert!(img.samples[0] < img.samples[1]);
assert!(img.samples[1] < img.samples[2]);
assert!(!img.notes.cmyk_image);
assert!(!img.notes.geometry_mismatch);
}
#[test]
fn grayscale_ignores_color_transform_per_table_13() {
let mut dict = dct_dict(2, 2);
dict.insert(
Name::from(b"DecodeParms"),
Object::Dict(dict_with(vec![(b"ColorTransform", Object::Integer(1))])),
);
let with_parm = decode_fixture(fixtures::GRAY_2X2, &dict).unwrap();
let without = decode_fixture(fixtures::GRAY_2X2, &dct_dict(2, 2)).unwrap();
assert_eq!(with_parm.samples, without.samples);
assert_eq!(with_parm.color_model, CodecColorModel::Gray);
}
fn assert_rgb_primaries(samples: &[u8]) {
assert_eq!(samples.len(), 12, "2x2 x 3 components");
let px = |i: usize| (samples[i * 3], samples[i * 3 + 1], samples[i * 3 + 2]);
let (r, g, b) = px(0);
assert!(
r > 200 && g < 60 && b < 60,
"pixel 0 should be red: {r},{g},{b}"
);
let (r, g, b) = px(1);
assert!(
r < 60 && g > 200 && b < 60,
"pixel 1 should be green: {r},{g},{b}"
);
let (r, g, b) = px(2);
assert!(
r < 60 && g < 60 && b > 200,
"pixel 2 should be blue: {r},{g},{b}"
);
let (r, g, b) = px(3);
assert!(
r > 200 && g > 200 && b > 200,
"pixel 3 should be white: {r},{g},{b}"
);
}
#[test]
fn rgb_jpeg_with_no_marker_takes_table_13s_default_transform_of_one() {
let img = decode_fixture(fixtures::RGB_2X2, &dct_dict(2, 2)).unwrap();
assert_eq!(img.components, 3);
assert_eq!(img.color_model, CodecColorModel::Rgb);
assert_rgb_primaries(&img.samples);
}
#[test]
fn progressive_jpeg_decodes_identically_to_baseline() {
let img = decode_fixture(fixtures::RGB_2X2_PROGRESSIVE, &dct_dict(2, 2)).unwrap();
assert_eq!(img.color_model, CodecColorModel::Rgb);
assert_rgb_primaries(&img.samples);
}
#[test]
fn app14_transform_one_reaches_the_same_result_as_the_default() {
let img = decode_fixture(fixtures::RGB_2X2_APP14_T1, &dct_dict(2, 2)).unwrap();
assert_eq!(img.color_model, CodecColorModel::Rgb);
assert_rgb_primaries(&img.samples);
}
#[test]
fn app14_transform_zero_delivers_untransformed_components() {
let raw = decode_fixture(fixtures::RGB_2X2_APP14_T0, &dct_dict(2, 2)).unwrap();
let transformed = decode_fixture(fixtures::RGB_2X2, &dct_dict(2, 2)).unwrap();
assert_eq!(raw.color_model, CodecColorModel::Untransformed3);
assert_eq!(raw.components, 3);
assert_eq!(raw.samples.len(), 12);
assert_ne!(
raw.samples, transformed.samples,
"ColorTransform 0 must NOT apply the YCbCr->RGB inverse"
);
}
#[test]
fn the_marker_outranks_the_dictionary() {
let mut dict = dct_dict(2, 2);
dict.insert(
Name::from(b"DecodeParms"),
Object::Dict(dict_with(vec![(b"ColorTransform", Object::Integer(1))])),
);
let img = decode_fixture(fixtures::RGB_2X2_APP14_T0, &dict).unwrap();
assert_eq!(
img.color_model,
CodecColorModel::Untransformed3,
"the APP14 marker wins"
);
}
#[test]
fn the_dictionary_wins_when_there_is_no_marker() {
let mut dict = dct_dict(2, 2);
dict.insert(
Name::from(b"DecodeParms"),
Object::Dict(dict_with(vec![(b"ColorTransform", Object::Integer(0))])),
);
let img = decode_fixture(fixtures::RGB_2X2, &dict).unwrap();
assert_eq!(img.color_model, CodecColorModel::Untransformed3);
let default = decode_fixture(fixtures::RGB_2X2, &dct_dict(2, 2)).unwrap();
assert_ne!(img.samples, default.samples);
}
#[test]
fn unknown_adobe_transform_is_a_named_diagnostic_not_a_vendor_error() {
assert_eq!(
decode_fixture(fixtures::RGB_2X2_APP14_T3, &dct_dict(2, 2)).unwrap_err(),
ImageCodecError::FeatureUnsupported {
feature: "DCT/adobe-transform-3"
}
);
}
#[test]
fn cmyk_jpeg_passes_four_raw_components_through_and_is_counted() {
let img = decode_fixture(fixtures::CMYK_2X2, &dct_dict(2, 2)).unwrap();
assert_eq!(img.components, 4);
assert_eq!(img.color_model, CodecColorModel::Cmyk);
assert_eq!(img.samples.len(), 16, "2x2 x 4 components");
assert!(
img.notes.cmyk_polarity_unverifiable,
"transform 0 + no /Decode is the R30 shape and must announce itself (decision 006)"
);
assert!(
!img.notes.cmyk_image,
"the benign census counts YCCK (transform 1/2) only (decision 006 §4.4)"
);
let first = &img.samples[0..4];
assert!(
first.iter().any(|&v| v > 200),
"raw stored samples, not inverted: {first:?}"
);
}
#[test]
fn cmyk_jpeg_with_a_decode_array_is_not_polarity_unverifiable() {
let mut dict = dct_dict(2, 2);
dict.insert(
Name::from(b"Decode"),
Object::Array(vec![
Object::Integer(1),
Object::Integer(0),
Object::Integer(1),
Object::Integer(0),
Object::Integer(1),
Object::Integer(0),
Object::Integer(1),
Object::Integer(0),
]),
);
let img = decode_fixture(fixtures::CMYK_2X2, &dict).unwrap();
assert!(!img.notes.cmyk_polarity_unverifiable);
assert!(!img.notes.cmyk_image);
let plain = decode_fixture(fixtures::CMYK_2X2, &dct_dict(2, 2)).unwrap();
assert_eq!(
img.samples, plain.samples,
"/Decode is observed for classification, never applied here"
);
}
#[test]
fn geometry_disagreement_is_counted_and_the_codestream_is_reported() {
let img = decode_fixture(fixtures::RGB_2X2, &dct_dict(7, 9)).unwrap();
assert_eq!((img.width, img.height), (2, 2));
assert!(img.notes.geometry_mismatch);
}
#[test]
fn a_wrong_bits_per_component_is_a_geometry_disagreement() {
let mut dict = dct_dict(2, 2);
dict.insert(Name::from(b"BitsPerComponent"), Object::Integer(4));
let img = decode_fixture(fixtures::RGB_2X2, &dict).unwrap();
assert_eq!(img.bits_per_component, 8);
assert!(img.notes.geometry_mismatch);
}
#[test]
fn a_codestream_past_max_image_pixels_is_refused_before_allocating() {
assert_eq!(
decode_fixture(fixtures::RGB_HUGE_DIMS, &dct_dict(65535, 65535)).unwrap_err(),
ImageCodecError::TooLarge
);
}
#[test]
fn corrupt_codestream_errs_never_returns_plausible_samples() {
let mut truncated = fixtures::RGB_2X2.to_vec();
truncated.truncate(truncated.len() / 2);
assert!(matches!(
decode_fixture(&truncated, &dct_dict(2, 2)),
Err(ImageCodecError::Corrupt { .. })
));
assert!(matches!(
decode_fixture(b"not a jpeg", &dct_dict(2, 2)),
Err(ImageCodecError::Corrupt { .. })
));
}
#[test]
fn an_ascii85_prefix_is_run_before_the_codec() {
let armoured = ascii85(fixtures::RGB_2X2);
let mut dict = dct_dict(2, 2);
dict.insert(
Name::from(b"Filter"),
Object::Array(vec![name(b"ASCII85Decode"), name(b"DCTDecode")]),
);
let img = decode_fixture(armoured.as_bytes(), &dict).unwrap();
assert_eq!(img.codec, Some(Codec::Dct));
assert_rgb_primaries(&img.samples);
}
fn ascii85(data: &[u8]) -> String {
let mut out = String::new();
for chunk in data.chunks(4) {
let mut word = [0u8; 4];
word[..chunk.len()].copy_from_slice(chunk);
let mut value = u32::from_be_bytes(word);
let mut group = [0u8; 5];
for slot in group.iter_mut().rev() {
*slot = b'!' + (value % 85) as u8;
value /= 85;
}
out.extend(group[..chunk.len() + 1].iter().map(|&b| b as char));
}
out.push_str("~>");
out
}
#[test]
fn a_chain_with_no_codec_yields_an_unspecified_coded_image() {
let dict = dict_with(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
(b"BitsPerComponent", Object::Integer(8)),
]);
let img = decode_fixture(b"rawsamples", &dict).unwrap();
assert_eq!(img.codec, None);
assert_eq!(img.color_model, CodecColorModel::Unspecified);
assert_eq!((img.width, img.height), (4, 2));
assert_eq!(img.components, 0, "no codec declared a component count");
assert_eq!(img.samples, b"rawsamples");
}
#[test]
fn every_recognized_codec_is_now_implemented() {
for filter in [
&b"DCTDecode"[..],
b"CCITTFaxDecode",
b"JBIG2Decode",
b"JPXDecode",
] {
let dict = dict_with(vec![
(b"Filter", name(filter)),
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
]);
let err = decode_fixture(b"not a codestream", &dict).unwrap_err();
assert!(
!matches!(err, ImageCodecError::Unsupported { .. }),
"{}: still reports the codec as unimplemented ({err})",
String::from_utf8_lossy(filter),
);
}
}
#[cfg(feature = "jpx")]
fn jpx_dict(entries: Vec<(&[u8], Object)>) -> Dict {
let mut all: Vec<(&[u8], Object)> = vec![(b"Filter", name(b"JPXDecode"))];
all.extend(entries);
dict_with(all)
}
#[cfg(feature = "jpx")]
fn jpx_gray_dict() -> Dict {
jpx_dict(vec![
(b"Width", Object::Integer(16)),
(b"Height", Object::Integer(4)),
])
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_decodes_a_jp2_container_to_the_expected_samples() {
let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &jpx_gray_dict()).unwrap();
assert_eq!(img.codec, Some(Codec::Jpx));
assert_eq!((img.width, img.height), (16, 4));
assert_eq!(img.components, 1);
assert_eq!(img.color_model, CodecColorModel::Gray);
assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_8_SAMPLES);
assert!(!img.notes.geometry_mismatch);
assert_eq!(img.embedded_alpha, None);
assert_eq!(img.icc_profile, None);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_decodes_a_raw_codestream_identically_to_its_jp2_container() {
let boxed = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &jpx_gray_dict()).unwrap();
let bare = decode_fixture(fixtures_jpx::JPX_GRAY_8_J2K, &jpx_gray_dict()).unwrap();
assert_eq!(bare.samples, fixtures_jpx::JPX_GRAY_8_SAMPLES);
assert_eq!(bare.samples, boxed.samples);
assert_eq!((bare.width, bare.height), (boxed.width, boxed.height));
assert_eq!(bare.color_model, boxed.color_model);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_interleaves_rgb_components_in_order() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
]);
let img = decode_fixture(fixtures_jpx::JPX_RGB_8_JP2, &dict).unwrap();
assert_eq!(img.components, 3);
assert_eq!(img.color_model, CodecColorModel::Rgb);
assert_eq!(img.samples, fixtures_jpx::JPX_RGB_8_SAMPLES);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_reports_cmyk_from_enumerated_colour_space_twelve() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
]);
let img = decode_fixture(fixtures_jpx::JPX_CMYK_8_JP2, &dict).unwrap();
assert_eq!(img.components, 4);
assert_eq!(img.color_model, CodecColorModel::Cmyk);
assert_eq!(img.samples, fixtures_jpx::JPX_CMYK_8_SAMPLES);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_absent_colour_space_is_conformant_and_the_codestream_supplies_it() {
let dict = jpx_gray_dict();
assert!(dict.get(b"ColorSpace").is_none());
assert!(dict.get(b"BitsPerComponent").is_none());
let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &dict).unwrap();
assert_eq!(img.color_model, CodecColorModel::Gray);
assert_eq!(img.bits_per_component, 8);
assert!(
!img.notes.geometry_mismatch,
"absent optional entries are not a disagreement"
);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_bits_per_component_is_ignored_and_a_stated_value_is_counted() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
(b"BitsPerComponent", Object::Integer(16)),
]);
let img = decode_fixture(fixtures_jpx::JPX_GRAY_16_JP2, &dict).unwrap();
assert_eq!(img.bits_per_component, 8);
assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_16_SAMPLES);
assert!(img.notes.geometry_mismatch);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_scales_high_bit_depths_full_range_not_by_high_byte() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
]);
let img = decode_fixture(fixtures_jpx::JPX_GRAY_16_JP2, &dict).unwrap();
assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_16_SAMPLES);
assert_eq!(img.samples.first().copied(), Some(0x00), "0 stays 0");
assert_eq!(
img.samples.get(1).copied(),
Some(0xFF),
"the white point 2^16-1 must land on exactly 255"
);
assert_eq!(
img.samples.get(4).copied(),
Some(0x01),
"0x00FF must scale to 1, not truncate to 0"
);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_dictionary_geometry_disagreement_is_counted_and_the_codestream_reported() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(999)),
(b"Height", Object::Integer(7)),
]);
let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &dict).unwrap();
assert_eq!((img.width, img.height), (16, 4));
assert!(img.notes.geometry_mismatch);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_colour_space_channel_count_disagreement_is_counted() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(16)),
(b"Height", Object::Integer(4)),
(b"ColorSpace", name(b"DeviceRGB")),
]);
let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &dict).unwrap();
assert_eq!(img.components, 1);
assert_eq!(img.color_model, CodecColorModel::Gray);
assert!(img.notes.geometry_mismatch);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_matching_colour_space_is_not_a_disagreement() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
(b"ColorSpace", name(b"DeviceRGB")),
]);
let img = decode_fixture(fixtures_jpx::JPX_RGB_8_JP2, &dict).unwrap();
assert!(!img.notes.geometry_mismatch);
assert_eq!(img.samples, fixtures_jpx::JPX_RGB_8_SAMPLES);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_smask_in_data_defaults_to_ignoring_the_opacity_channel() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
]);
let img = decode_fixture(fixtures_jpx::JPX_RGBA_8_JP2, &dict).unwrap();
assert_eq!(img.components, 3);
assert_eq!(img.embedded_alpha, None, "/SMaskInData 0 means ignore");
assert_eq!(
img.samples,
fixtures_jpx::JPX_RGBA_8_SAMPLES,
"the opacity channel must not stay interleaved with the colours"
);
assert!(!img.notes.jpx_smask_in_data_preblended);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_smask_in_data_one_exposes_the_opacity_channel() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
(b"SMaskInData", Object::Integer(1)),
]);
let img = decode_fixture(fixtures_jpx::JPX_RGBA_8_JP2, &dict).unwrap();
assert_eq!(img.components, 3);
assert_eq!(img.samples, fixtures_jpx::JPX_RGBA_8_SAMPLES);
assert_eq!(
img.embedded_alpha.as_deref(),
Some(fixtures_jpx::JPX_RGBA_8_ALPHA)
);
assert!(!img.notes.jpx_smask_in_data_preblended);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_smask_in_data_two_is_deferred_by_name_and_never_applied() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
(b"SMaskInData", Object::Integer(2)),
]);
let img = decode_fixture(fixtures_jpx::JPX_RGBA_8_JP2, &dict).unwrap();
assert!(img.notes.jpx_smask_in_data_preblended);
assert_eq!(img.embedded_alpha, None);
assert_eq!(img.samples, fixtures_jpx::JPX_RGBA_8_SAMPLES);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_smask_in_data_out_of_range_falls_back_to_the_default() {
for value in [-1, 3, 99] {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
(b"SMaskInData", Object::Integer(value)),
]);
let img = decode_fixture(fixtures_jpx::JPX_RGBA_8_JP2, &dict).unwrap();
assert_eq!(img.embedded_alpha, None, "SMaskInData {value}");
assert!(
!img.notes.jpx_smask_in_data_preblended,
"SMaskInData {value}"
);
}
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_smask_in_data_without_an_opacity_channel_is_a_disagreement() {
let dict = jpx_dict(vec![
(b"Width", Object::Integer(16)),
(b"Height", Object::Integer(4)),
(b"SMaskInData", Object::Integer(1)),
]);
let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &dict).unwrap();
assert_eq!(img.embedded_alpha, None);
assert!(img.notes.geometry_mismatch);
assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_8_SAMPLES);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_ignores_the_decode_array_entirely_at_this_layer() {
let plain = jpx_dict(vec![
(b"Width", Object::Integer(16)),
(b"Height", Object::Integer(4)),
]);
let inverted = jpx_dict(vec![
(b"Width", Object::Integer(16)),
(b"Height", Object::Integer(4)),
(
b"Decode",
Object::Array(vec![Object::Integer(1), Object::Integer(0)]),
),
]);
let a = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &plain).unwrap();
let b = decode_fixture(fixtures_jpx::JPX_GRAY_8_JP2, &inverted).unwrap();
assert_eq!(a.samples, b.samples);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_corrupt_data_errs_and_never_returns_plausible_samples() {
let mut truncated = fixtures_jpx::JPX_GRAY_8_JP2.to_vec();
truncated.truncate(truncated.len() / 2);
for data in [&b"not a codestream at all"[..], &truncated, &[]] {
let err = decode_fixture(data, &jpx_gray_dict()).unwrap_err();
assert!(
matches!(
err,
ImageCodecError::Corrupt {
codec: Codec::Jpx,
..
} | ImageCodecError::FeatureUnsupported { .. }
),
"unexpected error for {} bytes: {err}",
data.len()
);
}
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_refuses_an_absurd_tile_grid_that_no_pixel_ceiling_can_see() {
let mut shredded = fixtures_jpx::JPX_GRAY_8_J2K.to_vec();
for (offset, value) in [(8usize, 512u32), (12, 1024), (24, 4), (28, 2)] {
let Some(slot) = shredded.get_mut(offset..offset + 4) else {
panic!("fixture is shorter than a SIZ marker segment");
};
slot.copy_from_slice(&value.to_be_bytes());
}
assert_eq!(
decode_fixture(&shredded, &jpx_gray_dict()).unwrap_err(),
ImageCodecError::TooLarge,
"a 65,536-tile grid must be refused before any tile is built"
);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_accepts_a_tile_grid_within_the_ceiling() {
let img = decode_fixture(fixtures_jpx::JPX_GRAY_8_J2K, &jpx_gray_dict()).unwrap();
assert_eq!(img.samples, fixtures_jpx::JPX_GRAY_8_SAMPLES);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_unsupported_enumerated_colour_space_is_a_named_diagnostic() {
let mut ciejab = fixtures_jpx::JPX_RGB_8_JP2.to_vec();
let tag = ciejab
.windows(4)
.position(|w| w == b"colr")
.expect("the fixture must carry a colr box");
let at = tag + 4 + 3;
let Some(slot) = ciejab.get_mut(at..at + 4) else {
panic!("colr box is truncated");
};
assert_eq!(slot, &16u32.to_be_bytes(), "fixture should start as sRGB");
slot.copy_from_slice(&19u32.to_be_bytes());
let dict = jpx_dict(vec![
(b"Width", Object::Integer(4)),
(b"Height", Object::Integer(2)),
]);
assert_eq!(
decode_fixture(&ciejab, &dict).unwrap_err(),
ImageCodecError::FeatureUnsupported {
feature: "JPX/enumerated-colour-space",
}
);
}
#[cfg(feature = "jpx")]
#[test]
fn jpx_refuses_a_geometry_past_the_pdfcer_ceiling_before_decoding() {
let mut huge = fixtures_jpx::JPX_GRAY_8_J2K.to_vec();
for offset in [8usize, 12, 24, 28] {
let Some(slot) = huge.get_mut(offset..offset + 4) else {
panic!("fixture is shorter than a SIZ marker segment");
};
slot.copy_from_slice(&60_000u32.to_be_bytes());
}
let err = decode_fixture(&huge, &jpx_gray_dict()).unwrap_err();
assert_eq!(
err,
ImageCodecError::TooLarge,
"a 3.6 Gpx codestream must be refused before allocating"
);
}
fn ccitt_dict(parms: Vec<(&[u8], Object)>) -> Dict {
dict_with(vec![
(b"Filter", name(b"CCITTFaxDecode")),
(b"Width", Object::Integer(16)),
(b"Height", Object::Integer(4)),
(b"BitsPerComponent", Object::Integer(1)),
(b"DecodeParms", Object::Dict(dict_with(parms))),
])
}
fn ccitt_variants() -> [(&'static str, i64, &'static [u8]); 3] {
[
("Group 4 (K < 0)", -1, fixtures_bilevel::CCITT_G4_16X4),
("Group 3 1-D (K = 0)", 0, fixtures_bilevel::CCITT_G3_1D_16X4),
("Group 3 2-D (K > 0)", 4, fixtures_bilevel::CCITT_G3_2D_16X4),
]
}
#[test]
fn every_k_variant_decodes_to_the_same_picture() {
for (label, k, data) in ccitt_variants() {
let dict = ccitt_dict(vec![
(b"K", Object::Integer(k)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
]);
let img = decode_fixture(data, &dict).unwrap();
assert_eq!(img.codec, Some(Codec::Ccitt), "{label}");
assert_eq!((img.width, img.height), (16, 4), "{label}");
assert_eq!(img.components, 1, "{label}");
assert_eq!(img.bits_per_component, 1, "{label}");
assert_eq!(img.color_model, CodecColorModel::Bilevel, "{label}");
assert_eq!(
img.samples,
fixtures_bilevel::BILEVEL_16X4_SAMPLES,
"{label}: samples must be PDF convention, 0 = black"
);
assert!(!img.notes.geometry_mismatch, "{label}");
}
}
#[test]
fn ccitt_black_is_1_inverts_every_sample() {
for (label, k, data) in ccitt_variants() {
let dict = ccitt_dict(vec![
(b"K", Object::Integer(k)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
(b"BlackIs1", Object::Boolean(true)),
]);
let img = decode_fixture(data, &dict).unwrap();
assert_eq!(
img.samples,
fixtures_bilevel::BILEVEL_16X4_INK,
"{label}: BlackIs1 true must emit 1 for black"
);
let complement: Vec<u8> = fixtures_bilevel::BILEVEL_16X4_SAMPLES
.iter()
.map(|b| !b)
.collect();
assert_eq!(img.samples, complement, "{label}");
}
}
#[test]
fn ccitt_black_is_1_false_is_the_same_as_absent() {
let with = ccitt_dict(vec![
(b"K", Object::Integer(-1)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
(b"BlackIs1", Object::Boolean(false)),
]);
let without = ccitt_dict(vec![
(b"K", Object::Integer(-1)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
]);
let a = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &with).unwrap();
let b = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &without).unwrap();
assert_eq!(a.samples, b.samples);
}
#[test]
fn ccitt_positive_k_values_are_indistinguishable() {
let decode_with_k = |k: i64| {
let dict = ccitt_dict(vec![
(b"K", Object::Integer(k)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
]);
decode_fixture(fixtures_bilevel::CCITT_G3_2D_16X4, &dict)
.unwrap()
.samples
};
assert_eq!(decode_with_k(1), decode_with_k(4));
assert_eq!(decode_with_k(4), decode_with_k(40));
assert_eq!(decode_with_k(4), fixtures_bilevel::BILEVEL_16X4_SAMPLES);
}
#[test]
fn ccitt_rows_zero_falls_back_to_the_dictionary_height() {
for parms in [
vec![
(&b"K"[..], Object::Integer(-1)),
(b"Columns", Object::Integer(16)),
],
vec![
(&b"K"[..], Object::Integer(-1)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(0)),
],
] {
let img = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &ccitt_dict(parms)).unwrap();
assert_eq!(img.height, 4, "the /Height fallback must supply the bound");
assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
}
}
#[test]
fn ccitt_end_of_line_is_advisory_not_a_gate() {
let decode_with = |eol: Option<bool>| {
let mut parms = vec![
(&b"K"[..], Object::Integer(0)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
];
if let Some(v) = eol {
parms.push((b"EndOfLine", Object::Boolean(v)));
}
decode_fixture(fixtures_bilevel::CCITT_G3_1D_16X4, &ccitt_dict(parms))
.unwrap()
.samples
};
assert_eq!(decode_with(None), fixtures_bilevel::BILEVEL_16X4_SAMPLES);
assert_eq!(decode_with(Some(true)), decode_with(None));
assert_eq!(decode_with(Some(false)), decode_with(None));
}
#[test]
fn ccitt_columns_defaults_to_1728_and_the_default_is_load_bearing() {
let dict = dict_with(vec![
(b"Filter", name(b"CCITTFaxDecode")),
(b"Width", Object::Integer(16)),
(b"Height", Object::Integer(4)),
(b"DecodeParms", Object::Dict(dict_with(vec![]))),
]);
assert!(matches!(
decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &dict),
Err(ImageCodecError::Corrupt { .. })
));
}
#[test]
fn ccitt_geometry_disagreement_is_counted() {
let mut dict = ccitt_dict(vec![
(b"K", Object::Integer(-1)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
]);
dict.insert(Name::from(b"Width"), Object::Integer(24));
let img = decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &dict).unwrap();
assert_eq!(img.width, 16, "the filter's /Columns governs the samples");
assert!(img.notes.geometry_mismatch);
}
#[test]
fn ccitt_refuses_a_geometry_past_the_pdfcer_ceiling() {
let dict = ccitt_dict(vec![
(b"K", Object::Integer(-1)),
(b"Columns", Object::Integer(65535)),
(b"Rows", Object::Integer(65535)),
]);
assert_eq!(
decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &dict).unwrap_err(),
ImageCodecError::TooLarge
);
let wide = ccitt_dict(vec![
(b"K", Object::Integer(-1)),
(b"Columns", Object::Integer(70000)),
(b"Rows", Object::Integer(1)),
]);
assert_eq!(
decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &wide).unwrap_err(),
ImageCodecError::TooLarge
);
}
#[test]
fn ccitt_nonsensical_columns_is_refused_not_defaulted() {
for bad in [Object::Integer(0), Object::Integer(-16)] {
let dict = ccitt_dict(vec![(b"K", Object::Integer(-1)), (b"Columns", bad)]);
assert!(matches!(
decode_fixture(fixtures_bilevel::CCITT_G4_16X4, &dict),
Err(ImageCodecError::Corrupt { .. })
));
}
}
#[test]
fn ccitt_corrupt_data_errs_and_never_returns_a_short_page() {
let dict = ccitt_dict(vec![
(b"K", Object::Integer(-1)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
]);
let mut truncated = fixtures_bilevel::CCITT_G4_16X4.to_vec();
truncated.truncate(3);
assert!(matches!(
decode_fixture(&truncated, &dict),
Err(ImageCodecError::Corrupt { .. })
));
assert!(matches!(
decode_fixture(&[0x00; 32], &dict),
Err(ImageCodecError::Corrupt { .. })
));
let _ = decode_fixture(&[0xFF; 32], &dict);
}
#[test]
fn ccf_is_a_legal_inline_abbreviation() {
let doc = empty_document();
let mut dict = ccitt_dict(vec![
(b"K", Object::Integer(-1)),
(b"Columns", Object::Integer(16)),
(b"Rows", Object::Integer(4)),
]);
dict.insert(Name::from(b"Filter"), name(b"CCF"));
let img = decode_image(&doc, &dict, fixtures_bilevel::CCITT_G4_16X4, true).unwrap();
assert_eq!(img.codec, Some(Codec::Ccitt));
assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
}
fn jbig2_dict(parms: Vec<(&[u8], Object)>) -> Dict {
dict_with(vec![
(b"Filter", name(b"JBIG2Decode")),
(b"Width", Object::Integer(16)),
(b"Height", Object::Integer(4)),
(b"BitsPerComponent", Object::Integer(1)),
(b"DecodeParms", Object::Dict(dict_with(parms))),
])
}
fn document_with_globals(globals: &[u8]) -> Document {
let mut buf = b"%PDF-1.7\n".to_vec();
let mut offsets = Vec::new();
for (num, body) in [
(1u32, "<< /Type /Catalog /Pages 2 0 R >>".to_owned()),
(2, "<< /Type /Pages /Kids [] /Count 0 >>".to_owned()),
] {
offsets.push(buf.len());
buf.extend_from_slice(format!("{num} 0 obj\n{body}\nendobj\n").as_bytes());
}
offsets.push(buf.len());
buf.extend_from_slice(
format!("3 0 obj\n<< /Length {} >>\nstream\n", globals.len()).as_bytes(),
);
buf.extend_from_slice(globals);
buf.extend_from_slice(b"\nendstream\nendobj\n");
let xref_at = buf.len();
buf.extend_from_slice(b"xref\n0 4\n0000000000 65535 f\r\n");
for off in offsets {
buf.extend_from_slice(format!("{off:010} 00000 n\r\n").as_bytes());
}
buf.extend_from_slice(
format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref_at}\n%%EOF\n").as_bytes(),
);
Document::from_bytes(buf).unwrap()
}
#[test]
fn jbig2_decodes_to_the_same_samples_as_ccitt() {
let dict = jbig2_dict(vec![]);
let img = decode_fixture(fixtures_bilevel::JBIG2_MMR_16X4, &dict).unwrap();
assert_eq!(img.codec, Some(Codec::Jbig2));
assert_eq!((img.width, img.height), (16, 4));
assert_eq!(img.components, 1);
assert_eq!(img.bits_per_component, 1);
assert_eq!(img.color_model, CodecColorModel::Bilevel);
assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
assert!(!img.notes.geometry_mismatch);
}
#[test]
fn jbig2_globals_are_resolved_through_the_document() {
let doc = document_with_globals(fixtures_bilevel::JBIG2_MMR_16X4_GLOBALS);
let dict = jbig2_dict(vec![(
b"JBIG2Globals",
Object::Reference(pdfcer_model::object::ObjId::new(3, 0)),
)]);
let img = decode_image(&doc, &dict, fixtures_bilevel::JBIG2_MMR_16X4_PAGE, false).unwrap();
assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
}
#[test]
fn jbig2_without_its_globals_fails_cleanly() {
let dict = jbig2_dict(vec![]);
assert!(matches!(
decode_fixture(fixtures_bilevel::JBIG2_MMR_16X4_PAGE, &dict),
Err(ImageCodecError::Corrupt { .. })
));
}
#[test]
fn jbig2_globals_that_are_not_a_stream_are_treated_as_absent() {
let dict = jbig2_dict(vec![(b"JBIG2Globals", Object::Integer(7))]);
let img = decode_fixture(fixtures_bilevel::JBIG2_MMR_16X4, &dict).unwrap();
assert_eq!(img.samples, fixtures_bilevel::BILEVEL_16X4_SAMPLES);
}
#[test]
fn jbig2_geometry_comes_from_the_page_information_segment() {
let mut dict = jbig2_dict(vec![]);
dict.insert(Name::from(b"Height"), Object::Integer(9));
let img = decode_fixture(fixtures_bilevel::JBIG2_MMR_16X4, &dict).unwrap();
assert_eq!(img.height, 4, "the page information segment governs");
assert!(img.notes.geometry_mismatch);
}
#[test]
fn jbig2_page_association_other_than_1_still_decodes() {
let dict = jbig2_dict(vec![]);
for page in [0u8, 2, 7] {
let mut data = fixtures_bilevel::JBIG2_MMR_16X4.to_vec();
assert_eq!((data[6], data[36]), (1, 1));
data[6] = page;
data[36] = page;
let img = decode_fixture(&data, &dict).unwrap();
assert_eq!(
img.samples,
fixtures_bilevel::BILEVEL_16X4_SAMPLES,
"page {page}"
);
}
}
fn jbig2_file(flags: u8) -> Vec<u8> {
let seg = fixtures_bilevel::JBIG2_MMR_16X4;
let mut out = vec![0x97, 0x4A, 0x42, 0x32, 0x0D, 0x0A, 0x1A, 0x0A, flags];
if flags & 0x02 == 0 {
out.extend_from_slice(&1u32.to_be_bytes());
}
if flags & 0x01 != 0 {
out.extend_from_slice(seg);
} else {
for range in [0..11, 30..41] {
out.extend_from_slice(&seg[range]);
}
out.extend_from_slice(&[0, 0, 0, 2, 0x33, 0x00, 0x01, 0, 0, 0, 0]);
for range in [11..30, 41..80] {
out.extend_from_slice(&seg[range]);
}
}
out
}
#[test]
fn jbig2_with_a_file_header_decodes_in_either_organisation() {
let dict = jbig2_dict(vec![]);
for flags in [0x01, 0x03, 0x00, 0x02] {
let img = decode_fixture(&jbig2_file(flags), &dict).unwrap();
assert_eq!(
img.samples,
fixtures_bilevel::BILEVEL_16X4_SAMPLES,
"flags {flags:#04x}"
);
}
}
#[test]
fn jbig2_file_header_with_globals_is_refused() {
let doc = document_with_globals(fixtures_bilevel::JBIG2_MMR_16X4_GLOBALS);
let dict = jbig2_dict(vec![(
b"JBIG2Globals",
Object::Reference(pdfcer_model::object::ObjId::new(3, 0)),
)]);
let err = decode_image(&doc, &dict, &jbig2_file(0x01), false).unwrap_err();
assert!(
matches!(&err, ImageCodecError::Corrupt { detail, .. } if detail.contains("file header")),
"{err:?}"
);
}
#[test]
fn jbig2_corrupt_segments_err() {
let dict = jbig2_dict(vec![]);
for bad in [&b""[..], b"not jbig2 at all", &[0xFF; 40]] {
assert!(
matches!(
decode_fixture(bad, &dict),
Err(ImageCodecError::Corrupt { .. })
),
"{bad:?}"
);
}
let mut truncated = fixtures_bilevel::JBIG2_MMR_16X4.to_vec();
truncated.truncate(truncated.len() - 4);
assert!(matches!(
decode_fixture(&truncated, &dict),
Err(ImageCodecError::Corrupt { .. })
));
}
#[test]
fn inline_images_reject_jbig2_and_jpx_but_allow_dct() {
let doc = empty_document();
for (spelling, codec) in [
(&b"JBIG2Decode"[..], Codec::Jbig2),
(b"JPXDecode", Codec::Jpx),
(b"JXLDecode", Codec::Jxl),
] {
let dict = dict_with(vec![(b"Filter", name(spelling))]);
assert_eq!(
decode_image(&doc, &dict, b"anything", true).unwrap_err(),
ImageCodecError::NotAllowedInline { codec }
);
}
let mut inline = dct_dict(2, 2);
inline.insert(Name::from(b"Filter"), name(b"DCT"));
let img = decode_image(&doc, &inline, fixtures::RGB_2X2, true).unwrap();
assert_eq!(img.codec, Some(Codec::Dct));
}
#[test]
fn a_codec_that_is_not_the_last_filter_is_refused() {
let dict = dict_with(vec![(
b"Filter",
Object::Array(vec![name(b"DCTDecode"), name(b"FlateDecode")]),
)]);
assert_eq!(
decode_fixture(fixtures::RGB_2X2, &dict).unwrap_err(),
ImageCodecError::CodecNotTerminal
);
}
#[test]
fn lzw_framing_anomalies_survive_into_the_codec_notes() {
let dict = dict_with(vec![
(b"Filter", name(b"LZWDecode")),
(b"Width", Object::Integer(1)),
(b"Height", Object::Integer(1)),
]);
let img = decode_fixture(&[0x20, 0xC0, 0x40], &dict).unwrap();
assert_eq!(img.samples, b"A");
assert_eq!(img.notes.lzw_framing_anomalies, 1);
}
#[test]
fn codec_parms_follows_table_5_positions() {
let parms = dict_with(vec![(b"ColorTransform", Object::Integer(0))]);
let single = dict_with(vec![
(b"Filter", name(b"DCTDecode")),
(b"DecodeParms", Object::Dict(parms.clone())),
]);
assert!(codec_parms(&single, 1).is_some());
let chained = dict_with(vec![
(
b"Filter",
Object::Array(vec![name(b"ASCII85Decode"), name(b"DCTDecode")]),
),
(
b"DecodeParms",
Object::Array(vec![Object::Null, Object::Dict(parms)]),
),
]);
assert!(codec_parms(&chained, 2).is_some());
assert!(codec_parms(&chained, 1).is_none());
}
#[cfg(feature = "jpx")]
fn palette_entry(i: u8) -> [u8; 3] {
[i, 255 - i, 13]
}
#[cfg(feature = "jpx")]
#[test]
fn a_jp2_palette_is_left_to_the_codec_when_the_pdf_offers_no_indexed_space() {
let jp2 = fixtures_jpx::jpx_gray_8_jp2_with_palette();
let img = decode_fixture(&jp2, &jpx_gray_dict()).unwrap();
assert!(
!img.notes.jpx_palette_left_to_pdf,
"with no /Indexed space in the dictionary, the codec keeps the palette"
);
assert!(!img.samples.is_empty(), "the file still decodes");
}
#[cfg(feature = "jpx")]
#[test]
fn a_jp2_palette_is_left_to_the_pdf_when_the_dictionary_carries_indexed() {
let jp2 = fixtures_jpx::jpx_gray_8_jp2_with_palette();
let mut dict = jpx_gray_dict();
dict.insert(
Name::from(b"ColorSpace"),
Object::Array(vec![
Object::Name(Name::from(b"Indexed")),
Object::Name(Name::from(b"DeviceRGB")),
Object::Integer(0),
Object::String(palette_entry(0).to_vec()),
]),
);
let img = decode_fixture(&jp2, &dict).unwrap();
assert_eq!(
img.components, 1,
"the samples must remain a single INDEX channel"
);
assert!(
img.notes.jpx_palette_left_to_pdf,
"and the decision must be disclosed -- it is invisible in the output"
);
assert_eq!(
&img.samples[..8],
&fixtures_jpx::JPX_GRAY_8_SAMPLES[..8],
"indices pass through untouched, identical to the palette-free fixture"
);
let first = fixtures_jpx::JPX_GRAY_8_SAMPLES[0];
assert_ne!(
&img.samples[..3],
&palette_entry(first),
"if these matched, the palette had been applied after all and the \
renderer would apply it a SECOND time"
);
}
#[cfg(feature = "jpx")]
#[test]
fn only_a_visible_indexed_array_suppresses_palette_resolution() {
let doc = empty_document();
let with = |cs: Option<Object>| {
let mut d = Dict::new();
if let Some(cs) = cs {
d.insert(Name::from(b"ColorSpace"), cs);
}
super::jpx::dict_colorspace_is_indexed(&doc.view(), &d)
};
let arr = |first: &[u8]| {
Object::Array(vec![
Object::Name(Name::from(first)),
Object::Name(Name::from(b"DeviceRGB")),
])
};
assert!(with(Some(arr(b"Indexed"))), "the array form is decidable");
assert!(!with(Some(arr(b"ICCBased"))));
assert!(!with(Some(Object::Name(Name::from(b"DeviceRGB")))));
assert!(
!with(Some(Object::Name(Name::from(b"CS0")))),
"a NAMED resource is not visible from the codec layer; answering \
`false` keeps the pre-existing behaviour instead of guessing"
);
assert!(!with(None), "no /ColorSpace at all");
}
#[cfg(feature = "jxl")]
fn jxl_dict(w: i64, h: i64, extra: Vec<(&[u8], Object)>) -> Dict {
let mut all: Vec<(&[u8], Object)> = vec![
(b"Filter", name(b"JXLDecode")),
(b"Width", Object::Integer(w)),
(b"Height", Object::Integer(h)),
];
all.extend(extra);
dict_with(all)
}
#[cfg(feature = "jxl")]
#[test]
fn jxl_bare_and_boxed_gray_decode_to_the_same_samples() {
let dict = jxl_dict(4, 2, vec![]);
let bare = decode_fixture(fixtures_jxl::JXL_GRAY_4X2, &dict).unwrap();
let boxed = decode_fixture(fixtures_jxl::JXL_GRAY_4X2_BOXED, &dict).unwrap();
assert_eq!(bare.codec, Some(Codec::Jxl));
assert_eq!((bare.width, bare.height, bare.components), (4, 2, 1));
assert_eq!(bare.color_model, CodecColorModel::Gray);
assert_eq!(bare.samples, fixtures_jxl::JXL_GRAY_4X2_SAMPLES);
assert_eq!(boxed.samples, bare.samples);
assert!(bare.notes.jxl_nonstandard);
assert!(!bare.notes.geometry_mismatch);
assert!(bare.icc_profile.as_ref().is_some_and(|p| !p.is_empty()));
assert_eq!(bare.embedded_alpha, None);
}
#[cfg(feature = "jxl")]
#[test]
fn jxl_rgb_interleaves_in_order_and_counts_a_geometry_disagreement() {
let img = decode_fixture(fixtures_jxl::JXL_RGB_2X2, &jxl_dict(2, 2, vec![])).unwrap();
assert_eq!(img.color_model, CodecColorModel::Rgb);
assert_eq!(img.samples, fixtures_jxl::JXL_RGB_2X2_SAMPLES);
let wrong = decode_fixture(fixtures_jxl::JXL_RGB_2X2, &jxl_dict(3, 2, vec![])).unwrap();
assert!(wrong.notes.geometry_mismatch);
assert_eq!(wrong.width, 2, "the codestream's geometry wins");
}
#[cfg(feature = "jxl")]
#[test]
fn jxl_alpha_follows_smaskindata_then_a_dictionary_smask() {
let rgba = fixtures_jxl::JXL_RGBA_2X2_SAMPLES;
let colour: Vec<u8> = rgba.chunks(4).flat_map(|p| p[..3].to_vec()).collect();
let alpha: Vec<u8> = rgba.chunks(4).map(|p| p[3]).collect();
let decode =
|extra| decode_fixture(fixtures_jxl::JXL_RGBA_2X2, &jxl_dict(2, 2, extra)).unwrap();
let absent = decode(vec![]);
assert_eq!(absent.samples, colour);
assert_eq!(absent.embedded_alpha.as_deref(), Some(&alpha[..]));
assert_eq!(
decode(vec![(b"SMaskInData", Object::Integer(0))]).embedded_alpha,
None
);
let smask = vec![(
&b"SMask"[..],
Object::Reference(pdfcer_model::object::ObjId::new(9, 0)),
)];
assert_eq!(
decode(smask).embedded_alpha,
None,
"the dictionary's /SMask wins"
);
let forced = vec![
(
&b"SMask"[..],
Object::Reference(pdfcer_model::object::ObjId::new(9, 0)),
),
(&b"SMaskInData"[..], Object::Integer(1)),
];
assert!(decode(forced).embedded_alpha.is_some());
}
#[cfg(feature = "jxl")]
#[test]
fn jxl_garbage_is_a_codec_error_with_the_note_set() {
let err = decode_fixture(b"\xFF\x0Anot really", &jxl_dict(1, 1, vec![])).unwrap_err();
assert!(
matches!(
err,
ImageCodecError::Corrupt {
codec: Codec::Jxl,
..
}
),
"{err:?}"
);
}
}