1pub(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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48#[non_exhaustive]
49pub struct DecodeLimits {
50 pub memory_budget: u64,
53 pub max_pixels: Option<u64>,
56 pub downstream_bytes_per_pixel: u64,
59}
60
61impl DecodeLimits {
62 pub const FALLBACK_MEMORY_BUDGET: u64 = if cfg!(target_pointer_width = "64") {
65 4 << 30
66 } else {
67 1 << 30
68 };
69
70 #[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 #[must_use]
83 pub const fn for_physical_memory(physical_bytes: u64) -> Self {
84 Self::new(physical_bytes / 2)
85 }
86
87 #[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 #[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 fn default() -> Self {
105 Self::new(Self::FALLBACK_MEMORY_BUDGET)
106 }
107}
108
109const FIXED_OVERHEAD: u64 = 128 << 10;
113
114const RECORD_OVERHEAD: u64 = 1 << 10;
116
117const FLATE_CHUNK: u64 = 64 << 10;
120
121#[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#[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
189fn 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
227fn 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
237fn 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
247pub(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
254pub(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
288pub(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
302pub(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
308fn len<T>(s: &[T]) -> u64 {
310 u64::try_from(s.len()).unwrap_or(u64::MAX)
311}
312
313fn 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}