pdf2-render 1.5.0

Rasteriser for the pdf2 crate: paths, clips, images, text, fonts, shadings and patterns, with a report of what it cannot draw.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
//! Image XObjects: decode an 8-bit image, then sample it into the canvas.

use pdf2::{Dictionary, Document, Object, Stream};

use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
use crate::geom::{Matrix, Point};
use crate::{Error, Result};

/// A decoded image: width, height and one colour per pixel, top row first.
#[derive(Debug, Clone)]
pub struct Image {
    width: u32,
    height: u32,
    pixels: Vec<Color>,
    interpolate: bool,
    /// Per source pixel: masked by a colour key (`8.9.6.4`), and so not painted.
    masked: Option<Vec<bool>>,
}

impl Image {
    /// Decode an `/Image` XObject.
    ///
    /// Supports 8 bits per component, `DeviceGray`/`DeviceRGB`/`DeviceCMYK`,
    /// `Indexed` images with those bases, and `ICCBased` streams by component
    /// count. Anything else is reported rather than guessed.
    pub fn from_stream(
        document: &Document,
        stream: &Stream,
        id: Option<pdf2::ObjectId>,
    ) -> Result<Self> {
        let dict = stream.dict();
        // `/JPXDecode` and `/JBIG2Decode` carry their own colour space and bit
        // depth: `/ColorSpace` may be absent from a JPX image and its
        // `/BitsPerComponent` is ignored (7.4.9), so the dispatch has to happen
        // before either is read. A codec that is not compiled in is reported by
        // name there, because the alternative is a page that silently loses its
        // image.
        if is_jpx(dict) {
            return Self::from_jpx(document, stream, id);
        }
        if is_jbig2(dict) {
            return Self::from_jbig2(document, stream, id);
        }
        let width = integer(dict, b"Width")?;
        let height = integer(dict, b"Height")?;
        if width == 0 || height == 0 {
            return Err(Error::malformed("image with zero width or height"));
        }
        let bits = dict
            .get(b"BitsPerComponent")
            .and_then(Object::as_integer)
            .unwrap_or(8);
        // One bit per component is how every fax image arrives; the packed rows
        // are widened to bytes here so the sampler below has one path.
        if bits != 8 && bits != 1 {
            return Err(Error::malformed(
                "only 1 and 8 bits per component images are rendered",
            ));
        }
        let interpolate = matches!(dict.get(b"Interpolate"), Some(Object::Boolean(true)));
        let space = resolve(document, dict.get(b"ColorSpace"))?;
        // The colour space is dictionary metadata, so the size the image claims
        // is known before its stream is touched — and that is the order that
        // keeps a lying /Width from being paid for. Every component is one byte
        // here (8 bits per component is the only depth drawn), so the decoded
        // size is width × height × components.
        let colours = ColourSpace::from_object(document, space)?;
        let per_pixel = colours.components();
        let count = (width as usize)
            .checked_mul(height as usize)
            .and_then(|pixels| pixels.checked_mul(per_pixel))
            .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
        let limit = document.decoded_limit();
        if count > limit {
            return Err(Error::Limit {
                what: "an image of the /Width and /Height it declares",
                limit,
            });
        }
        // A colour key is tested on the samples *before* `/Decode` (8.9.6.4), so
        // it is read here, and two forms are refused by name rather than ignored:
        // the clause forbids `/DCTDecode` with a key, and a `/Mask` that is a
        // stream is a stencil image (8.9.6.3), a different mechanism.
        let key = match dict.get(b"Mask") {
            None => None,
            Some(Object::Array(items)) => Some(ColourKey::parse(items, per_pixel, bits)?),
            Some(Object::Reference(_)) => {
                return Err(Error::Unsupported {
                    what: "a /Mask image stencil",
                });
            }
            Some(_) => {
                return Err(Error::malformed(
                    "a /Mask that is neither an array nor a stream",
                ));
            }
        };
        if key.is_some() && is_dct(dict) {
            return Err(Error::Unsupported {
                what: "colour-key /Mask on a /DCTDecode image",
            });
        }
        if is_dct(dict) {
            return Self::from_dct(document, stream, id, interpolate);
        }
        let decoded = document.decode_stream(stream)?;
        let data = if bits == 1 {
            widen_one_bit(&decoded, width, height, per_pixel)?
        } else {
            decoded
        };
        if data.len() < count {
            return Err(Error::Malformed {
                what: "image data is shorter than width × height × components",
                offset: None,
            });
        }
        // `/Decode` remaps every sample before the colour space sees it; the
        // default is the identity, and `[1 0]` per component is an inversion
        // (8.9.5.2).
        let masked = key.map(|key| {
            data.chunks_exact(per_pixel)
                .map(|sample| key.masks(sample))
                .collect::<Vec<bool>>()
        });
        let decode = decode_ranges(dict.get(b"Decode"), per_pixel);
        let mut pixels = Vec::with_capacity((width as usize) * (height as usize));
        for index in (0..count).step_by(per_pixel) {
            let sample = &data[index..index + per_pixel];
            let mut components = [0.0_f64; 4];
            for (slot, byte) in sample.iter().enumerate().take(per_pixel) {
                let (from, to) = decode[slot];
                components[slot] = (from + f64::from(*byte) / 255.0 * (to - from)).clamp(0.0, 1.0);
            }
            pixels.push(colour_at(&colours, &components));
        }
        Ok(Self {
            width,
            height,
            pixels,
            interpolate,
            masked,
        })
    }

