pub(crate) mod dct;
mod jbig2;
#[cfg(feature = "jpx")]
mod jpx;
use pdfcer_model::filters::{self, predictor};
use pdfcer_model::graph::ObjectGraph;
use pdfcer_model::object::{Dict, Object};
use pdfcer_model::view::DocumentView;
use crate::Codec;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct DecodeLimits {
pub memory_budget: u64,
pub max_pixels: Option<u64>,
pub downstream_bytes_per_pixel: u64,
}
impl DecodeLimits {
pub const FALLBACK_MEMORY_BUDGET: u64 = if cfg!(target_pointer_width = "64") {
4 << 30
} else {
1 << 30
};
#[must_use]
pub const fn new(memory_budget: u64) -> Self {
Self {
memory_budget,
max_pixels: None,
downstream_bytes_per_pixel: 0,
}
}
#[must_use]
pub const fn for_physical_memory(physical_bytes: u64) -> Self {
Self::new(physical_bytes / 2)
}
#[must_use]
pub const fn with_max_pixels(mut self, max_pixels: Option<u64>) -> Self {
self.max_pixels = max_pixels;
self
}
#[must_use]
pub const fn with_downstream_bytes_per_pixel(mut self, bytes: u64) -> Self {
self.downstream_bytes_per_pixel = bytes;
self
}
}
impl Default for DecodeLimits {
fn default() -> Self {
Self::new(Self::FALLBACK_MEMORY_BUDGET)
}
}
const FIXED_OVERHEAD: u64 = 128 << 10;
const RECORD_OVERHEAD: u64 = 1 << 10;
const FLATE_CHUNK: u64 = 64 << 10;
#[must_use]
pub fn predict_peak(doc: &DocumentView<'_>, dict: &Dict, raw: &[u8]) -> Option<u64> {
let names = filters::filter_names(dict).ok()?;
let input = len(raw);
match names.as_slice() {
[] => Some(input.saturating_add(RECORD_OVERHEAD)),
[only] => match Codec::from_name(only) {
Some(codec) => {
codec_working_bytes(doc, codec, raw, dict).map(|w| w.saturating_add(input))
}
None if matches!(only.as_slice(), b"FlateDecode" | b"Fl") => {
flate_peak(doc, dict, input)
}
None => None,
},
_ => None,
}
}
#[must_use]
pub fn codec_working_bytes(
doc: &DocumentView<'_>,
codec: Codec,
data: &[u8],
dict: &Dict,
) -> Option<u64> {
let parms = crate::codec_parms(dict, filters::filter_names(dict).ok()?.len());
let working = match codec {
Codec::Dct => dct::working_bytes(data)?,
Codec::Ccitt => ccitt_working_bytes(doc, parms, dict)?,
Codec::Jbig2 => {
let globals = crate::jbig2::globals(doc, parms).ok()?;
jbig2::working_bytes(data, globals.as_deref())?
}
#[cfg(feature = "jpx")]
Codec::Jpx => jpx::working_bytes(data)?,
#[cfg(not(feature = "jpx"))]
Codec::Jpx => 0,
Codec::Jxl => return None,
};
Some(working.saturating_add(FIXED_OVERHEAD))
}
fn flate_peak(doc: &DocumentView<'_>, dict: &Dict, input: u64) -> Option<u64> {
let (width, height) = (
dim(doc, dict, b"Width", b"W")?,
dim(doc, dict, b"Height", b"H")?,
);
let row = width
.saturating_mul(sample_components(doc, dict)?)
.saturating_mul(bits_per_component(doc, dict)?)
.div_ceil(8);
let samples = row.saturating_mul(height);
let params = predictor::Params::from_dict(crate::codec_parms(dict, 1)).ok()?;
let png = params.filter(|p| p.predictor >= 10);
let inflated = match png {
Some(p) => {
let bits = u64::from(p.columns) * u64::from(p.colors) * u64::from(p.bits_per_component);
bits.div_ceil(8).saturating_add(1).saturating_mul(height)
}
None => samples,
};
let cap = drain_capacity(inflated);
let inflating = input
.saturating_add(FLATE_CHUNK)
.saturating_add(cap / 2)
.saturating_add(cap);
let unfiltering = match png {
Some(_) => input.saturating_add(cap).saturating_add(inflated),
None => 0,
};
Some(inflating.max(unfiltering).saturating_add(FIXED_OVERHEAD))
}
fn drain_capacity(n: u64) -> u64 {
let mut cap = FLATE_CHUNK;
while cap < n {
cap = cap.saturating_mul(2);
}
cap
}
fn ccitt_working_bytes(doc: &DocumentView<'_>, parms: Option<&Dict>, dict: &Dict) -> Option<u64> {
let (columns, rows) = crate::ccitt::declared_geometry(doc, parms, dict);
let columns = u64::try_from(columns).ok().filter(|&c| c > 0)?;
let packed = columns.div_ceil(8).saturating_mul(u64::from(rows?));
let lines = columns.saturating_add(2).saturating_mul(16);
Some(byte_pushed_peak(packed).saturating_add(lines))
}
pub(crate) fn byte_pushed_peak(n: u64) -> u64 {
let cap = n.max(8).checked_next_power_of_two().unwrap_or(u64::MAX);
cap.saturating_add(cap / 2)
}
pub(crate) fn sample_components(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
if is_image_mask(doc, dict) {
return Some(1);
}
let space = dict.get(b"ColorSpace").or_else(|| dict.get(b"CS"))?;
colour_space_components(doc, doc.resolve(space))
}
fn colour_space_components(doc: &DocumentView<'_>, space: &Object) -> Option<u64> {
let (family, rest) = match space {
Object::Name(n) => (n.as_bytes(), &[][..]),
Object::Array(items) => {
let (first, rest) = items.split_first()?;
(doc.resolve(first).as_name()?.as_bytes(), rest)
}
_ => return None,
};
match family {
b"DeviceGray" | b"G" | b"CalGray" | b"Indexed" | b"I" | b"Separation" => Some(1),
b"DeviceRGB" | b"RGB" | b"CalRGB" | b"Lab" => Some(3),
b"DeviceCMYK" | b"CMYK" => Some(4),
b"DeviceN" => Some(len(doc.resolve(rest.first()?).as_array()?)),
b"ICCBased" => match doc.resolve(rest.first()?) {
Object::Stream(s) => s.dict.get(b"N").and_then(Object::as_int),
_ => None,
}
.and_then(|n| u64::try_from(n).ok()),
_ => None,
}
}
pub(crate) fn bits_per_component(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
if is_image_mask(doc, dict) {
return Some(1);
}
dim(doc, dict, b"BitsPerComponent", b"BPC")
}
fn is_image_mask(doc: &DocumentView<'_>, dict: &Dict) -> bool {
let entry = dict.get(b"ImageMask").or_else(|| dict.get(b"IM"));
matches!(entry.map(|o| doc.resolve(o)), Some(Object::Boolean(true)))
}
pub(crate) fn dim(doc: &DocumentView<'_>, dict: &Dict, 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()
}
fn len<T>(s: &[T]) -> u64 {
u64::try_from(s.len()).unwrap_or(u64::MAX)
}
fn be<const N: usize>(d: &[u8], at: usize) -> Option<u64> {
let bytes: &[u8; N] = d.get(at..at.checked_add(N)?)?.try_into().ok()?;
Some(bytes.iter().fold(0, |v, &b| (v << 8) | u64::from(b)))
}