Skip to main content

pdfcer_image_codec/
evidence.rs

1//! Evidence bounds (decision 227): a codestream that declares more geometry
2//! than its own bytes could encode is refused before anything is sized from
3//! that geometry. Every bound is the fewest bytes a conforming encoder can
4//! spend, so a file that passes is never one these checks could misjudge.
5//!
6//! JBIG2 and JXL admit no such bound; Flate-coded image streams are bounded
7//! separately by their expected length.
8
9use crate::peak::dct::header;
10use crate::{Codec, ImageCodecError};
11
12/// The geometry a refused codestream declared, as named in
13/// [`ImageCodecError::DeclaredGeometryExceedsData`].
14///
15/// # Examples
16///
17/// ```
18/// use pdfcer_image_codec::DeclaredGeometry;
19///
20/// let g = DeclaredGeometry::Tiles { count: 65_536 };
21/// assert_eq!(g.to_string(), "65536 tiles");
22/// ```
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24#[non_exhaustive]
25pub enum DeclaredGeometry {
26    /// A frame of `width` x `height` pixels (DCT).
27    Pixels {
28        /// Declared width.
29        width: u32,
30        /// Declared height.
31        height: u32,
32    },
33    /// A tile grid of `count` tiles (JPX).
34    Tiles {
35        /// Declared tile count.
36        count: u64,
37    },
38    /// `rows` scan lines (CCITT).
39    Rows {
40        /// Declared row count.
41        rows: u32,
42    },
43}
44
45impl std::fmt::Display for DeclaredGeometry {
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            Self::Pixels { width, height } => write!(f, "{width} x {height} pixels"),
49            Self::Tiles { count } => write!(f, "{count} tiles"),
50            Self::Rows { rows } => write!(f, "{rows} rows"),
51        }
52    }
53}
54
55impl ImageCodecError {
56    /// A stable, greppable key naming why the image was refused, for
57    /// counting refusals by cause: `image/evidence/dct`, `image/evidence/jpx`
58    /// or `image/evidence/ccitt` for
59    /// [`ImageCodecError::DeclaredGeometryExceedsData`];
60    /// `image/limit/memory-budget` or `image/limit/pixel-cap` for
61    /// [`ImageCodecError::LimitExceeded`]. `None` for errors
62    /// that carry no refusal key.
63    ///
64    /// # Examples
65    ///
66    /// ```
67    /// use pdfcer_image_codec::{Codec, DeclaredGeometry, ImageCodecError};
68    ///
69    /// let e = ImageCodecError::DeclaredGeometryExceedsData {
70    ///     codec: Codec::Ccitt,
71    ///     declared: DeclaredGeometry::Rows { rows: 9000 },
72    ///     min_bytes: 1125,
73    ///     have_bytes: 40,
74    /// };
75    /// assert_eq!(e.refusal_key(), Some("image/evidence/ccitt"));
76    /// assert_eq!(ImageCodecError::Cancelled.refusal_key(), None);
77    /// ```
78    #[must_use]
79    pub fn refusal_key(&self) -> Option<&'static str> {
80        match self {
81            Self::DeclaredGeometryExceedsData { codec, .. } => Some(match codec {
82                Codec::Dct => "image/evidence/dct",
83                Codec::Jpx => "image/evidence/jpx",
84                Codec::Ccitt => "image/evidence/ccitt",
85                Codec::Jbig2 => "image/evidence/jbig2",
86                Codec::Jxl => "image/evidence/jxl",
87            }),
88            Self::LimitExceeded { limit, .. } => Some(limit.refusal_key()),
89            _ => None,
90        }
91    }
92}
93
94fn refuse(
95    codec: Codec,
96    declared: DeclaredGeometry,
97    min_bytes: u64,
98    have: usize,
99) -> ImageCodecError {
100    ImageCodecError::DeclaredGeometryExceedsData {
101        codec,
102        declared,
103        min_bytes,
104        have_bytes: u64::try_from(have).unwrap_or(u64::MAX),
105    }
106}
107
108/// Minimum entropy-coded bits for a Huffman DCT stream's first scan.
109///
110/// A component with sampling `(Hc, Vc)` has `ceil(ceil(X*Hc/Hmax)/8) *
111/// ceil(ceil(Y*Vc/Vmax)/8)` blocks (T.81 A.1.1, A.2.4). Every block of the
112/// first scan costs at least one Huffman code word for its DC difference
113/// (F.1.2.1; Annex C code lengths are 1-16 bits) and, in a sequential scan,
114/// at least one more for its AC coefficients, an EOB or a coded coefficient
115/// (F.1.2.2). A progressive first scan is a DC scan (G.1.1.1.1), one code
116/// word per block; its AC scans can cover thousands of blocks with one
117/// EOBRUN code (G.1.2.2), so only the first scan is counted.
118///
119/// A DNL segment after the first scan may redefine a non-zero `Y` (B.2.5);
120/// the bound trusts the frame header's figure, which is what the decoder
121/// sizes its buffers from.
122///
123/// `Ok(None)` means no bound applies: a DNL-deferred height (`Y = 0`,
124/// B.2.2), an unparsed header, or an inconsistent one the decoder will
125/// reject on its own terms.
126fn dct_min_bits(data: &[u8]) -> Result<Option<(u64, DeclaredGeometry)>, ImageCodecError> {
127    let Some(h) = header(data) else {
128        return Ok(None);
129    };
130    if h.process == 2 && h.first_scan_ss != 0 {
131        return Err(ImageCodecError::Corrupt {
132            codec: Codec::Dct,
133            detail: format!(
134                "progressive frame's first scan starts at coefficient {}; the DC scan \
135                 must come first (T.81 G.1.1.1.1)",
136                h.first_scan_ss
137            ),
138        });
139    }
140    if !matches!(h.process, 0..=2) || h.height == 0 || h.first_scan_selectors.is_empty() {
141        return Ok(None);
142    }
143    let hmax = h.sampling.iter().map(|s| s.0).max().unwrap_or(0);
144    let vmax = h.sampling.iter().map(|s| s.1).max().unwrap_or(0);
145    if hmax == 0 || vmax == 0 {
146        return Ok(None);
147    }
148    let mut fewest: Option<u64> = None;
149    for cs in &h.first_scan_selectors {
150        let Some(at) = h.ids.iter().position(|id| id == cs) else {
151            return Ok(None);
152        };
153        let Some(&(hc, vc)) = h.sampling.get(at) else {
154            return Ok(None);
155        };
156        let x = (h.width * hc).div_ceil(hmax).div_ceil(8);
157        let y = (h.height * vc).div_ceil(vmax).div_ceil(8);
158        let blocks = x.saturating_mul(y);
159        fewest = Some(fewest.map_or(blocks, |f| f.min(blocks)));
160    }
161    let per_block = if h.process == 2 { 1 } else { 2 };
162    let declared = DeclaredGeometry::Pixels {
163        width: u32::try_from(h.width).unwrap_or(u32::MAX),
164        height: u32::try_from(h.height).unwrap_or(u32::MAX),
165    };
166    Ok(fewest.map(|b| (b.saturating_mul(per_block), declared)))
167}
168
169/// DCT evidence: `8 * data.len()` must reach the first scan's minimum bits.
170///
171/// # Errors
172///
173/// [`ImageCodecError::DeclaredGeometryExceedsData`] when it does not;
174/// [`ImageCodecError::Corrupt`] for a progressive frame whose first scan is
175/// not a DC scan, which would make the bound unsound.
176pub(crate) fn dct(data: &[u8]) -> Result<(), ImageCodecError> {
177    let Some((bits, declared)) = dct_min_bits(data)? else {
178        return Ok(());
179    };
180    let have_bits = u64::try_from(data.len())
181        .unwrap_or(u64::MAX)
182        .saturating_mul(8);
183    if have_bits >= bits {
184        return Ok(());
185    }
186    Err(refuse(Codec::Dct, declared, bits.div_ceil(8), data.len()))
187}
188
189#[cfg(feature = "jpx")]
190/// Bytes every JPX tile-part takes at least: a 12-byte SOT marker segment
191/// (Lsot is fixed at 10) plus the 2-byte SOD marker (T.800 A.4.2).
192const JPX_TILE_PART_BYTES: u64 = 14;
193
194#[cfg(feature = "jpx")]
195/// JPX evidence: `tiles` may exceed `floor` (the work bound below which no
196/// evidence is asked for) only when the data holds a minimal tile-part for
197/// each tile, `tiles <= max(floor, len / 14)`.
198///
199/// # Errors
200///
201/// [`ImageCodecError::DeclaredGeometryExceedsData`] when it does not.
202pub(crate) fn jpx_tiles(tiles: u64, floor: u64, len: usize) -> Result<(), ImageCodecError> {
203    let min_bytes = tiles.saturating_mul(JPX_TILE_PART_BYTES);
204    if tiles <= floor || u64::try_from(len).unwrap_or(u64::MAX) >= min_bytes {
205        return Ok(());
206    }
207    Err(refuse(
208        Codec::Jpx,
209        DeclaredGeometry::Tiles { count: tiles },
210        min_bytes,
211        len,
212    ))
213}
214
215/// Most rows `len` bytes of CCITT data can code: every row takes at least
216/// one bit, the 1-bit V0 code of T.6 Table 1 (the shortest code word of
217/// T.4 and T.6), so `8 * len + 1` with one row of slack.
218pub(crate) fn ccitt_max_rows(len: usize) -> u64 {
219    u64::try_from(len)
220        .unwrap_or(u64::MAX)
221        .saturating_mul(8)
222        .saturating_add(1)
223}
224
225/// CCITT evidence: a declared row count must fit [`ccitt_max_rows`].
226///
227/// # Errors
228///
229/// [`ImageCodecError::DeclaredGeometryExceedsData`] when it does not.
230pub(crate) fn ccitt_rows(rows: u32, len: usize) -> Result<(), ImageCodecError> {
231    if u64::from(rows) <= ccitt_max_rows(len) {
232        return Ok(());
233    }
234    let min_bytes = u64::from(rows - 1).div_ceil(8);
235    Err(refuse(
236        Codec::Ccitt,
237        DeclaredGeometry::Rows { rows },
238        min_bytes,
239        len,
240    ))
241}