    /// Decode a `/DCTDecode` image through `zune-jpeg`.
    ///
    /// A JPEG in a PDF has no leading filters to unwind, so the bytes come
    /// straight from [`Document::stream_bytes`] — decrypted, not decoded — and
    /// `zune-jpeg` converts YCbCr to RGB itself. The size is checked against the
    /// budget twice: once from the dictionary, and once from the JPEG's own
    /// header, because the header is the authority on what the decoder produces.
    #[cfg(feature = "dct")]
    fn from_dct(
        document: &Document,
        _stream: &Stream,
        id: Option<pdf2::ObjectId>,
        interpolate: bool,
    ) -> Result<Self> {
        let Some(id) = id else {
            return Err(Error::malformed(
                "a /DCTDecode image without an object number",
            ));
        };
        let data = document.stream_bytes(id)?;
        // PDF 7.4.8: a four-component JPEG from an Adobe writer stores its CMYK
        // samples **inverted** (255 - sample), and its `/Decode` array — when the
        // writer states one — is the same statement in words. Asking the decoder
        // for CMYK rather than RGB is what makes the inversion possible: its RGB
        // conversion assumes the already-uninverted order and comes out black.
        let cmyk = dict_component_count(_stream) == Some(4);
        let mut decoder =
            zune_jpeg::JpegDecoder::new(zune_jpeg::zune_core::bytestream::ZCursor::new(&data));
        if cmyk {
            decoder.set_options(
                zune_jpeg::zune_core::options::DecoderOptions::default()
                    .jpeg_set_out_colorspace(zune_jpeg::zune_core::colorspace::ColorSpace::CMYK),
            );
        }
        let pixels = decoder
            .decode()
            .map_err(|_| Error::malformed("/DCTDecode payload"))?;
        let Some(info) = decoder.info() else {
            return Err(Error::malformed(
                "/DCTDecode payload without a frame header",
            ));
        };
        let components = match decoder.output_colorspace() {
            Some(zune_jpeg::zune_core::colorspace::ColorSpace::Luma) => 1,
            Some(zune_jpeg::zune_core::colorspace::ColorSpace::CMYK) => 4,
            _ => 3,
        };
        let count = usize::from(info.width)
            .checked_mul(usize::from(info.height))
            .and_then(|samples| samples.checked_mul(components))
            .ok_or_else(|| Error::malformed("image dimensions overflow"))?;
        let limit = document.decoded_limit();
        if count > limit {
            return Err(Error::Limit {
                what: "a /DCTDecode image of the size its header declares",
                limit,
            });
        }
        if pixels.len() < count {
            return Err(Error::malformed(
                "/DCTDecode payload is shorter than its header",
            ));
        }
        // The Adobe inversion is applied here only when the writer did not state
        // it as `/Decode`: the two are the same statement, and applying both
        // would invert twice (which is what pdf.js does, and what
        // `cmykjpeg.pdf` — an Adobe APP14 all-zero transform with no `/Decode` —
        // needs).
        let stated_decode = _stream.dict().get(b"Decode").is_some();
        let invert = cmyk && !stated_decode && has_adobe_marker(&data);
        // A `/Decode` array, when the writer states one, is applied to the samples
        // after the Adobe inversion; when it inverts, the two cancel out.
        let decode = decode_ranges(_stream.dict().get(b"Decode"), components);
        let sample = |bytes: &[u8]| -> Vec<f64> {
            bytes
                .iter()
                .enumerate()
                .map(|(index, byte)| {
                    let value = f64::from(*byte) / 255.0;
                    let (from, to) = decode[index.min(decode.len() - 1)];
                    (from + value * (to - from)).clamp(0.0, 1.0)
                })
                .collect()
        };
        let pixels = pixels[..count]
            .chunks_exact(components)
            .map(|bytes| {
                let bytes: Vec<u8> = if invert {
                    bytes.iter().map(|byte| 255 - byte).collect()
                } else {
                    bytes.to_vec()
                };
                let values = sample(&bytes);
                match components {
                    1 => Color::rgb(values[0], values[0], values[0]),
                    4 => Color::from_cmyk(values[0], values[1], values[2], values[3]),
                    _ => Color::rgb(values[0], values[1], values[2]),
                }
            })
            .collect();
        Ok(Self {
            width: u32::from(info.width),
            height: u32::from(info.height),
            pixels,
            interpolate,
            // A `/DCTDecode` image with a key is refused above, so there is
            // never a mask to carry here.
            masked: None,
        })
    }

