Skip to main content

pdfcer_image_codec/
peak.rs

1//! Peak-memory prediction for image decodes, and the limits a prediction
2//! is checked against (decision 227).
3//!
4//! A predictor reads only headers: the geometry an image declares, never
5//! its entropy-coded data. It answers "how many heap bytes will the decode
6//! hold at its worst moment", so a caller can refuse an image that does
7//! not fit its [`DecodeLimits::memory_budget`] *before* a dependency
8//! allocates infallibly. Each predictor is pinned by measurement: the
9//! `peak_memory` integration test counts the real peak with a counting
10//! allocator and requires `measured <= predicted <= 1.5 * measured` on
11//! every path, so a dependency upgrade that changes buffer sizing fails
12//! that test rather than silently undercounting.
13//!
14//! Nothing in this module refuses anything yet; the budget goes live in a
15//! later Pass and the existing ceiling constants stay in force until then.
16
17pub(crate) mod dct;
18mod jbig2;
19#[cfg(feature = "jpx")]
20mod jpx;
21
22use pdfcer_model::filters::{self, predictor};
23use pdfcer_model::graph::ObjectGraph;
24use pdfcer_model::object::{Dict, Object};
25use pdfcer_model::view::DocumentView;
26
27use crate::Codec;
28
29/// The memory a caller allows one image decode, plus an optional operator
30/// pixel cap (decision 227 sources (a) and (c)).
31///
32/// The budget is supplied by the shell, normally half the machine's
33/// physical memory; the engine never queries the machine itself, so a
34/// result is reproducible from its inputs.
35///
36/// # Examples
37///
38/// ```
39/// use pdfcer_image_codec::peak::DecodeLimits;
40///
41/// let limits = DecodeLimits::for_physical_memory(16 << 30)
42///     .with_max_pixels(Some(100_000_000))
43///     .with_downstream_bytes_per_pixel(4);
44/// assert_eq!(limits.memory_budget, 8 << 30);
45/// assert_eq!(limits.max_pixels, Some(100_000_000));
46/// ```
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48#[non_exhaustive]
49pub struct DecodeLimits {
50    /// Heap bytes one decode may hold at its peak, including the samples it
51    /// returns and `downstream_bytes_per_pixel` for every pixel.
52    pub memory_budget: u64,
53    /// Operator strict mode: the most pixels an image may declare. `None`
54    /// (the default) means memory alone decides.
55    pub max_pixels: Option<u64>,
56    /// Bytes per pixel the caller allocates after the decode (an RGBA
57    /// pixmap is 4, each spot plane 1), added to the codec's own peak.
58    pub downstream_bytes_per_pixel: u64,
59}
60
61impl DecodeLimits {
62    /// The budget used when no shell supplies one: 4 GiB on 64-bit
63    /// targets, 1 GiB on 32-bit targets including `wasm32`.
64    pub const FALLBACK_MEMORY_BUDGET: u64 = if cfg!(target_pointer_width = "64") {
65        4 << 30
66    } else {
67        1 << 30
68    };
69
70    /// A budget of `memory_budget` bytes, no pixel cap, nothing downstream.
71    #[must_use]
72    pub const fn new(memory_budget: u64) -> Self {
73        Self {
74            memory_budget,
75            max_pixels: None,
76            downstream_bytes_per_pixel: 0,
77        }
78    }
79
80    /// The default budget for a machine with `physical_bytes` of RAM: half
81    /// of it, so a decode never competes for the whole machine.
82    #[must_use]
83    pub const fn for_physical_memory(physical_bytes: u64) -> Self {
84        Self::new(physical_bytes / 2)
85    }
86
87    /// Sets or clears the operator pixel cap.
88    #[must_use]
89    pub const fn with_max_pixels(mut self, max_pixels: Option<u64>) -> Self {
90        self.max_pixels = max_pixels;
91        self
92    }
93
94    /// Sets the bytes per pixel the caller allocates after the decode.
95    #[must_use]
96    pub const fn with_downstream_bytes_per_pixel(mut self, bytes: u64) -> Self {
97        self.downstream_bytes_per_pixel = bytes;
98        self
99    }
100}
101
102impl Default for DecodeLimits {
103    /// [`DecodeLimits::new`] over [`DecodeLimits::FALLBACK_MEMORY_BUDGET`].
104    fn default() -> Self {
105        Self::new(Self::FALLBACK_MEMORY_BUDGET)
106    }
107}
108
109/// Allocator bookkeeping and small tables every decode holds regardless of
110/// geometry (Huffman tables, segment lists, the inflater's state), measured
111/// at up to 110 KiB across the paths in the `peak_memory` test.
112const FIXED_OVERHEAD: u64 = 128 << 10;
113
114/// The decoded-image record an unfiltered decode adds to its sample copy.
115const RECORD_OVERHEAD: u64 = 1 << 10;
116
117/// The inflater's output chunk, mirroring `pdfcer_model::filters::CHUNK`.
118/// A drift is caught by the `peak_memory` test, not silently.
119const FLATE_CHUNK: u64 = 64 << 10;
120
121/// Predicted peak heap bytes of [`crate::decode_image_view`] on this image
122/// stream: the copy of `raw` the filter chain starts from, every filter
123/// stage's buffers and the codec's working set, including the samples it
124/// returns.
125///
126/// Not included: `w * h * downstream_bytes_per_pixel`, which the caller
127/// adds from its [`DecodeLimits`].
128///
129/// Returns `None` when the peak cannot be bounded from headers: a filter
130/// chain other than none or a single `FlateDecode` before the image data,
131/// any filter in front of a codec (its input length is only known after
132/// decoding), a JBIG2 stream with a symbol dictionary or an unknown page
133/// height, JPEG XL, or headers too damaged to read. A `None` decode is
134/// bounded by the fallible-allocation backstop alone.
135///
136/// The prediction for an unfiltered or Flate image assumes the stream
137/// decodes to the length its geometry declares; data past that length is
138/// not counted.
139#[must_use]
140pub fn predict_peak(doc: &DocumentView<'_>, dict: &Dict, raw: &[u8]) -> Option<u64> {
141    let names = filters::filter_names(dict).ok()?;
142    let input = len(raw);
143    match names.as_slice() {
144        [] => Some(input.saturating_add(RECORD_OVERHEAD)),
145        [only] => match Codec::from_name(only) {
146            Some(codec) => {
147                codec_working_bytes(doc, codec, raw, dict).map(|w| w.saturating_add(input))
148            }
149            None if matches!(only.as_slice(), b"FlateDecode" | b"Fl") => {
150                flate_peak(doc, dict, input)
151            }
152            None => None,
153        },
154        _ => None,
155    }
156}
157
158/// Predicted peak heap bytes a terminal `codec` holds while decoding
159/// `data`, the fully filter-decoded image data, *above* `data` itself:
160/// working buffers plus the returned samples.
161///
162/// `dict` is the image dictionary; its `/DecodeParms` supply CCITT
163/// geometry and `/JBIG2Globals`. Returns `None` where [`predict_peak`]
164/// lists, for the codec part.
165#[must_use]
166pub fn codec_working_bytes(
167    doc: &DocumentView<'_>,
168    codec: Codec,
169    data: &[u8],
170    dict: &Dict,
171) -> Option<u64> {
172    let parms = crate::codec_parms(dict, filters::filter_names(dict).ok()?.len());
173    let working = match codec {
174        Codec::Dct => dct::working_bytes(data)?,
175        Codec::Ccitt => ccitt_working_bytes(doc, parms, dict)?,
176        Codec::Jbig2 => {
177            let globals = crate::jbig2::globals(doc, parms).ok()?;
178            jbig2::working_bytes(data, globals.as_deref())?
179        }
180        #[cfg(feature = "jpx")]
181        Codec::Jpx => jpx::working_bytes(data)?,
182        #[cfg(not(feature = "jpx"))]
183        Codec::Jpx => 0,
184        Codec::Jxl => return None,
185    };
186    Some(working.saturating_add(FIXED_OVERHEAD))
187}
188
189/// `FlateDecode` alone in front of uncoded samples (ISO 32000-1 7.4.4).
190///
191/// The inflated bytes grow by doubling from one `FLATE_CHUNK`, so at the
192/// last growth the old buffer (C/2) and the new one (C) are both live
193/// beside the compressed copy. A PNG predictor then writes the unfiltered
194/// rows into a fresh buffer while the inflated one is still held; a TIFF
195/// predictor works in place.
196fn flate_peak(doc: &DocumentView<'_>, dict: &Dict, input: u64) -> Option<u64> {
197    let (width, height) = (
198        dim(doc, dict, b"Width", b"W")?,
199        dim(doc, dict, b"Height", b"H")?,
200    );
201    let row = width
202        .saturating_mul(sample_components(doc, dict)?)
203        .saturating_mul(bits_per_component(doc, dict)?)
204        .div_ceil(8);
205    let samples = row.saturating_mul(height);
206    let params = predictor::Params::from_dict(crate::codec_parms(dict, 1)).ok()?;
207    let png = params.filter(|p| p.predictor >= 10);
208    let inflated = match png {
209        Some(p) => {
210            let bits = u64::from(p.columns) * u64::from(p.colors) * u64::from(p.bits_per_component);
211            bits.div_ceil(8).saturating_add(1).saturating_mul(height)
212        }
213        None => samples,
214    };
215    let cap = drain_capacity(inflated);
216    let inflating = input
217        .saturating_add(FLATE_CHUNK)
218        .saturating_add(cap / 2)
219        .saturating_add(cap);
220    let unfiltering = match png {
221        Some(_) => input.saturating_add(cap).saturating_add(inflated),
222        None => 0,
223    };
224    Some(inflating.max(unfiltering).saturating_add(FIXED_OVERHEAD))
225}
226
227/// Capacity of the inflate output buffer once it holds `n` bytes: the
228/// first pull fills one chunk, then each growth doubles.
229fn drain_capacity(n: u64) -> u64 {
230    let mut cap = FLATE_CHUNK;
231    while cap < n {
232        cap = cap.saturating_mul(2);
233    }
234    cap
235}
236
237/// CCITT (T.4/T.6): two coding lines of `Columns` changing elements, and
238/// the packed output growing byte by byte to the declared rows.
239fn ccitt_working_bytes(doc: &DocumentView<'_>, parms: Option<&Dict>, dict: &Dict) -> Option<u64> {
240    let (columns, rows) = crate::ccitt::declared_geometry(doc, parms, dict);
241    let columns = u64::try_from(columns).ok().filter(|&c| c > 0)?;
242    let packed = columns.div_ceil(8).saturating_mul(u64::from(rows?));
243    let lines = columns.saturating_add(2).saturating_mul(16);
244    Some(byte_pushed_peak(packed).saturating_add(lines))
245}
246
247/// Peak of a `Vec<u8>` filled one byte at a time to `n` bytes: capacity
248/// doubles from 8, and the growth that reaches capacity C holds C/2 + C.
249pub(crate) fn byte_pushed_peak(n: u64) -> u64 {
250    let cap = n.max(8).checked_next_power_of_two().unwrap_or(u64::MAX);
251    cap.saturating_add(cap / 2)
252}
253
254/// Colour components per sample of an uncoded image (ISO 32000-1 8.6,
255/// 8.9.5): 1 for an image mask. `None` for a colour space that is a
256/// resource name or a `/Pattern`, which an image cannot use.
257pub(crate) fn sample_components(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
258    if is_image_mask(doc, dict) {
259        return Some(1);
260    }
261    let space = dict.get(b"ColorSpace").or_else(|| dict.get(b"CS"))?;
262    colour_space_components(doc, doc.resolve(space))
263}
264
265fn colour_space_components(doc: &DocumentView<'_>, space: &Object) -> Option<u64> {
266    let (family, rest) = match space {
267        Object::Name(n) => (n.as_bytes(), &[][..]),
268        Object::Array(items) => {
269            let (first, rest) = items.split_first()?;
270            (doc.resolve(first).as_name()?.as_bytes(), rest)
271        }
272        _ => return None,
273    };
274    match family {
275        b"DeviceGray" | b"G" | b"CalGray" | b"Indexed" | b"I" | b"Separation" => Some(1),
276        b"DeviceRGB" | b"RGB" | b"CalRGB" | b"Lab" => Some(3),
277        b"DeviceCMYK" | b"CMYK" => Some(4),
278        b"DeviceN" => Some(len(doc.resolve(rest.first()?).as_array()?)),
279        b"ICCBased" => match doc.resolve(rest.first()?) {
280            Object::Stream(s) => s.dict.get(b"N").and_then(Object::as_int),
281            _ => None,
282        }
283        .and_then(|n| u64::try_from(n).ok()),
284        _ => None,
285    }
286}
287
288/// Bits per component of an uncoded image (ISO 32000-1 8.9.5): 1 for an
289/// image mask, whose `/BitsPerComponent` is optional.
290pub(crate) fn bits_per_component(doc: &DocumentView<'_>, dict: &Dict) -> Option<u64> {
291    if is_image_mask(doc, dict) {
292        return Some(1);
293    }
294    dim(doc, dict, b"BitsPerComponent", b"BPC")
295}
296
297fn is_image_mask(doc: &DocumentView<'_>, dict: &Dict) -> bool {
298    let entry = dict.get(b"ImageMask").or_else(|| dict.get(b"IM"));
299    matches!(entry.map(|o| doc.resolve(o)), Some(Object::Boolean(true)))
300}
301
302/// A non-negative integer entry under its full or inline-abbreviated key.
303pub(crate) fn dim(doc: &DocumentView<'_>, dict: &Dict, key: &[u8], short: &[u8]) -> Option<u64> {
304    let entry = dict.get(key).or_else(|| dict.get(short))?;
305    u64::try_from(doc.resolve(entry).as_int()?).ok()
306}
307
308/// A slice length as `u64`; lossless on every supported target.
309fn len<T>(s: &[T]) -> u64 {
310    u64::try_from(s.len()).unwrap_or(u64::MAX)
311}
312
313/// Big-endian unsigned field of `N` bytes at `at`.
314fn be<const N: usize>(d: &[u8], at: usize) -> Option<u64> {
315    let bytes: &[u8; N] = d.get(at..at.checked_add(N)?)?.try_into().ok()?;
316    Some(bytes.iter().fold(0, |v, &b| (v << 8) | u64::from(b)))
317}