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