    /// Without the feature a JPEG is reported, not guessed at.
    #[cfg(not(feature = "dct"))]
    fn from_dct(
        _document: &Document,
        _stream: &Stream,
        _id: Option<pdf2::ObjectId>,
        _interpolate: bool,
    ) -> Result<Self> {
        Err(Error::Unsupported {
            what: "/DCTDecode images (build with the `dct` feature)",
        })
    }

    /// A `/JPXDecode` image without the feature is reported by name.
    #[cfg(not(feature = "jpx"))]
    fn from_jpx(
        _document: &Document,
        _stream: &Stream,
        _id: Option<pdf2::ObjectId>,
    ) -> Result<Self> {
        Err(Error::Unsupported {
            what: "/JPXDecode images (build with the `jpx` feature)",
        })
    }

    /// A `/JPXDecode` image with the feature: the codestream decides the size,
    /// the colour space and the depth (7.4.9), so all three come from its header
    /// and the budget is checked before a pixel is decoded.
    #[cfg(feature = "jpx")]
    fn from_jpx(document: &Document, stream: &Stream, id: Option<pdf2::ObjectId>) -> Result<Self> {
        let Some(id) = id else {
            return Err(Error::malformed(
                "a /JPXDecode image without an object number",
            ));
        };
        let interpolate = matches!(
            stream.dict().get(b"Interpolate"),
            Some(Object::Boolean(true))
        );
        let data = document.stream_bytes(id)?;
        let image = hayro_jpeg2000::Image::new(&data, &hayro_jpeg2000::DecodeSettings::default())
            .map_err(|_| Error::malformed("/JPXDecode codestream"))?;
        // An alpha channel and an ICC or unknown colour space are refused by
        // name rather than guessed at: the first needs a soft mask this renderer
        // does not carry, and the other two need colour management it does not do.
        if image.has_alpha() {
            return Err(Error::Unsupported {
                what: "a /JPXDecode image with an alpha channel",
            });
        }
        let components = jpx_components(image.color_space())?;
        let width = image.width();
        let height = image.height();
        let count = (width as usize)
            .checked_mul(height as usize)
            .and_then(|pixels| pixels.checked_mul(components))
            .ok_or_else(|| Error::malformed("/JPXDecode image dimensions overflow"))?;
        let limit = document.decoded_limit();
        if count > limit {
            return Err(Error::Limit {
                what: "a /JPXDecode image of the size its codestream declares",
                limit,
            });
        }
        // `/Decode` is not part of the JPX model — the codestream carries its own
        // sample range — so the samples are used as they come.
        let mut context = hayro_jpeg2000::DecoderContext::default();
        let decoded = image
            .decode(&mut context)
            .map_err(|_| Error::malformed("/JPXDecode payload"))?;
        let samples = decoded.data_u8();
        if samples.len() < count {
            return Err(Error::malformed(
                "/JPXDecode payload is shorter than its header",
            ));
        }
        let sample = |byte: u8| f64::from(byte) / 255.0;
        let pixels = samples[..count]
            .chunks_exact(components)
            .map(|bytes| match components {
                1 => {
                    let grey = sample(bytes[0]);
                    Color::rgb(grey, grey, grey)
                }
                4 => Color::from_cmyk(
                    sample(bytes[0]),
                    sample(bytes[1]),
                    sample(bytes[2]),
                    sample(bytes[3]),
                ),
                _ => Color::rgb(sample(bytes[0]), sample(bytes[1]), sample(bytes[2])),
            })
            .collect();
        Ok(Self {
            width,
            height,
            pixels,
            interpolate,
            masked: None,
        })
    }

    /// A `/JBIG2Decode` image without the feature is reported by name.
    #[cfg(not(feature = "jbig2"))]
    fn from_jbig2(
        _document: &Document,
        _stream: &Stream,
        _id: Option<pdf2::ObjectId>,
    ) -> Result<Self> {
        Err(Error::Unsupported {
            what: "/JBIG2Decode images (build with the `jbig2` feature)",
        })
    }

