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        let pixels = widened
420            .into_iter()
421            .map(|sample| {
422                let grey = f64::from(sample) / 255.0;
423                Color::rgb(grey, grey, grey)
424            })
425            .collect();
426        Ok(Self {
427            width,
428            height,
429            pixels,
430            interpolate,
431            masked: None,
432        })
433    }
434
435    /// Whether the source sample nearest to `(u, v)` is hidden by the colour key.
436    fn is_masked(&self, u: f64, v: f64) -> bool {
437        let Some(masked) = &self.masked else {
438            return false;
439        };
440        if self.width == 0 || self.height == 0 {
441            return false;
442        }
443        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
444        let x = (u.clamp(0.0, 1.0) * f64::from(self.width)) as u32;
445        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
446        let y = (v.clamp(0.0, 1.0) * f64::from(self.height)) as u32;
447        let x = x.min(self.width - 1);
448        let y = y.min(self.height - 1);
449        masked
450            .get((y * self.width + x) as usize)
451            .copied()
452            .unwrap_or(false)
453    }
454
455    /// Width in samples.
456    pub fn width(&self) -> u32 {
457        self.width
458    }
459
460    /// Height in samples.
461    pub fn height(&self) -> u32 {
462        self.height
463    }
464
465    /// The colour at a sample position, nearest or bilinear.
466    pub fn sample(&self, u: f64, v: f64) -> Color {
467        if self.width == 0 || self.height == 0 {
468            return Color::WHITE;
469        }
470        let x = (u.clamp(0.0, 1.0) * f64::from(self.width) - 0.5).max(0.0);
471        let y = (v.clamp(0.0, 1.0) * f64::from(self.height) - 0.5).max(0.0);
472        if !self.interpolate {
473            return self.pixel(x.round() as u32, y.round() as u32);
474        }
475        let x0 = x.floor() as u32;
476        let y0 = y.floor() as u32;
477        let x1 = (x0 + 1).min(self.width - 1);
478        let y1 = (y0 + 1).min(self.height - 1);
479        let fx = x - f64::from(x0);
480        let fy = y - f64::from(y0);
481        let top = mix(self.pixel(x0, y0), self.pixel(x1, y0), fx);
482        let bottom = mix(self.pixel(x0, y1), self.pixel(x1, y1), fx);
483        mix(top, bottom, fy)
484    }
485
486    fn pixel(&self, x: u32, y: u32) -> Color {
487        let x = x.min(self.width - 1);
488        let y = y.min(self.height - 1);
489        self.pixels[(y as usize) * (self.width as usize) + (x as usize)]
490    }
491
492    /// Paint into the canvas through `ctm`, restricted to `mask`.
493    pub fn paint(
494        &self,
495        canvas: &mut Canvas,
496        mask: &ClipMask,
497        ctm: Matrix,
498        alpha: f64,
499        mode: BlendMode,
500    ) {
501        let Some(inverse) = ctm.invert() else {
502            return;
503        };
504        let corners = [
505            ctm.apply(Point::new(0.0, 0.0)),
506            ctm.apply(Point::new(1.0, 0.0)),
507            ctm.apply(Point::new(0.0, 1.0)),
508            ctm.apply(Point::new(1.0, 1.0)),
509        ];
510        let min_x = corners
511            .iter()
512            .fold(f64::INFINITY, |min, point| min.min(point.x))
513            .floor()
514            .max(0.0);
515        let max_x = corners
516            .iter()
517            .fold(f64::NEG_INFINITY, |max, point| max.max(point.x))
518            .ceil()
519            .min(f64::from(canvas.width()));
520        let min_y = corners
521            .iter()
522            .fold(f64::INFINITY, |min, point| min.min(point.y))
523            .floor()
524            .max(0.0);
525        let max_y = corners
526            .iter()
527            .fold(f64::NEG_INFINITY, |max, point| max.max(point.y))
528            .ceil()
529            .min(f64::from(canvas.height()));
530        for y in min_y as u32..max_y as u32 {
531            for x in min_x as u32..max_x as u32 {
532                let coverage = mask.alpha(x, y);
533                if coverage <= 0.0 {
534                    continue;
535                }
536                let device = Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5);
537                let user = inverse.apply(device);
538                if !(0.0..=1.0).contains(&user.x) || !(0.0..=1.0).contains(&user.y) {
539                    continue;
540                }
541                // Image space has its origin at the bottom-left, but the first
542                // sample row is the top one.
543                let v = 1.0 - user.y;
544                if self.is_masked(user.x, v) {
545                    // "Samples in the image that fall within this range shall not
546                    // be painted, allowing the existing background to show
547                    // through" (8.9.6.4): skipped, not blended.
548                    continue;
549                }
550                let colour = self.sample(user.x, v);
551                canvas.blend_with(x, y, colour, alpha * coverage, mode);
552            }
553        }
554    }
555}
556
557/// A colour key (`8.9.6.4`): samples whose every component falls in its range,
558/// **before** `/Decode`, are not painted.
559///
560/// The clause's ranges are inclusive: `colorkeymask.pdf` writes `min == max` for
561/// the red it wants hidden, which an exclusive reading would never mask.
562#[derive(Debug, Clone, PartialEq, Eq)]
563struct ColourKey {
564    min: [u8; 4],
565    max: [u8; 4],
566    components: usize,
567}
568
569impl ColourKey {
570    /// Read a `/Mask` array: `2 × n` integers in `0 … 2^bits − 1`, mapped onto the
571    /// byte values the samples are widened to (1-bit samples become 0/255).
572    fn parse(items: &[Object], components: usize, bits: i64) -> Result<Self> {
573        if items.len() != components * 2 {
574            return Err(Error::malformed(
575                "a /Mask whose length is not twice the image's component count",
576            ));
577        }
578        let scale = if bits == 1 { 255.0 } else { 1.0 };
579        let limit = if bits == 1 { 1.0 } else { 255.0 };
580        let mut min = [0_u8; 4];
581        let mut max = [0_u8; 4];
582        for slot in 0..components {
583            let low = items[slot * 2].as_real().unwrap_or(-1.0);
584            let high = items[slot * 2 + 1].as_real().unwrap_or(-1.0);
585            if !(0.0..=limit).contains(&low) || !(0.0..=limit).contains(&high) {
586                return Err(Error::malformed("a /Mask value outside the sample range"));
587            }
588            min[slot] = (low * scale).round() as u8;
589            max[slot] = (high * scale).round() as u8;
590        }
591        Ok(Self {
592            min,
593            max,
594            components,
595        })
596    }
597
598    /// Whether a sample falls inside the key on every component.
599    fn masks(&self, sample: &[u8]) -> bool {
600        sample
601            .iter()
602            .take(self.components)
603            .enumerate()
604            .all(|(slot, byte)| (self.min[slot]..=self.max[slot]).contains(byte))
605    }
606}
607
608/// The `/Decode` range for each component, defaulting to the identity.
609fn decode_ranges(decode: Option<&Object>, components: usize) -> Vec<(f64, f64)> {
610    let mut ranges = vec![(0.0, 1.0); components];
611    let Some(Object::Array(items)) = decode else {
612        return ranges;
613    };
614    if items.len() < components * 2 {
615        return ranges;
616    }
617    for (slot, pair) in items.as_chunks::<2>().0.iter().enumerate().take(components) {
618        let (Some(from), Some(to)) = (pair[0].as_real(), pair[1].as_real()) else {
619            continue;
620        };
621        ranges[slot] = (from, to);
622    }
623    ranges
624}
625
626/// Turn decoded components (0–1 each) into a colour through `colours`.
627fn colour_at(colours: &ColourSpace, components: &[f64; 4]) -> Color {
628    match colours {
629        ColourSpace::Gray => Color::rgb(components[0], components[0], components[0]),
630        ColourSpace::Rgb => Color::rgb(components[0], components[1], components[2]),
631        ColourSpace::Cmyk => {
632            Color::from_cmyk(components[0], components[1], components[2], components[3])
633        }
634        ColourSpace::Indexed { base, lookup } => {
635            // For an indexed image the decoded value is the index, not a colour
636            // component, so it is scaled back into the table's range.
637            let index = (components[0] * 255.0).round().max(0.0) as usize;
638            let count = base.components();
639            let entry = index * count;
640            let slice = lookup.get(entry..entry + count).unwrap_or(&[]);
641            if slice.len() < count {
642                return Color::BLACK;
643            }
644            let mut table = [0.0_f64; 4];
645            for (slot, byte) in slice.iter().enumerate().take(4) {
646                table[slot] = f64::from(*byte) / 255.0;
647            }
648            colour_at(base, &table)
649        }
650    }
651}
652
653fn mix(left: Color, right: Color, t: f64) -> Color {
654    let t = t.clamp(0.0, 1.0);
655    Color::rgb(
656        left.r * (1.0 - t) + right.r * t,
657        left.g * (1.0 - t) + right.g * t,
658        left.b * (1.0 - t) + right.b * t,
659    )
660}
661
662/// The colour space of an image, resolved to what the sampler needs.
663#[derive(Debug, Clone, PartialEq)]
664enum ColourSpace {
665    Gray,
666    Rgb,
667    Cmyk,
668    Indexed {
669        base: Box<ColourSpace>,
670        lookup: Vec<u8>,
671    },
672}
673
674impl ColourSpace {
675    fn from_object(document: &Document, object: Object) -> Result<Self> {
676        match object {
677            Object::Name(name) => match name.as_slice() {
678                b"DeviceGray" | b"G" | b"CalGray" => Ok(Self::Gray),
679                b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(Self::Rgb),
680                b"DeviceCMYK" | b"CMYK" => Ok(Self::Cmyk),
681                _ => Err(Error::malformed("unsupported image /ColorSpace")),
682            },
683            Object::Array(items) => {
684                let family = match items.first() {
685                    Some(Object::Name(name)) => name.clone(),
686                    _ => return Err(Error::malformed("image /ColorSpace array family")),
687                };
688                match family.as_slice() {
689                    b"Indexed" | b"I" => {
690                        let base = match items.get(1) {
691                            Some(base) => {
692                                Self::from_object(document, resolve(document, Some(base))?)?
693                            }
694                            None => return Err(Error::malformed("Indexed image without a base")),
695                        };
696                        let lookup = match items.get(3) {
697                            Some(Object::String(string)) => string.as_bytes().to_vec(),
698                            Some(Object::Reference(id)) => document.stream_data(*id)?,
699                            _ => {
700                                return Err(Error::malformed(
701                                    "Indexed image without a lookup table",
702                                ));
703                            }
704                        };
705                        Ok(Self::Indexed {
706                            base: Box::new(base),
707                            lookup,
708                        })
709                    }
710                    b"ICCBased" => {
711                        let stream = match items.get(1) {
712                            Some(Object::Reference(id)) => document.stream(*id)?,
713                            _ => return Err(Error::malformed("ICCBased without a stream")),
714                        };
715                        let components = stream
716                            .dict()
717                            .get(b"N")
718                            .and_then(Object::as_integer)
719                            .unwrap_or(3);
720                        match components {
721                            1 => Ok(Self::Gray),
722                            3 => Ok(Self::Rgb),
723                            4 => Ok(Self::Cmyk),
724                            _ => Err(Error::malformed("unsupported ICCBased components")),
725                        }
726                    }
727                    _ => Err(Error::malformed("unsupported image /ColorSpace array")),
728                }
729            }
730            _ => Err(Error::malformed("unsupported image /ColorSpace value")),
731        }
732    }
733
734    fn components(&self) -> usize {
735        match self {
736            Self::Gray => 1,
737            Self::Rgb => 3,
738            Self::Cmyk => 4,
739            Self::Indexed { .. } => 1,
740        }
741    }
742}
743
744fn integer(dict: &Dictionary, key: &[u8]) -> Result<u32> {
745    dict.get(key)
746        .and_then(Object::as_integer)
747        .and_then(|value| u32::try_from(value).ok())
748        .ok_or_else(|| Error::malformed("image without integer /Width and /Height"))
749}
750
751/// How many components the stream's `/ColorSpace` declares, when it is a name or
752/// a known family — enough to know whether a JPEG is CMYK.
753fn dict_component_count(stream: &Stream) -> Option<usize> {
754    match stream.dict().get(b"ColorSpace") {
755        Some(Object::Name(name)) if name == b"DeviceCMYK" => Some(4),
756        Some(Object::Name(name)) if name == b"DeviceGray" => Some(1),
757        Some(Object::Name(name)) if name == b"DeviceRGB" => Some(3),
758        _ => None,
759    }
760}
761
762/// Widen packed one-bit samples to one byte each, 0 or 255.
763///
764/// PDF pads each row to a byte boundary, so a 1728-pixel fax line occupies 216
765/// bytes; a row shorter than its padding is malformed rather than merely short.
766fn widen_one_bit(data: &[u8], width: u32, height: u32, components: usize) -> Result<Vec<u8>> {
767    if components != 1 {
768        return Err(Error::malformed(
769            "one-bit samples need a single-component colour space",
770        ));
771    }
772    let bits_per_row = usize::try_from(width).unwrap_or(0);
773    let stride = bits_per_row.div_ceil(8);
774    let rows = usize::try_from(height).unwrap_or(0);
775    if data.len() < stride.saturating_mul(rows) {
776        return Err(Error::malformed(
777            "one-bit image data is shorter than its rows",
778        ));
779    }
780    let mut out = Vec::with_capacity(bits_per_row.saturating_mul(rows));
781    for row in 0..rows {
782        for column in 0..bits_per_row {
783            let byte = data[row * stride + column / 8];
784            let shift = 7 - column % 8;
785            let bit = (byte >> shift) & 1;
786            out.push(if bit == 1 { 255 } else { 0 });
787        }
788    }
789    Ok(out)
790}
791
792/// Whether a JPEG carries an Adobe APP14 marker, which is what makes its CMYK
793/// samples stored inverted (PDF 7.4.8).
794///
795/// The marker is `FFEE` then a two-byte length and the identifier `Adobe`; only
796/// the identifier matters here, because the transform byte says whether the
797/// samples are plain CMYK or YCCK, and both are stored inverted.
798fn has_adobe_marker(data: &[u8]) -> bool {
799    let mut index = 2; // past the `FF D8` start-of-image marker
800    while index + 4 <= data.len() {
801        if data[index] != 0xFF {
802            return false;
803        }
804        let marker = data[index + 1];
805        // Segments with no payload.
806        if matches!(marker, 0xD8 | 0x01 | 0xD0..=0xD7) {
807            index += 2;
808            continue;
809        }
810        let length = usize::from(u16::from_be_bytes([data[index + 2], data[index + 3]]));
811        if length < 2 {
812            return false;
813        }
814        if marker == 0xEE {
815            let payload = &data[index + 4..(index + 2 + length).min(data.len())];
816            return payload.starts_with(b"Adobe");
817        }
818        // Start of scan: no more header segments follow.
819        if marker == 0xDA {
820            return false;
821        }
822        index += 2 + length;
823    }
824    false
825}
826
827/// Whether the stream's filter chain ends in `name`.
828fn ends_in(dict: &Dictionary, name: &[u8]) -> bool {
829    match dict.get(b"Filter") {
830        Some(Object::Name(filter)) => filter == name,
831        Some(Object::Array(items)) => items
832            .iter()
833            .rev()
834            .find_map(Object::as_name)
835            .is_some_and(|filter| filter == name),
836        _ => false,
837    }
838}
839
840/// Whether the stream's filter chain ends in `/DCTDecode`.
841fn is_dct(dict: &Dictionary) -> bool {
842    ends_in(dict, b"DCTDecode")
843}
844
845/// Whether the stream's filter chain ends in `/JPXDecode` (7.4.9).
846fn is_jpx(dict: &Dictionary) -> bool {
847    ends_in(dict, b"JPXDecode")
848}
849
850/// Whether the stream's filter chain ends in `/JBIG2Decode` (7.4.7).
851fn is_jbig2(dict: &Dictionary) -> bool {
852    ends_in(dict, b"JBIG2Decode")
853}
854
855/// Follow one indirect reference; deeper chains are not needed for images.
856pub(crate) fn resolve(document: &Document, object: Option<&Object>) -> Result<Object> {
857    match object {
858        Some(Object::Reference(id)) => document.get_object(*id),
859        Some(other) => Ok(other.clone()),
860        None => Ok(Object::Null),
861    }
862}
863
864/// How many components a JPX colour space needs, or why it is refused.
865///
866/// `/JPXDecode` takes its colour space from the codestream (7.4.9), and this
867/// renderer can paint grey, RGB and CMYK. An ICC or unnamed space would need
868/// colour management, so it is reported by name instead of mapped by component
869/// count — the failure mode that guesses is the one that draws a wrong colour
870/// with full confidence.
871#[cfg(feature = "jpx")]
872fn jpx_components(space: &hayro_jpeg2000::ColorSpace) -> Result<usize> {
873    match space {
874        hayro_jpeg2000::ColorSpace::Gray => Ok(1),
875        hayro_jpeg2000::ColorSpace::RGB => Ok(3),
876        hayro_jpeg2000::ColorSpace::CMYK => Ok(4),
877        hayro_jpeg2000::ColorSpace::Icc { .. } => Err(Error::Unsupported {
878            what: "a /JPXDecode image in an ICC colour space",
879        }),
880        hayro_jpeg2000::ColorSpace::Unknown { .. } => Err(Error::Unsupported {
881            what: "a /JPXDecode image in a colour space it cannot name",
882        }),
883    }
884}
885
886/// Resolves the `/JBIG2Globals` stream of a `/JBIG2Decode` image, if it names one.
887#[cfg(feature = "jbig2")]
888fn globals_bytes(document: &Document, dict: &Dictionary) -> Result<Option<Vec<u8>>> {
889    let Some(parms) = dict.get(b"DecodeParms") else {
890        return Ok(None);
891    };
892    let parms = resolve(document, Some(parms))?;
893    let Some(parms) = parms.as_dict() else {
894        return Ok(None);
895    };
896    let Some(globals) = parms.get(b"JBIG2Globals") else {
897        return Ok(None);
898    };
899    let globals = resolve(document, Some(globals))?;
900    let Some(stream) = globals.as_stream() else {
901        return Err(Error::malformed("/JBIG2Globals is not a stream"));
902    };
903    document.decode_stream(stream).map(Some)
904}
905
906/// A JBIG2 sink that writes packed 1-bit rows the way a PDF image expects them.
907///
908/// `hayro-jbig2` reports `black`, and a 1-bit `/DeviceGray` sample is 1 for
909/// **white** unless `/Decode` inverts it (`src/fax.rs:37` and the CCITT writer
910/// beside it). Writing `black` straight through draws the page as its negative,
911/// which is why the tests assert ink on white instead of trusting the sense.
912#[cfg(feature = "jbig2")]
913struct Rows {
914    packed: Vec<u8>,
915    /// Bytes per row: a 1-bit PDF image is **row-aligned to a byte**, so a row of
916    /// 399 pixels occupies 50 bytes and leaves one bit of padding.
917    stride: usize,
918    row: usize,
919    column: usize,
920}
921
922#[cfg(feature = "jbig2")]
923impl Rows {
924    fn new(width: usize, height: usize) -> Self {
925        Self {
926            packed: vec![0; width.div_ceil(8) * height],
927            stride: width.div_ceil(8),
928            row: 0,
929            column: 0,
930        }
931    }
932
933    /// Write `count` samples of one value, MSB first, in the current row.
934    ///
935    /// The row offset is what makes this a PDF image rather than a bit stream: with
936    /// a width that is not a multiple of eight, packing the pixels contiguously
937    /// shifts every row by one bit, which is a defect this sink had — it cost
938    /// 19 553 differing pixels against pdfium's reference raster (12.25 %, mean
939    /// |Δ| 31.24) while the decoder's own output was byte-exact.
940    fn run(&mut self, white: bool, count: usize) {
941        for _ in 0..count {
942            if white {
943                let byte = self.row * self.stride + self.column / 8;
944                let shift = 7 - self.column % 8;
945                if let Some(slot) = self.packed.get_mut(byte) {
946                    *slot |= 1 << shift;
947                }
948            }
949            self.column += 1;
950        }
951    }
952
953    fn finish(self) -> Vec<u8> {
954        self.packed
955    }
956}
957
958#[cfg(feature = "jbig2")]
959impl hayro_jbig2::Decoder for Rows {
960    fn push_pixel(&mut self, black: bool) {
961        self.run(!black, 1);
962    }
963
964    fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
965        self.run(!black, 8 * chunk_count as usize);
966    }
967
968    fn next_line(&mut self) {
969        self.row += 1;
970        self.column = 0;
971    }
972}
973
974#[cfg(test)]
975mod tests {
976    use super::Image;
977    use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
978    use crate::geom::Matrix;
979
980    /// A JPX colour space this renderer cannot honour is refused by name, not
981    /// mapped by component count: the guess is what draws a confident wrong
982    /// colour.
983    #[cfg(feature = "jpx")]
984    #[test]
985    fn jpx_refuses_the_colour_spaces_it_cannot_paint() {
986        use hayro_jpeg2000::ColorSpace;
987
988        assert_eq!(super::jpx_components(&ColorSpace::Gray).unwrap(), 1);
989        assert_eq!(super::jpx_components(&ColorSpace::RGB).unwrap(), 3);
990        assert_eq!(super::jpx_components(&ColorSpace::CMYK).unwrap(), 4);
991        let icc = super::jpx_components(&ColorSpace::Icc {
992            profile: Vec::new(),
993            num_channels: 3,
994        })
995        .expect_err("an ICC space needs colour management");
996        assert!(icc.to_string().contains("ICC"), "{icc}");
997        let unknown = super::jpx_components(&ColorSpace::Unknown { num_channels: 2 })
998            .expect_err("an unnamed space is refused");
999        assert!(unknown.to_string().contains("cannot name"), "{unknown}");
1000    }
1001
1002    fn image(width: u32, height: u32, interpolate: bool) -> Image {
1003        let mut pixels = Vec::new();
1004        for y in 0..height {
1005            for x in 0..width {
1006                pixels.push(if (x + y) % 2 == 0 {
1007                    Color::BLACK
1008                } else {
1009                    Color::WHITE
1010                });
1011            }
1012        }
1013        Image {
1014            width,
1015            height,
1016            pixels,
1017            interpolate,
1018            masked: None,
1019        }
1020    }
1021
1022    #[test]
1023    fn nearest_sampling_returns_whole_pixels() {
1024        let image = image(2, 2, false);
1025        assert_eq!(image.sample(0.25, 0.25), Color::BLACK);
1026        assert_eq!(image.sample(0.75, 0.25), Color::WHITE);
1027        assert_eq!(image.sample(0.25, 0.75), Color::WHITE);
1028    }
1029
1030    #[test]
1031    fn bilinear_sampling_blends_neighbours() {
1032        let image = image(2, 2, true);
1033        let middle = image.sample(0.5, 0.5);
1034        assert!((middle.r - 0.5).abs() < 1e-9, "{middle:?}");
1035    }
1036
1037    #[test]
1038    fn painting_covers_the_unit_square_transform() {
1039        let image = image(2, 2, false);
1040        let mut canvas = Canvas::new(4, 4, Color::WHITE);
1041        let mask = ClipMask::all(4, 4);
1042        // Unit square scaled to 4×4 with y flipped like the page transform.
1043        let ctm = Matrix::new(4.0, 0.0, 0.0, -4.0, 0.0, 4.0);
1044        image.paint(&mut canvas, &mask, ctm, 1.0, BlendMode::Normal);
1045        assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
1046        assert_eq!(canvas.pixel(3, 0), Some([255, 255, 255, 255]));
1047        assert_eq!(canvas.pixel(0, 3), Some([255, 255, 255, 255]));
1048        assert_eq!(canvas.pixel(3, 3), Some([0, 0, 0, 255]));
1049    }
1050}