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    /// A side length past what the format or its decoder can represent:
23    /// JBIG2 through `hayro-jbig2`, 65,535 samples. A fact about the data
24    /// path, not a policy. Figures are samples per side.
25    FormatField,
26}
27
28impl SizeLimit {
29    /// Stable refusal key: `image/limit/memory-budget`,
30    /// `image/limit/pixel-cap` or `image/limit/format-field`.
31    #[must_use]
32    pub const fn refusal_key(self) -> &'static str {
33        match self {
34            Self::MemoryBudget => "image/limit/memory-budget",
35            Self::OperatorPixelCap => "image/limit/pixel-cap",
36            Self::FormatField => "image/limit/format-field",
37        }
38    }
39
40    /// The unit `needed` and `allowed` are counted in, for messages.
41    #[must_use]
42    pub const fn unit(self) -> &'static str {
43        match self {
44            Self::MemoryBudget => "bytes",
45            Self::OperatorPixelCap => "pixels",
46            Self::FormatField => "samples per side",
47        }
48    }
49}
50
51/// Per-decode options for [`crate::decode_image_view_with`].
52///
53/// # Examples
54///
55/// ```
56/// use pdfcer_image_codec::peak::DecodeLimits;
57/// use pdfcer_image_codec::{CmykJpegPolarity, DecodeOptions};
58///
59/// let options = DecodeOptions::default()
60///     .with_cmyk_jpeg_polarity(CmykJpegPolarity::InvertOnApp14)
61///     .with_limits(DecodeLimits::new(64 << 20).with_max_pixels(Some(1_000_000)));
62/// assert_eq!(options.limits.memory_budget, 64 << 20);
63/// ```
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65#[non_exhaustive]
66pub struct DecodeOptions {
67    /// The `DCT-A1` polarity rule (R169).
68    pub cmyk_jpeg_polarity: CmykJpegPolarity,
69    /// The memory budget and pixel cap the image is checked against.
70    pub limits: DecodeLimits,
71}
72
73impl DecodeOptions {
74    /// Sets the `DCT-A1` polarity rule.
75    #[must_use]
76    pub const fn with_cmyk_jpeg_polarity(mut self, polarity: CmykJpegPolarity) -> Self {
77        self.cmyk_jpeg_polarity = polarity;
78        self
79    }
80
81    /// Sets the limits.
82    #[must_use]
83    pub const fn with_limits(mut self, limits: DecodeLimits) -> Self {
84        self.limits = limits;
85        self
86    }
87}
88
89/// Refuse an image that crosses `limits`, from its dictionary and raw
90/// bytes alone.
91///
92/// The pixel cap is checked first, against the dictionary's
93/// `/Width x /Height`. The memory figure is [`predict_peak`] plus
94/// `width * height * downstream_bytes_per_pixel`; where the peak cannot be
95/// predicted only the downstream term is checked, and the decode is
96/// otherwise bounded by fallible allocation.
97pub(crate) fn check(
98    doc: &DocumentView<'_>,
99    dict: &Dict,
100    raw: &[u8],
101    limits: &DecodeLimits,
102) -> Result<(), ImageCodecError> {
103    let pixels = declared_pixels(doc, dict);
104    if let (Some(cap), Some(pixels)) = (limits.max_pixels, pixels)
105        && pixels > cap
106    {
107        return Err(ImageCodecError::LimitExceeded {
108            limit: SizeLimit::OperatorPixelCap,
109            needed: pixels,
110            allowed: cap,
111        });
112    }
113    let downstream = pixels
114        .unwrap_or(0)
115        .saturating_mul(limits.downstream_bytes_per_pixel);
116    let needed = predict_peak(doc, dict, raw)
117        .unwrap_or(0)
118        .saturating_add(downstream);
119    if needed > limits.memory_budget {
120        return Err(ImageCodecError::LimitExceeded {
121            limit: SizeLimit::MemoryBudget,
122            needed,
123            allowed: limits.memory_budget,
124        });
125    }
126    Ok(())
127}
128
129/// Refuse `needed` bytes past [`DecodeLimits::memory_budget`]: the check a
130/// codec makes on its own header geometry, which the dictionary-level
131/// [`check`] cannot see when a filter sits in front of the codec.
132pub(crate) fn admit(limits: &DecodeLimits, needed: u64) -> Result<(), ImageCodecError> {
133    if needed > limits.memory_budget {
134        return Err(ImageCodecError::LimitExceeded {
135            limit: SizeLimit::MemoryBudget,
136            needed,
137            allowed: limits.memory_budget,
138        });
139    }
140    Ok(())
141}
142
143fn declared_pixels(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
144    let dim = |key: &[u8], short: &[u8]| -> Option<u64> {
145        let entry = dict.get(key).or_else(|| dict.get(short))?;
146        u64::try_from(doc.resolve(entry).as_int()?).ok()
147    };
148    Some(dim(b"Width", b"W")?.saturating_mul(dim(b"Height", b"H")?))
149}