    /// A `/JBIG2Decode` image with the feature: the page information decides the
    /// size, and `/DecodeParms /JBIG2Globals` may carry shared segments that must
    /// be decoded before the page's own (7.4.7).
    #[cfg(feature = "jbig2")]
    fn from_jbig2(
        document: &Document,
        stream: &Stream,
        id: Option<pdf2::ObjectId>,
    ) -> Result<Self> {
        let Some(id) = id else {
            return Err(Error::malformed(
                "a /JBIG2Decode image without an object number",
            ));
        };
        let interpolate = matches!(
            stream.dict().get(b"Interpolate"),
            Some(Object::Boolean(true))
        );
        let settings = hayro_jbig2::DecodeSettings::default();
        // The globals are a *separate* stream: `/DecodeParms /JBIG2Globals` names
        // it, and its segments have to be decoded before the image's own. A page
        // wired only to `new_embedded(data, None, …)` fails on exactly these files.
        let globals = match globals_bytes(document, stream.dict())? {
            Some(bytes) => Some(
                hayro_jbig2::Globals::new(&bytes, &settings)
                    .map_err(|_| Error::malformed("/JBIG2Decode globals stream"))?,
            ),
            None => None,
        };
        let data = document.stream_bytes(id)?;
        let page = hayro_jbig2::Page::new_embedded(&data, globals.as_ref(), &settings)
            .map_err(|_| Error::malformed("/JBIG2Decode page"))?;
        let width = page.width();
        let height = page.height();
        let count = (width as usize)
            .checked_mul(height as usize)
            .ok_or_else(|| Error::malformed("/JBIG2Decode image dimensions overflow"))?;
        let limit = document.decoded_limit();
        if count > limit {
            return Err(Error::Limit {
                what: "a /JBIG2Decode image of the size its page information declares",
                limit,
            });
        }
        let mut rows = Rows::new(width as usize, height as usize);
        page.decode(&mut rows)
            .map_err(|_| Error::malformed("/JBIG2Decode payload"))?;
        let widened = widen_one_bit(&rows.finish(), width, height, 1)?;
        let pixels = widened
            .into_iter()
            .map(|sample| {
                let grey = f64::from(sample) / 255.0;
                Color::rgb(grey, grey, grey)
            })
            .collect();
        Ok(Self {
            width,
            height,
            pixels,
            interpolate,
            masked: None,
        })
    }

    /// Whether the source sample nearest to `(u, v)` is hidden by the colour key.
    fn is_masked(&self, u: f64, v: f64) -> bool {
        let Some(masked) = &self.masked else {
            return false;
        };
        if self.width == 0 || self.height == 0 {
            return false;
        }
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let x = (u.clamp(0.0, 1.0) * f64::from(self.width)) as u32;
        #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
        let y = (v.clamp(0.0, 1.0) * f64::from(self.height)) as u32;
        let x = x.min(self.width - 1);
        let y = y.min(self.height - 1);
        masked
            .get((y * self.width + x) as usize)
            .copied()
            .unwrap_or(false)
    }

    /// Width in samples.
    pub fn width(&self) -> u32 {
        self.width
    }

    /// Height in samples.
    pub fn height(&self) -> u32 {
        self.height
    }

    /// The colour at a sample position, nearest or bilinear.
    pub fn sample(&self, u: f64, v: f64) -> Color {
        if self.width == 0 || self.height == 0 {
            return Color::WHITE;
        }
        let x = (u.clamp(0.0, 1.0) * f64::from(self.width) - 0.5).max(0.0);
        let y = (v.clamp(0.0, 1.0) * f64::from(self.height) - 0.5).max(0.0);
        if !self.interpolate {
            return self.pixel(x.round() as u32, y.round() as u32);
        }
        let x0 = x.floor() as u32;
        let y0 = y.floor() as u32;
        let x1 = (x0 + 1).min(self.width - 1);
        let y1 = (y0 + 1).min(self.height - 1);
        let fx = x - f64::from(x0);
        let fy = y - f64::from(y0);
        let top = mix(self.pixel(x0, y0), self.pixel(x1, y0), fx);
        let bottom = mix(self.pixel(x0, y1), self.pixel(x1, y1), fx);
        mix(top, bottom, fy)
    }

    fn pixel(&self, x: u32, y: u32) -> Color {
        let x = x.min(self.width - 1);
        let y = y.min(self.height - 1);
        self.pixels[(y as usize) * (self.width as usize) + (x as usize)]
    }

    /// Paint into the canvas through `ctm`, restricted to `mask`.
    pub fn paint(
        &self,
        canvas: &mut Canvas,
        mask: &ClipMask,
        ctm: Matrix,
        alpha: f64,
        mode: BlendMode,
    ) {
        let Some(inverse) = ctm.invert() else {
            return;
        };
        let corners = [
            ctm.apply(Point::new(0.0, 0.0)),
            ctm.apply(Point::new(1.0, 0.0)),
            ctm.apply(Point::new(0.0, 1.0)),
            ctm.apply(Point::new(1.0, 1.0)),
        ];
        let min_x = corners
            .iter()
            .fold(f64::INFINITY, |min, point| min.min(point.x))
            .floor()
            .max(0.0);
        let max_x = corners
            .iter()
            .fold(f64::NEG_INFINITY, |max, point| max.max(point.x))
            .ceil()
            .min(f64::from(canvas.width()));
        let min_y = corners
            .iter()
            .fold(f64::INFINITY, |min, point| min.min(point.y))
            .floor()
            .max(0.0);
        let max_y = corners
            .iter()
            .fold(f64::NEG_INFINITY, |max, point| max.max(point.y))
            .ceil()
            .min(f64::from(canvas.height()));
        for y in min_y as u32..max_y as u32 {
            for x in min_x as u32..max_x as u32 {
                let coverage = mask.alpha(x, y);
                if coverage <= 0.0 {
                    continue;
                }
                let device = Point::new(f64::from(x) + 0.5, f64::from(y) + 0.5);
                let user = inverse.apply(device);
                if !(0.0..=1.0).contains(&user.x) || !(0.0..=1.0).contains(&user.y) {
                    continue;
                }
                // Image space has its origin at the bottom-left, but the first
                // sample row is the top one.
                let v = 1.0 - user.y;
                if self.is_masked(user.x, v) {
                    // "Samples in the image that fall within this range shall not
                    // be painted, allowing the existing background to show
                    // through" (8.9.6.4): skipped, not blended.
                    continue;
                }
                let colour = self.sample(user.x, v);
                canvas.blend_with(x, y, colour, alpha * coverage, mode);
            }
        }
    }
}

