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