Skip to main content

pdf2_render/
image.rs

1//! Image XObjects: decode an 8-bit image, then sample it into the canvas.
2
3use pdf2::{Dictionary, Document, Object, Stream};
4
5use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
6use crate::geom::{Matrix, Point};
7use crate::{Error, Result};
8
9/// A decoded image: width, height and one colour per pixel, top row first.
10#[derive(Debug, Clone)]
11pub struct Image {
12    width: u32,
13    height: u32,
14    pixels: Vec<Color>,
15    interpolate: bool,
16    /// Per source pixel: masked by a colour key (`8.9.6.4`), and so not painted.
17    masked: Option<Vec<bool>>,
18}
19
20impl Image {
21    /// Decode an `/Image` XObject.
22    ///
23    /// Supports 8 bits per component, `DeviceGray`/`DeviceRGB`/`DeviceCMYK`,
24    /// `Indexed` images with those bases, and `ICCBased` streams by component
25    /// count. Anything else is reported rather than guessed.
26    pub fn from_stream(
27        document: &Document,
28        stream: &Stream,
29        id: Option<pdf2::ObjectId>,
30    ) -> Result<Self> {
31        let dict = stream.dict();
32        // `/JPXDecode` and `/JBIG2Decode` carry their own colour space and bit
33        // depth: `/ColorSpace` may be absent from a JPX image and its
34        // `/BitsPerComponent` is ignored (7.4.9), so the dispatch has to happen
35        // before either is read. A codec that is not compiled in is reported by
36        // name there, because the alternative is a page that silently loses its
37        // image.
38        if is_jpx(dict) {
39            return Self::from_jpx(document, stream, id);
40        }
41        if is_jbig2(dict) {
42            return Self::from_jbig2(document, stream, id);
43        }
44        let width = integer(dict, b"Width")?;
45        let height = integer(dict, b"Height")?;
46        if width == 0 || height == 0 {
47            return Err(Error::malformed("image with zero width or height"));
48        }
49        let bits = dict
50            .get(b"BitsPerComponent")
51            .and_then(Object::as_integer)
52            .unwrap_or(8);
53        // One bit per component is how every fax image arrives; the packed rows
54        // are widened to bytes here so the sampler below has one path.
55        if bits != 8 && bits != 1 {
56            return Err(Error::malformed(
57                "only 1 and 8 bits per component images are rendered",
58            ));
59        }
60        let interpolate = matches!(dict.get(b"Interpolate"), Some(Object::Boolean(true)));
61        let space = resolve(document, dict.get(b"ColorSpace"))?;
62        // The colour space is dictionary metadata, so the size the image claims
63        // is known before its stream is touched — and that is the order that
64        // keeps a lying /Width from being paid for. Every component is one byte
65        // here (8 bits per component is the only depth drawn), so the decoded
66        // size is width × height × components.
67        let colours = ColourSpace::from_object(document, space)?;
68        let per_pixel = colours.components();
69        let count = (width as usize)
70            .checked_mul(height as usize)
71            .and_then(|pixels| pixels.checked_mul(per_pixel))
72            .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
73        let limit = document.decoded_limit();
74        if count > limit {
75            return Err(Error::Limit {
76                what: "an image of the /Width and /Height it declares",
77                limit,
78            });
79        }
80        // A colour key is tested on the samples *before* `/Decode` (8.9.6.4), so
81        // it is read here, and two forms are refused by name rather than ignored:
82        // the clause forbids `/DCTDecode` with a key, and a `/Mask` that is a
83        // stream is a stencil image (8.9.6.3), a different mechanism.
84        let key = match dict.get(b"Mask") {
85            None => None,
86            Some(Object::Array(items)) => Some(ColourKey::parse(items, per_pixel, bits)?),
87            Some(Object::Reference(_)) => {
88                return Err(Error::Unsupported {
89                    what: "a /Mask image stencil",
90                });
91            }
92            Some(_) => {
93                return Err(Error::malformed(
94                    "a /Mask that is neither an array nor a stream",
95                ));
96            }
97        };
98        if key.is_some() && is_dct(dict) {
99            return Err(Error::Unsupported {
100                what: "colour-key /Mask on a /DCTDecode image",
101            });
102        }
103        if is_dct(dict) {
104            return Self::from_dct(document, stream, id, interpolate);
105        }
106        let decoded = document.decode_stream(stream)?;
107        let data = if bits == 1 {
108            widen_one_bit(&decoded, width, height, per_pixel)?
109        } else {
110            decoded
111        };
112        if data.len() < count {
113            return Err(Error::Malformed {
114                what: "image data is shorter than width × height × components",
115                offset: None,
116            });
117        }
118        // `/Decode` remaps every sample before the colour space sees it; the
119        // default is the identity, and `[1 0]` per component is an inversion
120        // (8.9.5.2).
121        let masked = key.map(|key| {
122            data.chunks_exact(per_pixel)
123                .map(|sample| key.masks(sample))
124                .collect::<Vec<bool>>()
125        });
126        let decode = decode_ranges(dict.get(b"Decode"), per_pixel);
127        let mut pixels = Vec::with_capacity((width as usize) * (height as usize));
128        for index in (0..count).step_by(per_pixel) {
129            let sample = &data[index..index + per_pixel];
130            let mut components = [0.0_f64; 4];
131            for (slot, byte) in sample.iter().enumerate().take(per_pixel) {
132                let (from, to) = decode[slot];
133                components[slot] = (from + f64::from(*byte) / 255.0 * (to - from)).clamp(0.0, 1.0);
134            }
135            pixels.push(colour_at(&colours, &components));
136        }
137        Ok(Self {
138            width,
139            height,
140            pixels,
141            interpolate,
142            masked,
143        })
144    }
145
146    /// Decode a `/DCTDecode` image through `zune-jpeg`.
147    ///
148    /// A JPEG in a PDF has no leading filters to unwind, so the bytes come
149    /// straight from [`Document::stream_bytes`] — decrypted, not decoded — and
150    /// `zune-jpeg` converts YCbCr to RGB itself. The size is checked against the
151    /// budget twice: once from the dictionary, and once from the JPEG's own
152    /// header, because the header is the authority on what the decoder produces.
153    #[cfg(feature = "dct")]
154    fn from_dct(
155        document: &Document,
156        _stream: &Stream,
157        id: Option<pdf2::ObjectId>,
158        interpolate: bool,
159    ) -> Result<Self> {
160        let Some(id) = id else {
161            return Err(Error::malformed(
162                "a /DCTDecode image without an object number",
163            ));
164        };
165        let data = document.stream_bytes(id)?;
166        // PDF 7.4.8: a four-component JPEG from an Adobe writer stores its CMYK
167        // samples **inverted** (255 - sample), and its `/Decode` array — when the
168        // writer states one — is the same statement in words. Asking the decoder
169        // for CMYK rather than RGB is what makes the inversion possible: its RGB
170        // conversion assumes the already-uninverted order and comes out black.
171        let cmyk = dict_component_count(_stream) == Some(4);
172        let mut decoder =
173            zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&data));
174        if cmyk {
175            decoder.set_options(
176                zune_jpeg::zune_core::options::DecoderOptions::default()
177                    .jpeg_set_out_colorspace(zune_jpeg::zune_core::colorspace::ColorSpace::CMYK),
178            );
179        }
180        let pixels = decoder
181            .decode()
182            .map_err(|_| Error::malformed("/DCTDecode payload"))?;
183        let Some(info) = decoder.info() else {
184            return Err(Error::malformed(
185                "/DCTDecode payload without a frame header",
186            ));
187        };
188        let components = match decoder.output_colorspace() {
189            Some(zune_jpeg::zune_core::colorspace::ColorSpace::Luma) => 1,
190            Some(zune_jpeg::zune_core::colorspace::ColorSpace::CMYK) => 4,
191            _ => 3,
192        };
193        let count = usize::from(info.width)
194            .checked_mul(usize::from(info.height))
195            .and_then(|samples| samples.checked_mul(components))
196            .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
197        let limit = document.decoded_limit();
198        if count > limit {
199            return Err(Error::Limit {
200                what: "a /DCTDecode image of the size its header declares",
201                limit,
202            });
203        }
204        if pixels.len() < count {
205            return Err(Error::malformed(
206                "/DCTDecode payload is shorter than its header",
207            ));
208        }
209        // The Adobe inversion is applied here only when the writer did not state
210        // it as `/Decode`: the two are the same statement, and applying both
211        // would invert twice (which is what pdf.js does, and what
212        // `cmykjpeg.pdf` — an Adobe APP14 all-zero transform with no `/Decode` —
213        // needs).
214        let stated_decode = _stream.dict().get(b"Decode").is_some();
215        let invert = cmyk && !stated_decode && has_adobe_marker(&data);
216        // A `/Decode` array, when the writer states one, is applied to the samples
217        // after the Adobe inversion; when it inverts, the two cancel out.
218        let decode = decode_ranges(_stream.dict().get(b"Decode"), components);
219        let sample = |bytes: &[u8]| -> Vec<f64> {
220            bytes
221                .iter()
222                .enumerate()
223                .map(|(index, byte)| {
224                    let value = f64::from(*byte) / 255.0;
225                    let (from, to) = decode[index.min(decode.len() - 1)];
226                    (from + value * (to - from)).clamp(0.0, 1.0)
227                })
228                .collect()
229        };
230        let pixels = pixels[..count]
231            .chunks_exact(components)
232            .map(|bytes| {
233                let bytes: Vec<u8> = if invert {
234                    bytes.iter().map(|byte| 255 - byte).collect()
235                } else {
236                    bytes.to_vec()
237                };
238                let values = sample(&bytes);
239                match components {
240                    1 => Color::rgb(values[0], values[0], values[0]),
241                    4 => Color::from_cmyk(values[0], values[1], values[2], values[3]),
242                    _ => Color::rgb(values[0], values[1], values[2]),
243                }
244            })
245            .collect();
246        Ok(Self {
247            width: u32::from(info.width),
248            height: u32::from(info.height),
249            pixels,
250            interpolate,
251            // A `/DCTDecode` image with a key is refused above, so there is
252            // never a mask to carry here.
253            masked: None,
254        })
255    }
256
257    /// Without the feature a JPEG is reported, not guessed at.
258    #[cfg(not(feature = "dct"))]
259    fn from_dct(
260        _document: &Document,
261        _stream: &Stream,
262        _id: Option<pdf2::ObjectId>,
263        _interpolate: bool,
264    ) -> Result<Self> {
265        Err(Error::Unsupported {
266            what: "/DCTDecode images (build with the `dct` feature)",
267        })
268    }
269
270    /// A `/JPXDecode` image without the feature is reported by name.
271    #[cfg(not(feature = "jpx"))]
272    fn from_jpx(
273        _document: &Document,
274        _stream: &Stream,
275        _id: Option<pdf2::ObjectId>,
276    ) -> Result<Self> {
277        Err(Error::Unsupported {
278            what: "/JPXDecode images (build with the `jpx` feature)",
279        })
280    }
281
282    /// A `/JPXDecode` image with the feature: the codestream decides the size,
283    /// the colour space and the depth (7.4.9), so all three come from its header
284    /// and the budget is checked before a pixel is decoded.
285    #[cfg(feature = "jpx")]
286    fn from_jpx(document: &Document, stream: &Stream, id: Option<pdf2::ObjectId>) -> Result<Self> {
287        let Some(id) = id else {
288            return Err(Error::malformed(
289                "a /JPXDecode image without an object number",
290            ));
291        };
292        let interpolate = matches!(
293            stream.dict().get(b"Interpolate"),
294            Some(Object::Boolean(true))
295        );
296        let data = document.stream_bytes(id)?;
297        let image = hayro_jpeg2000::Image::new(&data, &hayro_jpeg2000::DecodeSettings::default())
298            .map_err(|_| Error::malformed("/JPXDecode codestream"))?;
299        // An alpha channel and an ICC or unknown colour space are refused by
300        // name rather than guessed at: the first needs a soft mask this renderer
301        // does not carry, and the other two need colour management it does not do.
302        if image.has_alpha() {
303            return Err(Error::Unsupported {
304                what: "a /JPXDecode image with an alpha channel",
305            });
306        }
307        let components = jpx_components(image.color_space())?;
308        let width = image.width();
309        let height = image.height();
310        let count = (width as usize)
311            .checked_mul(height as usize)
312            .and_then(|pixels| pixels.checked_mul(components))
313            .ok_or_else(|| Error::malformed("/JPXDecode image dimensions overflow"))?;
314        let limit = document.decoded_limit();
315        if count > limit {
316            return Err(Error::Limit {
317                what: "a /JPXDecode image of the size its codestream declares",
318                limit,
319            });
320        }
321        // `/Decode` is not part of the JPX model — the codestream carries its own
322        // sample range — so the samples are used as they come.
323        let mut context = hayro_jpeg2000::DecoderContext::default();
324        let decoded = image
325            .decode(&mut context)
326            .map_err(|_| Error::malformed("/JPXDecode payload"))?;
327        let samples = decoded.data_u8();
328        if samples.len() < count {
329            return Err(Error::malformed(
330                "/JPXDecode payload is shorter than its header",
331            ));
332        }
333        let sample = |byte: u8| f64::from(byte) / 255.0;
334        let pixels = samples[..count]
335            .chunks_exact(components)
336            .map(|bytes| match components {
337                1 => {
338                    let grey = sample(bytes[0]);
339                    Color::rgb(grey, grey, grey)
340                }
341                4 => Color::from_cmyk(
342                    sample(bytes[0]),
343                    sample(bytes[1]),
344                    sample(bytes[2]),
345                    sample(bytes[3]),
346                ),
347                _ => Color::rgb(sample(bytes[0]), sample(bytes[1]), sample(bytes[2])),
348            })
349            .collect();
350        Ok(Self {
351            width,
352            height,
353            pixels,
354            interpolate,
355            masked: None,
356        })
357    }
358
359    /// A `/JBIG2Decode` image without the feature is reported by name.
360    #[cfg(not(feature = "jbig2"))]
361    fn from_jbig2(
362        _document: &Document,
363        _stream: &Stream,
364        _id: Option<pdf2::ObjectId>,
365    ) -> Result<Self> {
366        Err(Error::Unsupported {
367            what: "/JBIG2Decode images (build with the `jbig2` feature)",
368        })
369    }
370
371    /// A `/JBIG2Decode` image with the feature: the page information decides the
372    /// size, and `/DecodeParms /JBIG2Globals` may carry shared segments that must
373    /// be decoded before the page's own (7.4.7).
374    #[cfg(feature = "jbig2")]
375    fn from_jbig2(
376        document: &Document,
377        stream: &Stream,
378        id: Option<pdf2::ObjectId>,
379    ) -> Result<Self> {
380        let Some(id) = id else {
381            return Err(Error::malformed(
382                "a /JBIG2Decode image without an object number",
383            ));
384        };
385        let interpolate = matches!(
386            stream.dict().get(b"Interpolate"),
387            Some(Object::Boolean(true))
388        );
389        let settings = hayro_jbig2::DecodeSettings::default();
390        // The globals are a *separate* stream: `/DecodeParms /JBIG2Globals` names
391        // it, and its segments have to be decoded before the image's own. A page
392        // wired only to `new_embedded(data, None, …)` fails on exactly these files.
393        let globals = match globals_bytes(document, stream.dict())? {
394            Some(bytes) => Some(
395                hayro_jbig2::Globals::new(&bytes, &settings)
396                    .map_err(|_| Error::malformed("/JBIG2Decode globals stream"))?,
397            ),
398            None => None,
399        };
400        let data = document.stream_bytes(id)?;
401        let page = hayro_jbig2::Page::new_embedded(&data, globals.as_ref(), &settings)
402            .map_err(|_| Error::malformed("/JBIG2Decode page"))?;
403        let width = page.width();
404        let height = page.height();
405        let count = (width as usize)
406            .checked_mul(height as usize)
407            .ok_or_else(|| Error::malformed("/JBIG2Decode image dimensions overflow"))?;
408        let limit = document.decoded_limit();
409        if count > limit {
410            return Err(Error::Limit {
411                what: "a /JBIG2Decode image of the size its page information declares",
412                limit,
413            });
414        }
415        let mut rows = Rows::new(width as usize, height as usize);
416        page.decode(&mut rows)
417            .map_err(|_| Error::malformed("/JBIG2Decode payload"))?;
418        let widened = widen_one_bit(&rows.finish(), width, height, 1)?;
419        // `/Decode` remaps the samples before the colour space sees them (8.9.5.2),
420        // and a 1-bit scan is exactly where a writer states `[1 0]` — the CCITT and
421        // DCT paths applied it from the start, this one did not, so such an image
422        // drew as its negative: white text on a black page.
423        let decode = decode_ranges(stream.dict().get(b"Decode"), 1);
424        let (from, to) = decode[0];
425        let pixels = widened
426            .into_iter()
427            .map(|sample| {
428                let value = f64::from(sample) / 255.0;
429                let grey = (from + value * (to - from)).clamp(0.0, 1.0);
430                Color::rgb(grey, grey, grey)
431            })
432            .collect();
433        Ok(Self {
434            width,
435            height,
436            pixels,
437            interpolate,
438            masked: None,
439        })
440    }
441
442    /// Whether the source sample nearest to `(u, v)` is hidden by the colour key.
443    fn is_masked(&self, u: f64, v: f64) -> bool {
444        let Some(masked) = &self.masked else {
445            return false;
446        };
447        if self.width == 0 || self.height == 0 {
448            return false;
449        }
450        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
451        let x = (u.clamp(0.0, 1.0) * f64::from(self.width)) as u32;
452        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
453        let y = (v.clamp(0.0, 1.0) * f64::from(self.height)) as u32;
454        let x = x.min(self.width - 1);
455        let y = y.min(self.height - 1);
456        masked
457            .get((y * self.width + x) as usize)
458            .copied()
459            .unwrap_or(false)
460    }
461
462    /// Width in samples.
463    pub fn width(&self) -> u32 {
464        self.width
465    }
466
467    /// Height in samples.
468    pub fn height(&self) -> u32 {
469        self.height
470    }
471
472    /// The colour at a sample position, nearest or bilinear.
473    pub fn sample(&self, u: f64, v: f64) -> Color {
474        if self.width == 0 || self.height == 0 {
475            return Color::WHITE;
476        }
477        let x = (u.clamp(0.0, 1.0) * f64::from(self.width) - 0.5).max(0.0);
478        let y = (v.clamp(0.0, 1.0) * f64::from(self.height) - 0.5).max(0.0);
479        if !self.interpolate {
480            return self.pixel(x.round() as u32, y.round() as u32);
481        }
482        let x0 = x.floor() as u32;
483        let y0 = y.floor() as u32;
484        let x1 = (x0 + 1).min(self.width - 1);
485        let y1 = (y0 + 1).min(self.height - 1);
486        let fx = x - f64::from(x0);
487        let fy = y - f64::from(y0);
488        let top = mix(self.pixel(x0, y0), self.pixel(x1, y0), fx);
489        let bottom = mix(self.pixel(x0, y1), self.pixel(x1, y1), fx);
490        mix(top, bottom, fy)
491    }
492
493    fn pixel(&self, x: u32, y: u32) -> Color {
494        let x = x.min(self.width - 1);
495        let y = y.min(self.height - 1);
496        self.pixels[(y as usize) * (self.width as usize) + (x as usize)]
497    }
498
499    /// Paint into the canvas through `ctm`, restricted to `mask`.
500    pub fn paint(
501        &self,
502        canvas: &mut Canvas,
503        mask: &ClipMask,
504        ctm: Matrix,
505        alpha: f64,
506        mode: BlendMode,
507    ) {
508        let Some(inverse) = ctm.invert() else {
509            return;
510        };
511        let corners = [
512            ctm.apply(Point::new(0.0, 0.0)),
513            ctm.apply(Point::new(1.0, 0.0)),
514            ctm.apply(Point::new(0.0, 1.0)),
515            ctm.apply(Point::new(1.0, 1.0)),
516        ];
517        let min_x = corners
518            .iter()
519            .fold(f64::INFINITY, |min, point| min.min(point.x))
520            .floor()
521            .max(0.0);
522        let max_x = corners
523            .iter()
524            .fold(f64::NEG_INFINITY, |max, point| max.max(point.x))
525            .ceil()
526            .min(f64::from(canvas.width()));
527        let min_y = corners
528            .iter()
529            .fold(f64::INFINITY, |min, point| min.min(point.y))
530            .floor()
531            .max(0.0);
532        let max_y = corners
533            .iter()
534            .fold(f64::NEG_INFINITY, |max, point| max.max(point.y))
535            .ceil()
536            .min(f64::from(canvas.height()));
537        for y in min_y as u32..max_y as u32 {
538            for x in min_x as u32..max_x as u32 {
539                let coverage = mask.alpha(x, y);
540                if coverage <= 0.0 {
541                    continue;
542                }
543                let device = Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5);
544                let user = inverse.apply(device);
545                if !(0.0..=1.0).contains(&user.x) || !(0.0..=1.0).contains(&user.y) {
546                    continue;
547                }
548                // Image space has its origin at the bottom-left, but the first
549                // sample row is the top one.
550                let v = 1.0 - user.y;
551                if self.is_masked(user.x, v) {
552                    // "Samples in the image that fall within this range shall not
553                    // be painted, allowing the existing background to show
554                    // through" (8.9.6.4): skipped, not blended.
555                    continue;
556                }
557                let colour = self.sample(user.x, v);
558                canvas.blend_with(x, y, colour, alpha * coverage, mode);
559            }
560        }
561    }
562}
563
564/// A colour key (`8.9.6.4`): samples whose every component falls in its range,
565/// **before** `/Decode`, are not painted.
566///
567/// The clause's ranges are inclusive: `colorkeymask.pdf` writes `min == max` for
568/// the red it wants hidden, which an exclusive reading would never mask.
569#[derive(Debug, Clone, PartialEq, Eq)]
570struct ColourKey {
571    min: [u8; 4],
572    max: [u8; 4],
573    components: usize,
574}
575
576impl ColourKey {
577    /// Read a `/Mask` array: `2 × n` integers in `0 … 2^bits − 1`, mapped onto the
578    /// byte values the samples are widened to (1-bit samples become 0/255).
579    fn parse(items: &[Object], components: usize, bits: i64) -> Result<Self> {
580        if items.len() != components * 2 {
581            return Err(Error::malformed(
582                "a /Mask whose length is not twice the image's component count",
583            ));
584        }
585        let scale = if bits == 1 { 255.0 } else { 1.0 };
586        let limit = if bits == 1 { 1.0 } else { 255.0 };
587        let mut min = [0_u8; 4];
588        let mut max = [0_u8; 4];
589        for slot in 0..components {
590            let low = items[slot * 2].as_real().unwrap_or(-1.0);
591            let high = items[slot * 2 + 1].as_real().unwrap_or(-1.0);
592            if !(0.0..=limit).contains(&low) || !(0.0..=limit).contains(&high) {
593                return Err(Error::malformed("a /Mask value outside the sample range"));
594            }
595            min[slot] = (low * scale).round() as u8;
596            max[slot] = (high * scale).round() as u8;
597        }
598        Ok(Self {
599            min,
600            max,
601            components,
602        })
603    }
604
605    /// Whether a sample falls inside the key on every component.
606    fn masks(&self, sample: &[u8]) -> bool {
607        sample
608            .iter()
609            .take(self.components)
610            .enumerate()
611            .all(|(slot, byte)| (self.min[slot]..=self.max[slot]).contains(byte))
612    }
613}
614
615/// The `/Decode` range for each component, defaulting to the identity.
616fn decode_ranges(decode: Option<&Object>, components: usize) -> Vec<(f64, f64)> {
617    let mut ranges = vec![(0.0, 1.0); components];
618    let Some(Object::Array(items)) = decode else {
619        return ranges;
620    };
621    if items.len() < components * 2 {
622        return ranges;
623    }
624    for (slot, pair) in items.as_chunks::<2>().0.iter().enumerate().take(components) {
625        let (Some(from), Some(to)) = (pair[0].as_real(), pair[1].as_real()) else {
626            continue;
627        };
628        ranges[slot] = (from, to);
629    }
630    ranges
631}
632
633/// Turn decoded components (0–1 each) into a colour through `colours`.
634fn colour_at(colours: &ColourSpace, components: &[f64; 4]) -> Color {
635    match colours {
636        ColourSpace::Gray => Color::rgb(components[0], components[0], components[0]),
637        ColourSpace::Rgb => Color::rgb(components[0], components[1], components[2]),
638        ColourSpace::Cmyk => {
639            Color::from_cmyk(components[0], components[1], components[2], components[3])
640        }
641        ColourSpace::Indexed { base, lookup } => {
642            // For an indexed image the decoded value is the index, not a colour
643            // component, so it is scaled back into the table's range.
644            let index = (components[0] * 255.0).round().max(0.0) as usize;
645            let count = base.components();
646            let entry = index * count;
647            let slice = lookup.get(entry..entry + count).unwrap_or(&[]);
648            if slice.len() < count {
649                return Color::BLACK;
650            }
651            let mut table = [0.0_f64; 4];
652            for (slot, byte) in slice.iter().enumerate().take(4) {
653                table[slot] = f64::from(*byte) / 255.0;
654            }
655            colour_at(base, &table)
656        }
657    }
658}
659
660fn mix(left: Color, right: Color, t: f64) -> Color {
661    let t = t.clamp(0.0, 1.0);
662    Color::rgb(
663        left.r * (1.0 - t) + right.r * t,
664        left.g * (1.0 - t) + right.g * t,
665        left.b * (1.0 - t) + right.b * t,
666    )
667}
668
669/// The colour space of an image, resolved to what the sampler needs.
670#[derive(Debug, Clone, PartialEq)]
671enum ColourSpace {
672    Gray,
673    Rgb,
674    Cmyk,
675    Indexed {
676        base: Box<ColourSpace>,
677        lookup: Vec<u8>,
678    },
679}
680
681impl ColourSpace {
682    fn from_object(document: &Document, object: Object) -> Result<Self> {
683        match object {
684            Object::Name(name) => match name.as_slice() {
685                b"DeviceGray" | b"G" | b"CalGray" => Ok(Self::Gray),
686                b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(Self::Rgb),
687                b"DeviceCMYK" | b"CMYK" => Ok(Self::Cmyk),
688                _ => Err(Error::malformed("unsupported image /ColorSpace")),
689            },
690            Object::Array(items) => {
691                let family = match items.first() {
692                    Some(Object::Name(name)) => name.clone(),
693                    _ => return Err(Error::malformed("image /ColorSpace array family")),
694                };
695                match family.as_slice() {
696                    b"Indexed" | b"I" => {
697                        let base = match items.get(1) {
698                            Some(base) => {
699                                Self::from_object(document, resolve(document, Some(base))?)?
700                            }
701                            None => return Err(Error::malformed("Indexed image without a base")),
702                        };
703                        let lookup = match items.get(3) {
704                            Some(Object::String(string)) => string.as_bytes().to_vec(),
705                            Some(Object::Reference(id)) => document.stream_data(*id)?,
706                            _ => {
707                                return Err(Error::malformed(
708                                    "Indexed image without a lookup table",
709                                ));
710                            }
711                        };
712                        Ok(Self::Indexed {
713                            base: Box::new(base),
714                            lookup,
715                        })
716                    }
717                    b"ICCBased" => {
718                        // One resolver for paints and images: `/N` decides the
719                        // sample count, and `/Alternate` is the writer's fallback
720                        // when it is a count this renderer cannot name.
721                        match crate::shading::icc_components(document, &items)? {
722                            crate::shading::Space::Gray => Ok(Self::Gray),
723                            crate::shading::Space::Rgb => Ok(Self::Rgb),
724                            crate::shading::Space::Cmyk => Ok(Self::Cmyk),
725                            _ => Err(Error::Unsupported {
726                                what: "an /ICCBased image in a tint space",
727                            }),
728                        }
729                    }
730                    _ => Err(Error::malformed("unsupported image /ColorSpace array")),
731                }
732            }
733            _ => Err(Error::malformed("unsupported image /ColorSpace value")),
734        }
735    }
736
737    fn components(&self) -> usize {
738        match self {
739            Self::Gray => 1,
740            Self::Rgb => 3,
741            Self::Cmyk => 4,
742            Self::Indexed { .. } => 1,
743        }
744    }
745}
746
747fn integer(dict: &Dictionary, key: &[u8]) -> Result<u32> {
748    dict.get(key)
749        .and_then(Object::as_integer)
750        .and_then(|value| u32::try_from(value).ok())
751        .ok_or_else(|| Error::malformed("image without integer /Width and /Height"))
752}
753
754/// How many components the stream's `/ColorSpace` declares, when it is a name or
755/// a known family — enough to know whether a JPEG is CMYK.
756fn dict_component_count(stream: &Stream) -> Option<usize> {
757    match stream.dict().get(b"ColorSpace") {
758        Some(Object::Name(name)) if name == b"DeviceCMYK" => Some(4),
759        Some(Object::Name(name)) if name == b"DeviceGray" => Some(1),
760        Some(Object::Name(name)) if name == b"DeviceRGB" => Some(3),
761        _ => None,
762    }
763}
764
765/// Widen packed one-bit samples to one byte each, 0 or 255.
766///
767/// PDF pads each row to a byte boundary, so a 1728-pixel fax line occupies 216
768/// bytes; a row shorter than its padding is malformed rather than merely short.
769fn widen_one_bit(data: &[u8], width: u32, height: u32, components: usize) -> Result<Vec<u8>> {
770    if components != 1 {
771        return Err(Error::malformed(
772            "one-bit samples need a single-component colour space",
773        ));
774    }
775    let bits_per_row = usize::try_from(width).unwrap_or(0);
776    let stride = bits_per_row.div_ceil(8);
777    let rows = usize::try_from(height).unwrap_or(0);
778    if data.len() < stride.saturating_mul(rows) {
779        return Err(Error::malformed(
780            "one-bit image data is shorter than its rows",
781        ));
782    }
783    let mut out = Vec::with_capacity(bits_per_row.saturating_mul(rows));
784    for row in 0..rows {
785        for column in 0..bits_per_row {
786            let byte = data[row * stride + column / 8];
787            let shift = 7 - column % 8;
788            let bit = (byte >> shift) & 1;
789            out.push(if bit == 1 { 255 } else { 0 });
790        }
791    }
792    Ok(out)
793}
794
795/// Whether a JPEG carries an Adobe APP14 marker, which is what makes its CMYK
796/// samples stored inverted (PDF 7.4.8).
797///
798/// The marker is `FFEE` then a two-byte length and the identifier `Adobe`; only
799/// the identifier matters here, because the transform byte says whether the
800/// samples are plain CMYK or YCCK, and both are stored inverted.
801fn has_adobe_marker(data: &[u8]) -> bool {
802    let mut index = 2; // past the `FF D8` start-of-image marker
803    while index + 4 <= data.len() {
804        if data[index] != 0xFF {
805            return false;
806        }
807        let marker = data[index + 1];
808        // Segments with no payload.
809        if matches!(marker, 0xD8 | 0x01 | 0xD0..=0xD7) {
810            index += 2;
811            continue;
812        }
813        let length = usize::from(u16::from_be_bytes([data[index + 2], data[index + 3]]));
814        if length < 2 {
815            return false;
816        }
817        if marker == 0xEE {
818            let payload = &data[index + 4..(index + 2 + length).min(data.len())];
819            return payload.starts_with(b"Adobe");
820        }
821        // Start of scan: no more header segments follow.
822        if marker == 0xDA {
823            return false;
824        }
825        index += 2 + length;
826    }
827    false
828}
829
830/// Whether the stream's filter chain ends in `name`.
831fn ends_in(dict: &Dictionary, name: &[u8]) -> bool {
832    match dict.get(b"Filter") {
833        Some(Object::Name(filter)) => filter == name,
834        Some(Object::Array(items)) => items
835            .iter()
836            .rev()
837            .find_map(Object::as_name)
838            .is_some_and(|filter| filter == name),
839        _ => false,
840    }
841}
842
843/// Whether the stream's filter chain ends in `/DCTDecode`.
844fn is_dct(dict: &Dictionary) -> bool {
845    ends_in(dict, b"DCTDecode")
846}
847
848/// Whether the stream's filter chain ends in `/JPXDecode` (7.4.9).
849fn is_jpx(dict: &Dictionary) -> bool {
850    ends_in(dict, b"JPXDecode")
851}
852
853/// Whether the stream's filter chain ends in `/JBIG2Decode` (7.4.7).
854fn is_jbig2(dict: &Dictionary) -> bool {
855    ends_in(dict, b"JBIG2Decode")
856}
857
858/// Follow one indirect reference; deeper chains are not needed for images.
859pub(crate) fn resolve(document: &Document, object: Option<&Object>) -> Result<Object> {
860    match object {
861        Some(Object::Reference(id)) => document.get_object(*id),
862        Some(other) => Ok(other.clone()),
863        None => Ok(Object::Null),
864    }
865}
866
867/// How many components a JPX colour space needs, or why it is refused.
868///
869/// `/JPXDecode` takes its colour space from the codestream (7.4.9), and this
870/// renderer can paint grey, RGB and CMYK. An ICC or unnamed space would need
871/// colour management, so it is reported by name instead of mapped by component
872/// count — the failure mode that guesses is the one that draws a wrong colour
873/// with full confidence.
874#[cfg(feature = "jpx")]
875fn jpx_components(space: &hayro_jpeg2000::ColorSpace) -> Result<usize> {
876    match space {
877        hayro_jpeg2000::ColorSpace::Gray => Ok(1),
878        hayro_jpeg2000::ColorSpace::RGB => Ok(3),
879        hayro_jpeg2000::ColorSpace::CMYK => Ok(4),
880        hayro_jpeg2000::ColorSpace::Icc { .. } => Err(Error::Unsupported {
881            what: "a /JPXDecode image in an ICC colour space",
882        }),
883        hayro_jpeg2000::ColorSpace::Unknown { .. } => Err(Error::Unsupported {
884            what: "a /JPXDecode image in a colour space it cannot name",
885        }),
886    }
887}
888
889/// Resolves the `/JBIG2Globals` stream of a `/JBIG2Decode` image, if it names one.
890#[cfg(feature = "jbig2")]
891fn globals_bytes(document: &Document, dict: &Dictionary) -> Result<Option<Vec<u8>>> {
892    let Some(parms) = dict.get(b"DecodeParms") else {
893        return Ok(None);
894    };
895    let parms = resolve(document, Some(parms))?;
896    let Some(parms) = parms.as_dict() else {
897        return Ok(None);
898    };
899    let Some(globals) = parms.get(b"JBIG2Globals") else {
900        return Ok(None);
901    };
902    let globals = resolve(document, Some(globals))?;
903    let Some(stream) = globals.as_stream() else {
904        return Err(Error::malformed("/JBIG2Globals is not a stream"));
905    };
906    document.decode_stream(stream).map(Some)
907}
908
909/// A JBIG2 sink that writes packed 1-bit rows the way a PDF image expects them.
910///
911/// `hayro-jbig2` reports `black`, and a 1-bit `/DeviceGray` sample is 1 for
912/// **white** unless `/Decode` inverts it (`src/fax.rs:37` and the CCITT writer
913/// beside it). Writing `black` straight through draws the page as its negative,
914/// which is why the tests assert ink on white instead of trusting the sense.
915#[cfg(feature = "jbig2")]
916struct Rows {
917    packed: Vec<u8>,
918    /// Bytes per row: a 1-bit PDF image is **row-aligned to a byte**, so a row of
919    /// 399 pixels occupies 50 bytes and leaves one bit of padding.
920    stride: usize,
921    row: usize,
922    column: usize,
923}
924
925#[cfg(feature = "jbig2")]
926impl Rows {
927    fn new(width: usize, height: usize) -> Self {
928        Self {
929            packed: vec![0; width.div_ceil(8) * height],
930            stride: width.div_ceil(8),
931            row: 0,
932            column: 0,
933        }
934    }
935
936    /// Write `count` samples of one value, MSB first, in the current row.
937    ///
938    /// The row offset is what makes this a PDF image rather than a bit stream: with
939    /// a width that is not a multiple of eight, packing the pixels contiguously
940    /// shifts every row by one bit, which is a defect this sink had — it cost
941    /// 19 553 differing pixels against pdfium's reference raster (12.25 %, mean
942    /// |Δ| 31.24) while the decoder's own output was byte-exact.
943    fn run(&mut self, white: bool, count: usize) {
944        for _ in 0..count {
945            if white {
946                let byte = self.row * self.stride + self.column / 8;
947                let shift = 7 - self.column % 8;
948                if let Some(slot) = self.packed.get_mut(byte) {
949                    *slot |= 1 << shift;
950                }
951            }
952            self.column += 1;
953        }
954    }
955
956    fn finish(self) -> Vec<u8> {
957        self.packed
958    }
959}
960
961#[cfg(feature = "jbig2")]
962impl hayro_jbig2::Decoder for Rows {
963    fn push_pixel(&mut self, black: bool) {
964        self.run(!black, 1);
965    }
966
967    fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
968        self.run(!black, 8 * chunk_count as usize);
969    }
970
971    fn next_line(&mut self) {
972        self.row += 1;
973        self.column = 0;
974    }
975}
976
977#[cfg(test)]
978mod tests {
979    use super::Image;
980    use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
981    use crate::geom::Matrix;
982
983    /// A JPX colour space this renderer cannot honour is refused by name, not
984    /// mapped by component count: the guess is what draws a confident wrong
985    /// colour.
986    #[cfg(feature = "jpx")]
987    #[test]
988    fn jpx_refuses_the_colour_spaces_it_cannot_paint() {
989        use hayro_jpeg2000::ColorSpace;
990
991        assert_eq!(super::jpx_components(&ColorSpace::Gray).unwrap(), 1);
992        assert_eq!(super::jpx_components(&ColorSpace::RGB).unwrap(), 3);
993        assert_eq!(super::jpx_components(&ColorSpace::CMYK).unwrap(), 4);
994        let icc = super::jpx_components(&ColorSpace::Icc {
995            profile: Vec::new(),
996            num_channels: 3,
997        })
998        .expect_err("an ICC space needs colour management");
999        assert!(icc.to_string().contains("ICC"), "{icc}");
1000        let unknown = super::jpx_components(&ColorSpace::Unknown { num_channels: 2 })
1001            .expect_err("an unnamed space is refused");
1002        assert!(unknown.to_string().contains("cannot name"), "{unknown}");
1003    }
1004
1005    fn image(width: u32, height: u32, interpolate: bool) -> Image {
1006        let mut pixels = Vec::new();
1007        for y in 0..height {
1008            for x in 0..width {
1009                pixels.push(if (x + y) % 2 == 0 {
1010                    Color::BLACK
1011                } else {
1012                    Color::WHITE
1013                });
1014            }
1015        }
1016        Image {
1017            width,
1018            height,
1019            pixels,
1020            interpolate,
1021            masked: None,
1022        }
1023    }
1024
1025    #[test]
1026    fn nearest_sampling_returns_whole_pixels() {
1027        let image = image(2, 2, false);
1028        assert_eq!(image.sample(0.25, 0.25), Color::BLACK);
1029        assert_eq!(image.sample(0.75, 0.25), Color::WHITE);
1030        assert_eq!(image.sample(0.25, 0.75), Color::WHITE);
1031    }
1032
1033    #[test]
1034    fn bilinear_sampling_blends_neighbours() {
1035        let image = image(2, 2, true);
1036        let middle = image.sample(0.5, 0.5);
1037        assert!((middle.r - 0.5).abs() < 1e-9, "{middle:?}");
1038    }
1039
1040    #[test]
1041    fn painting_covers_the_unit_square_transform() {
1042        let image = image(2, 2, false);
1043        let mut canvas = Canvas::new(4, 4, Color::WHITE);
1044        let mask = ClipMask::all(4, 4);
1045        // Unit square scaled to 4×4 with y flipped like the page transform.
1046        let ctm = Matrix::new(4.0, 0.0, 0.0, -4.0, 0.0, 4.0);
1047        image.paint(&mut canvas, &mask, ctm, 1.0, BlendMode::Normal);
1048        assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
1049        assert_eq!(canvas.pixel(3, 0), Some([255, 255, 255, 255]));
1050        assert_eq!(canvas.pixel(0, 3), Some([255, 255, 255, 255]));
1051        assert_eq!(canvas.pixel(3, 3), Some([0, 0, 0, 255]));
1052    }
1053}