/// A colour key (`8.9.6.4`): samples whose every component falls in its range,
/// **before** `/Decode`, are not painted.
///
/// The clause's ranges are inclusive: `colorkeymask.pdf` writes `min == max` for
/// the red it wants hidden, which an exclusive reading would never mask.
#[derive(Debug, Clone, PartialEq, Eq)]
struct ColourKey {
    min: [u8; 4],
    max: [u8; 4],
    components: usize,
}

impl ColourKey {
    /// Read a `/Mask` array: `2 × n` integers in `0 … 2^bits − 1`, mapped onto the
    /// byte values the samples are widened to (1-bit samples become 0/255).
    fn parse(items: &[Object], components: usize, bits: i64) -> Result<Self> {
        if items.len() != components * 2 {
            return Err(Error::malformed(
                "a /Mask whose length is not twice the image's component count",
            ));
        }
        let scale = if bits == 1 { 255.0 } else { 1.0 };
        let limit = if bits == 1 { 1.0 } else { 255.0 };
        let mut min = [0_u8; 4];
        let mut max = [0_u8; 4];
        for slot in 0..components {
            let low = items[slot * 2].as_real().unwrap_or(-1.0);
            let high = items[slot * 2 + 1].as_real().unwrap_or(-1.0);
            if !(0.0..=limit).contains(&low) || !(0.0..=limit).contains(&high) {
                return Err(Error::malformed("a /Mask value outside the sample range"));
            }
            min[slot] = (low * scale).round() as u8;
            max[slot] = (high * scale).round() as u8;
        }
        Ok(Self {
            min,
            max,
            components,
        })
    }

    /// Whether a sample falls inside the key on every component.
    fn masks(&self, sample: &[u8]) -> bool {
        sample
            .iter()
            .take(self.components)
            .enumerate()
            .all(|(slot, byte)| (self.min[slot]..=self.max[slot]).contains(byte))
    }
}

/// The `/Decode` range for each component, defaulting to the identity.
fn decode_ranges(decode: Option<&Object>, components: usize) -> Vec<(f64, f64)> {
    let mut ranges = vec![(0.0, 1.0); components];
    let Some(Object::Array(items)) = decode else {
        return ranges;
    };
    if items.len() < components * 2 {
        return ranges;
    }
    for (slot, pair) in items.as_chunks::<2>().0.iter().enumerate().take(components) {
        let (Some(from), Some(to)) = (pair[0].as_real(), pair[1].as_real()) else {
            continue;
        };
        ranges[slot] = (from, to);
    }
    ranges
}

/// Turn decoded components (0–1 each) into a colour through `colours`.
fn colour_at(colours: &ColourSpace, components: &[f64; 4]) -> Color {
    match colours {
        ColourSpace::Gray => Color::rgb(components[0], components[0], components[0]),
        ColourSpace::Rgb => Color::rgb(components[0], components[1], components[2]),
        ColourSpace::Cmyk => {
            Color::from_cmyk(components[0], components[1], components[2], components[3])
        }
        ColourSpace::Indexed { base, lookup } => {
            // For an indexed image the decoded value is the index, not a colour
            // component, so it is scaled back into the table's range.
            let index = (components[0] * 255.0).round().max(0.0) as usize;
            let count = base.components();
            let entry = index * count;
            let slice = lookup.get(entry..entry + count).unwrap_or(&[]);
            if slice.len() < count {
                return Color::BLACK;
            }
            let mut table = [0.0_f64; 4];
            for (slot, byte) in slice.iter().enumerate().take(4) {
                table[slot] = f64::from(*byte) / 255.0;
            }
            colour_at(base, &table)
        }
    }
}

fn mix(left: Color, right: Color, t: f64) -> Color {
    let t = t.clamp(0.0, 1.0);
    Color::rgb(
        left.r * (1.0 - t) + right.r * t,
        left.g * (1.0 - t) + right.g * t,
        left.b * (1.0 - t) + right.b * t,
    )
}

