use pdfcer_model::graph::ObjectGraph;
use pdfcer_model::object::Dict;
use pdfcer_model::view::DocumentView;
use crate::peak::{DecodeLimits, predict_peak};
use crate::{CmykJpegPolarity, ImageCodecError};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum SizeLimit {
MemoryBudget,
OperatorPixelCap,
}
impl SizeLimit {
#[must_use]
pub const fn refusal_key(self) -> &'static str {
match self {
Self::MemoryBudget => "image/limit/memory-budget",
Self::OperatorPixelCap => "image/limit/pixel-cap",
}
}
#[must_use]
pub const fn unit(self) -> &'static str {
match self {
Self::MemoryBudget => "bytes",
Self::OperatorPixelCap => "pixels",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub struct DecodeOptions {
pub cmyk_jpeg_polarity: CmykJpegPolarity,
pub limits: DecodeLimits,
}
impl DecodeOptions {
#[must_use]
pub const fn with_cmyk_jpeg_polarity(mut self, polarity: CmykJpegPolarity) -> Self {
self.cmyk_jpeg_polarity = polarity;
self
}
#[must_use]
pub const fn with_limits(mut self, limits: DecodeLimits) -> Self {
self.limits = limits;
self
}
}
pub(crate) fn check(
doc: &DocumentView<'_>,
dict: &Dict,
raw: &[u8],
limits: &DecodeLimits,
) -> Result<(), ImageCodecError> {
let pixels = declared_pixels(doc, dict);
if let (Some(cap), Some(pixels)) = (limits.max_pixels, pixels)
&& pixels > cap
{
return Err(ImageCodecError::LimitExceeded {
limit: SizeLimit::OperatorPixelCap,
needed: pixels,
allowed: cap,
});
}
let downstream = pixels
.unwrap_or(0)
.saturating_mul(limits.downstream_bytes_per_pixel);
let needed = predict_peak(doc, dict, raw)
.unwrap_or(0)
.saturating_add(downstream);
if needed > limits.memory_budget {
return Err(ImageCodecError::LimitExceeded {
limit: SizeLimit::MemoryBudget,
needed,
allowed: limits.memory_budget,
});
}
Ok(())
}
fn declared_pixels(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
let dim = |key: &[u8], short: &[u8]| -> Option<u64> {
let entry = dict.get(key).or_else(|| dict.get(short))?;
u64::try_from(doc.resolve(entry).as_int()?).ok()
};
Some(dim(b"Width", b"W")?.saturating_mul(dim(b"Height", b"H")?))
}