Skip to main content

pdfcer_image_codec/
limits.rs

1//! The decode-time check of [`DecodeLimits`] (decision 227 sources (a)
2//! and (c)), run before the filter chain touches the data.
3
4use pdfcer_model::graph::ObjectGraph;
5use pdfcer_model::object::Dict;
6use pdfcer_model::view::DocumentView;
7
8use crate::peak::{DecodeLimits, predict_peak};
9use crate::{CmykJpegPolarity, ImageCodecError};
10
11/// Which limit refused an image ([`ImageCodecError::LimitExceeded`]).
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
13#[non_exhaustive]
14pub enum SizeLimit {
15    /// [`DecodeLimits::memory_budget`]: the predicted peak heap bytes,
16    /// plus what the caller allocates per pixel afterwards. Figures are
17    /// bytes.
18    MemoryBudget,
19    /// [`DecodeLimits::max_pixels`], the operator's strict mode. Figures
20    /// are pixels.
21    OperatorPixelCap,
22}
23
24impl SizeLimit {
25    /// Stable refusal key: `image/limit/memory-budget` or
26    /// `image/limit/pixel-cap`.
27    #[must_use]
28    pub const fn refusal_key(self) -> &'static str {
29        match self {
30            Self::MemoryBudget => "image/limit/memory-budget",
31            Self::OperatorPixelCap => "image/limit/pixel-cap",
32        }
33    }
34
35    /// The unit `needed` and `allowed` are counted in, for messages.
36    #[must_use]
37    pub const fn unit(self) -> &'static str {
38        match self {
39            Self::MemoryBudget => "bytes",
40            Self::OperatorPixelCap => "pixels",
41        }
42    }
43}
44
45/// Per-decode options for [`crate::decode_image_view_with`].
46///
47/// # Examples
48///
49/// ```
50/// use pdfcer_image_codec::peak::DecodeLimits;
51/// use pdfcer_image_codec::{CmykJpegPolarity, DecodeOptions};
52///
53/// let options = DecodeOptions::default()
54///     .with_cmyk_jpeg_polarity(CmykJpegPolarity::InvertOnApp14)
55///     .with_limits(DecodeLimits::new(64 << 20).with_max_pixels(Some(1_000_000)));
56/// assert_eq!(options.limits.memory_budget, 64 << 20);
57/// ```
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
59#[non_exhaustive]
60pub struct DecodeOptions {
61    /// The `DCT-A1` polarity rule (R169).
62    pub cmyk_jpeg_polarity: CmykJpegPolarity,
63    /// The memory budget and pixel cap the image is checked against.
64    pub limits: DecodeLimits,
65}
66
67impl DecodeOptions {
68    /// Sets the `DCT-A1` polarity rule.
69    #[must_use]
70    pub const fn with_cmyk_jpeg_polarity(mut self, polarity: CmykJpegPolarity) -> Self {
71        self.cmyk_jpeg_polarity = polarity;
72        self
73    }
74
75    /// Sets the limits.
76    #[must_use]
77    pub const fn with_limits(mut self, limits: DecodeLimits) -> Self {
78        self.limits = limits;
79        self
80    }
81}
82
83/// Refuse an image that crosses `limits`, from its dictionary and raw
84/// bytes alone.
85///
86/// The pixel cap is checked first, against the dictionary's
87/// `/Width x /Height`. The memory figure is [`predict_peak`] plus
88/// `width * height * downstream_bytes_per_pixel`; where the peak cannot be
89/// predicted only the downstream term is checked, and the decode is
90/// otherwise bounded by fallible allocation.
91pub(crate) fn check(
92    doc: &DocumentView<'_>,
93    dict: &Dict,
94    raw: &[u8],
95    limits: &DecodeLimits,
96) -> Result<(), ImageCodecError> {
97    let pixels = declared_pixels(doc, dict);
98    if let (Some(cap), Some(pixels)) = (limits.max_pixels, pixels)
99        && pixels > cap
100    {
101        return Err(ImageCodecError::LimitExceeded {
102            limit: SizeLimit::OperatorPixelCap,
103            needed: pixels,
104            allowed: cap,
105        });
106    }
107    let downstream = pixels
108        .unwrap_or(0)
109        .saturating_mul(limits.downstream_bytes_per_pixel);
110    let needed = predict_peak(doc, dict, raw)
111        .unwrap_or(0)
112        .saturating_add(downstream);
113    if needed > limits.memory_budget {
114        return Err(ImageCodecError::LimitExceeded {
115            limit: SizeLimit::MemoryBudget,
116            needed,
117            allowed: limits.memory_budget,
118        });
119    }
120    Ok(())
121}
122
123fn declared_pixels(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
124    let dim = |key: &[u8], short: &[u8]| -> Option<u64> {
125        let entry = dict.get(key).or_else(|| dict.get(short))?;
126        u64::try_from(doc.resolve(entry).as_int()?).ok()
127    };
128    Some(dim(b"Width", b"W")?.saturating_mul(dim(b"Height", b"H")?))
129}