/// The colour space of an image, resolved to what the sampler needs.
#[derive(Debug, Clone, PartialEq)]
enum ColourSpace {
    Gray,
    Rgb,
    Cmyk,
    Indexed {
        base: Box<ColourSpace>,
        lookup: Vec<u8>,
    },
}

impl ColourSpace {
    fn from_object(document: &Document, object: Object) -> Result<Self> {
        match object {
            Object::Name(name) => match name.as_slice() {
                b"DeviceGray" | b"G" | b"CalGray" => Ok(Self::Gray),
                b"DeviceRGB" | b"RGB" | b"CalRGB" => Ok(Self::Rgb),
                b"DeviceCMYK" | b"CMYK" => Ok(Self::Cmyk),
                _ => Err(Error::malformed("unsupported image /ColorSpace")),
            },
            Object::Array(items) => {
                let family = match items.first() {
                    Some(Object::Name(name)) => name.clone(),
                    _ => return Err(Error::malformed("image /ColorSpace array family")),
                };
                match family.as_slice() {
                    b"Indexed" | b"I" => {
                        let base = match items.get(1) {
                            Some(base) => {
                                Self::from_object(document, resolve(document, Some(base))?)?
                            }
                            None => return Err(Error::malformed("Indexed image without a base")),
                        };
                        let lookup = match items.get(3) {
                            Some(Object::String(string)) => string.as_bytes().to_vec(),
                            Some(Object::Reference(id)) => document.stream_data(*id)?,
                            _ => {
                                return Err(Error::malformed(
                                    "Indexed image without a lookup table",
                                ));
                            }
                        };
                        Ok(Self::Indexed {
                            base: Box::new(base),
                            lookup,
                        })
                    }
                    b"ICCBased" => {
                        let stream = match items.get(1) {
                            Some(Object::Reference(id)) => document.stream(*id)?,
                            _ => return Err(Error::malformed("ICCBased without a stream")),
                        };
                        let components = stream
                            .dict()
                            .get(b"N")
                            .and_then(Object::as_integer)
                            .unwrap_or(3);
                        match components {
                            1 => Ok(Self::Gray),
                            3 => Ok(Self::Rgb),
                            4 => Ok(Self::Cmyk),
                            _ => Err(Error::malformed("unsupported ICCBased components")),
                        }
                    }
                    _ => Err(Error::malformed("unsupported image /ColorSpace array")),
                }
            }
            _ => Err(Error::malformed("unsupported image /ColorSpace value")),
        }
    }

    fn components(&self) -> usize {
        match self {
            Self::Gray => 1,
            Self::Rgb => 3,
            Self::Cmyk => 4,
            Self::Indexed { .. } => 1,
        }
    }
}

fn integer(dict: &Dictionary, key: &[u8]) -> Result<u32> {
    dict.get(key)
        .and_then(Object::as_integer)
        .and_then(|value| u32::try_from(value).ok())
        .ok_or_else(|| Error::malformed("image without integer /Width and /Height"))
}

/// How many components the stream's `/ColorSpace` declares, when it is a name or
/// a known family — enough to know whether a JPEG is CMYK.
fn dict_component_count(stream: &Stream) -> Option<usize> {
    match stream.dict().get(b"ColorSpace") {
        Some(Object::Name(name)) if name == b"DeviceCMYK" => Some(4),
        Some(Object::Name(name)) if name == b"DeviceGray" => Some(1),
        Some(Object::Name(name)) if name == b"DeviceRGB" => Some(3),
        _ => None,
    }
}

/// Widen packed one-bit samples to one byte each, 0 or 255.
///
/// PDF pads each row to a byte boundary, so a 1728-pixel fax line occupies 216
/// bytes; a row shorter than its padding is malformed rather than merely short.
fn widen_one_bit(data: &[u8], width: u32, height: u32, components: usize) -> Result<Vec<u8>> {
    if components != 1 {
        return Err(Error::malformed(
            "one-bit samples need a single-component colour space",
        ));
    }
    let bits_per_row = usize::try_from(width).unwrap_or(0);
    let stride = bits_per_row.div_ceil(8);
    let rows = usize::try_from(height).unwrap_or(0);
    if data.len() < stride.saturating_mul(rows) {
        return Err(Error::malformed(
            "one-bit image data is shorter than its rows",
        ));
    }
    let mut out = Vec::with_capacity(bits_per_row.saturating_mul(rows));
    for row in 0..rows {
        for column in 0..bits_per_row {
            let byte = data[row * stride + column / 8];
            let shift = 7 - column % 8;
            let bit = (byte >> shift) & 1;
            out.push(if bit == 1 { 255 } else { 0 });
        }
    }
    Ok(out)
}

/// Whether a JPEG carries an Adobe APP14 marker, which is what makes its CMYK
/// samples stored inverted (PDF 7.4.8).
///
/// The marker is `FFEE` then a two-byte length and the identifier `Adobe`; only
/// the identifier matters here, because the transform byte says whether the
/// samples are plain CMYK or YCCK, and both are stored inverted.
fn has_adobe_marker(data: &[u8]) -> bool {
    let mut index = 2; // past the `FF D8` start-of-image marker
    while index + 4 <= data.len() {
        if data[index] != 0xFF {
            return false;
        }
        let marker = data[index + 1];
        // Segments with no payload.
        if matches!(marker, 0xD8 | 0x01 | 0xD0..=0xD7) {
            index += 2;
            continue;
        }
        let length = usize::from(u16::from_be_bytes([data[index + 2], data[index + 3]]));
        if length < 2 {
            return false;
        }
        if marker == 0xEE {
            let payload = &data[index + 4..(index + 2 + length).min(data.len())];
            return payload.starts_with(b"Adobe");
        }
        // Start of scan: no more header segments follow.
        if marker == 0xDA {
            return false;
        }
        index += 2 + length;
    }
    false
}

/// Whether the stream's filter chain ends in `name`.
fn ends_in(dict: &Dictionary, name: &[u8]) -> bool {
    match dict.get(b"Filter") {
        Some(Object::Name(filter)) => filter == name,
        Some(Object::Array(items)) => items
            .iter()
            .rev()
            .find_map(Object::as_name)
            .is_some_and(|filter| filter == name),
        _ => false,
    }
}

/// Whether the stream's filter chain ends in `/DCTDecode`.
fn is_dct(dict: &Dictionary) -> bool {
    ends_in(dict, b"DCTDecode")
}

/// Whether the stream's filter chain ends in `/JPXDecode` (7.4.9).
fn is_jpx(dict: &Dictionary) -> bool {
    ends_in(dict, b"JPXDecode")
}

/// Whether the stream's filter chain ends in `/JBIG2Decode` (7.4.7).
fn is_jbig2(dict: &Dictionary) -> bool {
    ends_in(dict, b"JBIG2Decode")
}

/// Follow one indirect reference; deeper chains are not needed for images.
pub(crate) fn resolve(document: &Document, object: Option<&Object>) -> Result<Object> {
    match object {
        Some(Object::Reference(id)) => document.get_object(*id),
        Some(other) => Ok(other.clone()),
        None => Ok(Object::Null),
    }
}

/// How many components a JPX colour space needs, or why it is refused.
///
/// `/JPXDecode` takes its colour space from the codestream (7.4.9), and this
/// renderer can paint grey, RGB and CMYK. An ICC or unnamed space would need
/// colour management, so it is reported by name instead of mapped by component
/// count — the failure mode that guesses is the one that draws a wrong colour
/// with full confidence.
#[cfg(feature = "jpx")]
fn jpx_components(space: &hayro_jpeg2000::ColorSpace) -> Result<usize> {
    match space {
        hayro_jpeg2000::ColorSpace::Gray => Ok(1),
        hayro_jpeg2000::ColorSpace::RGB => Ok(3),
        hayro_jpeg2000::ColorSpace::CMYK => Ok(4),
        hayro_jpeg2000::ColorSpace::Icc { .. } => Err(Error::Unsupported {
            what: "a /JPXDecode image in an ICC colour space",
        }),
        hayro_jpeg2000::ColorSpace::Unknown { .. } => Err(Error::Unsupported {
            what: "a /JPXDecode image in a colour space it cannot name",
        }),
    }
}

/// Resolves the `/JBIG2Globals` stream of a `/JBIG2Decode` image, if it names one.
#[cfg(feature = "jbig2")]
fn globals_bytes(document: &Document, dict: &Dictionary) -> Result<Option<Vec<u8>>> {
    let Some(parms) = dict.get(b"DecodeParms") else {
        return Ok(None);
    };
    let parms = resolve(document, Some(parms))?;
    let Some(parms) = parms.as_dict() else {
        return Ok(None);
    };
    let Some(globals) = parms.get(b"JBIG2Globals") else {
        return Ok(None);
    };
    let globals = resolve(document, Some(globals))?;
    let Some(stream) = globals.as_stream() else {
        return Err(Error::malformed("/JBIG2Globals is not a stream"));
    };
    document.decode_stream(stream).map(Some)
}

/// A JBIG2 sink that writes packed 1-bit rows the way a PDF image expects them.
///
/// `hayro-jbig2` reports `black`, and a 1-bit `/DeviceGray` sample is 1 for
/// **white** unless `/Decode` inverts it (`src/fax.rs:37` and the CCITT writer
/// beside it). Writing `black` straight through draws the page as its negative,
/// which is why the tests assert ink on white instead of trusting the sense.
#[cfg(feature = "jbig2")]
struct Rows {
    packed: Vec<u8>,
    /// Bytes per row: a 1-bit PDF image is **row-aligned to a byte**, so a row of
    /// 399 pixels occupies 50 bytes and leaves one bit of padding.
    stride: usize,
    row: usize,
    column: usize,
}

#[cfg(feature = "jbig2")]
impl Rows {
    fn new(width: usize, height: usize) -> Self {
        Self {
            packed: vec![0; width.div_ceil(8) * height],
            stride: width.div_ceil(8),
            row: 0,
            column: 0,
        }
    }

    /// Write `count` samples of one value, MSB first, in the current row.
    ///
    /// The row offset is what makes this a PDF image rather than a bit stream: with
    /// a width that is not a multiple of eight, packing the pixels contiguously
    /// shifts every row by one bit, which is a defect this sink had — it cost
    /// 19 553 differing pixels against pdfium's reference raster (12.25 %, mean
    /// |Δ| 31.24) while the decoder's own output was byte-exact.
    fn run(&mut self, white: bool, count: usize) {
        for _ in 0..count {
            if white {
                let byte = self.row * self.stride + self.column / 8;
                let shift = 7 - self.column % 8;
                if let Some(slot) = self.packed.get_mut(byte) {
                    *slot |= 1 << shift;
                }
            }
            self.column += 1;
        }
    }

    fn finish(self) -> Vec<u8> {
        self.packed
    }
}

#[cfg(feature = "jbig2")]
impl hayro_jbig2::Decoder for Rows {
    fn push_pixel(&mut self, black: bool) {
        self.run(!black, 1);
    }

    fn push_pixel_chunk(&mut self, black: bool, chunk_count: u32) {
        self.run(!black, 8 * chunk_count as usize);
    }

    fn next_line(&mut self) {
        self.row += 1;
        self.column = 0;
    }
}

#[cfg(test)]
mod tests {
    use super::Image;
    use crate::canvas::{BlendMode, Canvas, ClipMask, Color};
    use crate::geom::Matrix;

    /// A JPX colour space this renderer cannot honour is refused by name, not
    /// mapped by component count: the guess is what draws a confident wrong
    /// colour.
    #[cfg(feature = "jpx")]
    #[test]
    fn jpx_refuses_the_colour_spaces_it_cannot_paint() {
        use hayro_jpeg2000::ColorSpace;

        assert_eq!(super::jpx_components(&ColorSpace::Gray).unwrap(), 1);
        assert_eq!(super::jpx_components(&ColorSpace::RGB).unwrap(), 3);
        assert_eq!(super::jpx_components(&ColorSpace::CMYK).unwrap(), 4);
        let icc = super::jpx_components(&ColorSpace::Icc {
            profile: Vec::new(),
            num_channels: 3,
        })
        .expect_err("an ICC space needs colour management");
        assert!(icc.to_string().contains("ICC"), "{icc}");
        let unknown = super::jpx_components(&ColorSpace::Unknown { num_channels: 2 })
            .expect_err("an unnamed space is refused");
        assert!(unknown.to_string().contains("cannot name"), "{unknown}");
    }

    fn image(width: u32, height: u32, interpolate: bool) -> Image {
        let mut pixels = Vec::new();
        for y in 0..height {
            for x in 0..width {
                pixels.push(if (x + y) % 2 == 0 {
                    Color::BLACK
                } else {
                    Color::WHITE
                });
            }
        }
        Image {
            width,
            height,
            pixels,
            interpolate,
            masked: None,
        }
    }

    #[test]
    fn nearest_sampling_returns_whole_pixels() {
        let image = image(2, 2, false);
        assert_eq!(image.sample(0.25, 0.25), Color::BLACK);
        assert_eq!(image.sample(0.75, 0.25), Color::WHITE);
        assert_eq!(image.sample(0.25, 0.75), Color::WHITE);
    }

    #[test]
    fn bilinear_sampling_blends_neighbours() {
        let image = image(2, 2, true);
        let middle = image.sample(0.5, 0.5);
        assert!((middle.r - 0.5).abs() < 1e-9, "{middle:?}");
    }

    #[test]
    fn painting_covers_the_unit_square_transform() {
        let image = image(2, 2, false);
        let mut canvas = Canvas::new(4, 4, Color::WHITE);
        let mask = ClipMask::all(4, 4);
        // Unit square scaled to 4×4 with y flipped like the page transform.
        let ctm = Matrix::new(4.0, 0.0, 0.0, -4.0, 0.0, 4.0);
        image.paint(&mut canvas, &mask, ctm, 1.0, BlendMode::Normal);
        assert_eq!(canvas.pixel(0, 0), Some([0, 0, 0, 255]));
        assert_eq!(canvas.pixel(3, 0), Some([255, 255, 255, 255]));
        assert_eq!(canvas.pixel(0, 3), Some([255, 255, 255, 255]));
        assert_eq!(canvas.pixel(3, 3), Some([0, 0, 0, 255]));
    }
}