otf-pixels-codec-png 0.2.0

PNG codec for otf-pixels, implemented from scratch including DEFLATE.
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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
//! The PNG decoder.
//!
//! # Laziness
//!
//! Construction reads the chunks up to the first `IDAT` and stops at its
//! header, so the descriptor and orientation are known without touching pixel
//! data (SPEC §Guarantees 3). Everything that changes how a pixel is read or
//! shown — `PLTE`, `tRNS`, `eXIf` — precedes `IDAT` (§5.6), so nothing found
//! later can revise them. The image data is read on the first
//! [`Decoder::read_row`].
//!
//! # Memory
//!
//! A non-interlaced PNG **streams**: chunks are walked one piece at a time,
//! inflate runs incrementally, and each scanline is unfiltered and expanded as
//! it arrives. Peak memory is two scanlines plus the 32 KiB inflate window and
//! a read buffer — none of which grow with image height. That is what makes
//! SPEC §Guarantees 1 true for PNG rather than merely claimed.
//!
//! Interlaced PNG is **internally buffered**, as SPEC §Formats says: Adam7
//! scatters each pass across the whole image, so no row is final until every
//! pass has been read. That is ADR-0005's stated allowance for formats that
//! leave no choice.

use otf_pixels_core::{
    Codec, DecodeCapability, Decoder, Format, ImageDescriptor, Limits, Orientation, PixelFormat,
    PixelsError, Result, Source,
};

use crate::format::{
    ChunkReader, ChunkStream, ColorType, Filter, Header, SIGNATURE, adam7_pass_size,
    adam7_position, unfilter,
};
use otf_pixels_compress::{ZlibStream, zlib_decompress};

/// The specification's cap on a `PLTE` chunk: 256 entries of three bytes.
const MAX_PLTE: usize = 256 * 3;
/// The largest `tRNS` chunk any colour type permits: 256 palette alphas.
const MAX_TRNS: usize = 256;
/// How much compressed data is pulled from the source per refill.
const READ_CHUNK: usize = 64 * 1024;
/// How much of an `eXIf` chunk is read looking for the orientation.
///
/// The tag lives in the first directory, which writers put at the front; the
/// rest is typically a thumbnail. A tag beyond this is not found, which is
/// metadata declined rather than an image refused.
const EXIF_PREFIX: usize = 64 * 1024;

/// The largest ICC profile accepted, compressed or not. Real profiles run
/// from a few hundred bytes (matrix/TRC) to a megabyte or two (LUT-based); a
/// larger `iCCP` is declined as metadata, not refused as an image.
const MAX_ICC: usize = 4 << 20;

/// Transparency from a `tRNS` chunk (§11.3.2.1).
#[derive(Debug, Clone)]
enum Transparency {
    /// One transparent grey level, in the image's bit depth.
    Gray(u16),
    /// One transparent RGB triple, in the image's bit depth.
    Rgb(u16, u16, u16),
    /// Per-palette-entry alpha; entries beyond the list are opaque.
    Palette(Vec<u8>),
}

/// The profile in an `iCCP` payload (§11.3.3.3): a 1-79 byte name, a NUL,
/// compression method 0, and the zlib-compressed profile.
fn parse_iccp(data: &[u8]) -> Option<Vec<u8>> {
    let nul = data
        .iter()
        .position(|&b| b == 0)
        .filter(|&n| (1..=79).contains(&n))?;
    let (&method, compressed) = data.get(nul + 1..)?.split_first()?;
    if method != 0 {
        return None;
    }
    zlib_decompress(compressed, MAX_ICC).ok()
}

/// Decodes a PNG stream.
#[derive(Debug)]
pub struct PngDecoder<S: Source> {
    header: Header,
    descriptor: ImageDescriptor,
    /// Everything read before the image data, until a decode path takes it.
    prelude: Option<Prelude<S>>,
    orientation: Orientation,
    /// The `iCCP` profile, decompressed.
    icc: Option<Vec<u8>>,
    /// The decoded image in output format, produced on first row read.
    ///
    /// Only used by the interlaced path; a non-interlaced image never
    /// materializes here.
    raster: Option<Vec<u8>>,
    /// Per-row state for the non-interlaced streaming path.
    stream: Option<Box<Streaming<S>>>,
    row: u32,
}

/// The chunks before the image data, and the stream left at the first `IDAT`.
#[derive(Debug)]
struct Prelude<S: Source> {
    /// Positioned inside the first `IDAT`, its payload unread.
    chunks: ChunkStream<S>,
    palette: Option<Vec<[u8; 3]>>,
    transparency: Option<Transparency>,
}

/// Everything the streaming path carries between rows.
///
/// This is the whole memory cost of decoding a non-interlaced PNG: two
/// scanlines, the inflate window, and one read buffer — none of which grow
/// with image height.
#[derive(Debug)]
struct Streaming<S: Source> {
    chunks: ChunkStream<S>,
    zlib: ZlibStream,
    /// Decompressed but not yet consumed filtered bytes.
    filtered: Vec<u8>,
    /// Read cursor into `filtered`.
    at: usize,
    /// The previous reconstructed scanline, which filters predict from.
    previous: Vec<u8>,
    palette: Option<Vec<[u8; 3]>>,
    transparency: Option<Transparency>,
    /// Set once `IEND` is reached or the final `IDAT` is consumed.
    input_done: bool,
}

impl<S: Source> PngDecoder<S> {
    /// Parse the signature, `IHDR` and every chunk before the image data.
    ///
    /// # Errors
    ///
    /// Returns [`PixelsError::Malformed`] for a bad signature, header or
    /// pre-`IDAT` chunk, or [`PixelsError::LimitExceeded`] if the dimensions
    /// exceed `limits`.
    pub fn new(mut source: S, limits: Limits) -> Result<Self> {
        // Signature plus a complete IHDR chunk: 8 + 4 + 4 + 13 + 4.
        let mut prefix = vec![0_u8; 33];
        source.read_exact(&mut prefix)?;

        let mut reader = ChunkReader::new(&prefix)?;
        let chunk = reader.next_chunk()?;
        if !chunk.is(b"IHDR") {
            return Err(PixelsError::malformed(
                "png",
                format!("first chunk must be IHDR, got `{}`", chunk.name()),
            ));
        }
        let header = Header::parse(&chunk.data, &limits)?;

        let mut chunks = ChunkStream::new(source);
        let mut palette: Option<Vec<[u8; 3]>> = None;
        let mut transparency: Option<Transparency> = None;
        let mut orientation = None;
        let mut icc = None;
        loop {
            let kind = chunks.open_next()?;
            match &kind {
                b"IHDR" => {
                    return Err(PixelsError::malformed("png", "more than one IHDR"));
                }
                b"PLTE" => {
                    let data = chunks.read_payload_to_end(MAX_PLTE)?;
                    palette = Some(parse_plte(&data)?);
                    chunks.close()?;
                }
                b"tRNS" => {
                    let data = chunks.read_payload_to_end(MAX_TRNS)?;
                    transparency = Some(parse_trns(&data, header.color_type)?);
                    chunks.close()?;
                }
                b"eXIf" => {
                    let mut exif = vec![0_u8; EXIF_PREFIX];
                    let mut filled = 0;
                    while let Some(rest) = exif.get_mut(filled..) {
                        match chunks.read_payload(rest)? {
                            0 => break,
                            n => filled += n,
                        }
                    }
                    exif.truncate(filled);
                    chunks.skip_payload()?;
                    chunks.close()?;
                    // The first one wins; §11.3.6.1 permits only one.
                    orientation = orientation.or_else(|| Orientation::from_exif_block(&exif));
                }
                b"iCCP" => {
                    // One byte past the cap tells an oversized chunk apart.
                    let mut data = vec![0_u8; MAX_ICC + 1];
                    let mut filled = 0;
                    while let Some(rest) = data.get_mut(filled..).filter(|r| !r.is_empty()) {
                        match chunks.read_payload(rest)? {
                            0 => break,
                            n => filled += n,
                        }
                    }
                    data.truncate(filled);
                    chunks.skip_payload()?;
                    chunks.close()?;
                    // §11.3.3.3 permits one; a broken or oversized one is
                    // dropped.
                    if filled <= MAX_ICC {
                        icc = icc.or_else(|| parse_iccp(&data));
                    }
                }
                b"IDAT" => break,
                b"IEND" => {
                    return Err(PixelsError::malformed("png", "no IDAT data"));
                }
                _ => {
                    if !chunks.is_ancillary() {
                        return Err(PixelsError::malformed(
                            "png",
                            format!("unknown critical chunk `{}`", chunks.name()),
                        ));
                    }
                    chunks.skip_payload()?;
                    chunks.close()?;
                }
            }
        }

        if header.color_type == ColorType::Palette && palette.is_none() {
            return Err(PixelsError::malformed(
                "png",
                "palette image has no PLTE chunk",
            ));
        }
        let descriptor = header.descriptor(transparency.is_some(), &limits)?;

        Ok(Self {
            header,
            descriptor,
            prelude: Some(Prelude {
                chunks,
                palette,
                transparency,
            }),
            orientation: orientation.unwrap_or_default(),
            icc,
            raster: None,
            stream: None,
            row: 0,
        })
    }

    /// The parsed header.
    #[must_use]
    pub const fn header(&self) -> Header {
        self.header
    }

    /// Start the streaming path from where construction stopped.
    fn begin_streaming(&mut self) -> Result<Streaming<S>> {
        let Some(Prelude {
            chunks,
            palette,
            transparency,
        }) = self.prelude.take()
        else {
            return Err(PixelsError::graph("png source was already consumed"));
        };

        let row_bytes = self.header.row_bytes(self.header.width);
        Ok(Streaming {
            chunks,
            // The limit is the exact filtered size the header implies, which
            // is what makes a decompression bomb a malformed-input error.
            zlib: ZlibStream::new(self.header.filtered_size()),
            filtered: Vec::new(),
            at: 0,
            previous: vec![0_u8; row_bytes],
            palette,
            transparency,
            input_done: false,
        })
    }

    /// Read the rest of the stream and produce the output-format raster.
    fn decode_image(&mut self) -> Result<Vec<u8>> {
        let Some(Prelude {
            mut chunks,
            palette,
            transparency,
        }) = self.prelude.take()
        else {
            return Err(PixelsError::graph("png source was already consumed"));
        };

        // Construction left the first IDAT open; collect it and any that
        // follow, skipping ancillary chunks between them.
        let mut compressed: Vec<u8> = Vec::new();
        let mut buffer = vec![0_u8; READ_CHUNK];
        loop {
            loop {
                let read = chunks.read_payload(&mut buffer)?;
                if read == 0 {
                    break;
                }
                compressed.extend_from_slice(buffer.get(..read).unwrap_or(&[]));
            }
            chunks.close()?;
            match &chunks.open_next()? {
                b"IDAT" => {}
                b"IEND" => {
                    chunks.skip_payload()?;
                    chunks.close()?;
                    break;
                }
                _ => {
                    // Unknown critical chunks mean the image cannot be
                    // rendered correctly; ancillary ones are skipped (§5.4).
                    if !chunks.is_ancillary() {
                        return Err(PixelsError::malformed(
                            "png",
                            format!("unknown critical chunk `{}`", chunks.name()),
                        ));
                    }
                    chunks.skip_payload()?;
                }
            }
        }

        // The limit is the exact filtered size the header implies, which is
        // what makes a decompression bomb a malformed-input error.
        let filtered = zlib_decompress(&compressed, self.header.filtered_size())
            .map_err(crate::compress_error)?;
        let samples = self.unfilter_all(&filtered)?;
        self.expand(&samples, palette.as_deref(), transparency.as_ref())
    }

    /// Reverse filtering, producing unfiltered sample rows in PNG layout.
    ///
    /// For interlaced images the passes are deinterlaced into a single raster
    /// of `height` rows here, so everything downstream sees one image.
    fn unfilter_all(&self, filtered: &[u8]) -> Result<Vec<u8>> {
        let stride = self.header.filter_stride();
        let full_row = self.header.row_bytes(self.header.width);

        if !self.header.interlaced {
            let mut out = vec![0_u8; self.header.height as usize * full_row];
            let mut previous = vec![0_u8; full_row];
            let mut at = 0;
            for y in 0..self.header.height as usize {
                let filter_byte = filtered
                    .get(at)
                    .copied()
                    .ok_or_else(|| PixelsError::malformed("png", "raster ends early"))?;
                let filter = Filter::from_byte(filter_byte)?;
                at += 1;
                let row = filtered
                    .get(at..at + full_row)
                    .ok_or_else(|| PixelsError::malformed("png", "scanline ends early"))?;
                at += full_row;

                let mut current = row.to_vec();
                unfilter(filter, &mut current, &previous, stride)?;
                let start = y * full_row;
                if let Some(slot) = out.get_mut(start..start + full_row) {
                    slot.copy_from_slice(&current);
                }
                previous = current;
            }
            return Ok(out);
        }

        // Adam7: each pass is an independent filtered raster, then its pixels
        // are scattered into their positions in the full image.
        let mut out = vec![0_u8; self.header.height as usize * full_row];
        let mut at = 0;
        for pass in 0..7 {
            let (pass_width, pass_height) =
                adam7_pass_size(pass, self.header.width, self.header.height);
            if pass_width == 0 || pass_height == 0 {
                continue;
            }
            let pass_row = self.header.row_bytes(pass_width);
            let mut previous = vec![0_u8; pass_row];
            for y in 0..pass_height {
                let filter_byte = filtered.get(at).copied().ok_or_else(|| {
                    PixelsError::malformed("png", format!("pass {pass} ends early"))
                })?;
                let filter = Filter::from_byte(filter_byte)?;
                at += 1;
                let row = filtered.get(at..at + pass_row).ok_or_else(|| {
                    PixelsError::malformed("png", format!("pass {pass} scanline ends early"))
                })?;
                at += pass_row;

                let mut current = row.to_vec();
                unfilter(filter, &mut current, &previous, stride)?;
                for x in 0..pass_width {
                    let (image_x, image_y) = adam7_position(pass, x, y);
                    copy_pixel_bits(
                        &current,
                        x as usize,
                        &mut out,
                        image_y as usize * full_row,
                        image_x as usize,
                        self.header.bits_per_pixel(),
                    );
                }
                previous = current;
            }
        }
        Ok(out)
    }

    /// Convert unfiltered PNG samples into the engine's output format.
    fn expand(
        &self,
        samples: &[u8],
        palette: Option<&[[u8; 3]]>,
        transparency: Option<&Transparency>,
    ) -> Result<Vec<u8>> {
        let height = self.header.height as usize;
        let row_bytes = self.header.row_bytes(self.header.width);
        let out_row = self.descriptor.row_bytes();
        let mut out = vec![0_u8; height * out_row];

        for y in 0..height {
            let row = samples
                .get(y * row_bytes..(y + 1) * row_bytes)
                .ok_or_else(|| PixelsError::malformed("png", "sample row missing"))?;
            let Some(slot) = out.get_mut(y * out_row..(y + 1) * out_row) else {
                return Err(PixelsError::graph("output row is missing"));
            };
            self.expand_row(row, palette, transparency, slot)?;
        }
        Ok(out)
    }

    /// Convert one unfiltered PNG scanline into the engine's output format.
    ///
    /// Shared by both paths: the streaming one calls it per scanline as it
    /// arrives, the interlaced one per row of the deinterlaced raster. Having
    /// one implementation is what makes "interlaced and non-interlaced decode
    /// identically" a structural fact rather than a coincidence.
    fn expand_row(
        &self,
        samples: &[u8],
        palette: Option<&[[u8; 3]]>,
        transparency: Option<&Transparency>,
        out: &mut [u8],
    ) -> Result<()> {
        let format = self.descriptor.pixel;
        let width = self.header.width as usize;
        let depth = self.header.bit_depth;
        let channels = self.header.color_type.channels();
        let max = ((1_u32 << depth) - 1) as u16;

        if depth == 8 {
            // 8-bit samples already in the output layout are the common
            // case, and the per-pixel conversion below is the identity for
            // them (`scale8` of an 8-bit value is that value).
            let same_layout = matches!(
                (self.header.color_type, format),
                (ColorType::Rgb, PixelFormat::Rgb8)
                    | (ColorType::Rgba, PixelFormat::Rgba8)
                    | (ColorType::Grayscale, PixelFormat::Gray8)
                    | (ColorType::GrayscaleAlpha, PixelFormat::GrayA8)
            );
            if same_layout && samples.len() == out.len() {
                out.copy_from_slice(samples);
                return Ok(());
            }
            if matches!(self.header.color_type, ColorType::Palette) {
                return expand_palette_row(samples, format, palette, transparency, out);
            }
        }

        let mut at = 0;
        for x in 0..width {
            let mut channel = [0_u16; 4];
            for (c, slot) in channel.iter_mut().take(channels).enumerate() {
                *slot = read_sample(samples, x * channels + c, depth);
            }
            write_pixel(
                out,
                &mut at,
                format,
                self.header.color_type,
                &channel,
                depth,
                max,
                palette,
                transparency,
            )?;
        }
        Ok(())
    }

    /// The buffered path, used for interlaced images.
    fn read_row_buffered(&mut self, out: &mut [u8]) -> Result<()> {
        if self.raster.is_none() {
            self.raster = Some(self.decode_image()?);
        }
        let Some(raster) = self.raster.as_ref() else {
            return Err(PixelsError::graph("raster vanished after decoding"));
        };
        if self.row >= self.descriptor.height {
            return Err(PixelsError::invalid_argument(
                "out",
                format!("all {} rows have already been read", self.descriptor.height),
            ));
        }
        let row_bytes = self.descriptor.row_bytes();
        if out.len() != row_bytes {
            return Err(PixelsError::invalid_argument(
                "out",
                format!("row buffer is {} bytes, expected {row_bytes}", out.len()),
            ));
        }
        let start = self.row as usize * row_bytes;
        let row = raster
            .get(start..start + row_bytes)
            .ok_or_else(|| PixelsError::malformed("png", "decoded raster is short"))?;
        out.copy_from_slice(row);
        self.row += 1;
        Ok(())
    }
}

impl<S: Source> Streaming<S> {
    /// Pull more compressed bytes and decompress them.
    ///
    /// Returns `false` once the stream is exhausted, so a caller asking for a
    /// scanline that never arrives gets a truncation error rather than a hang.
    fn refill(&mut self) -> Result<bool> {
        if self.input_done {
            return Ok(false);
        }
        let mut buffer = vec![0_u8; READ_CHUNK];

        // Walk forward until this feed produced some output, or the stream
        // ends. An IDAT boundary or a run of ancillary chunks can legitimately
        // yield nothing, so one pass is not enough.
        loop {
            if self.chunks.payload_done() {
                self.chunks.close()?;
                // Find the next IDAT, skipping whatever sits between them.
                loop {
                    let kind = self.chunks.open_next()?;
                    match &kind {
                        b"IDAT" => break,
                        b"IEND" => {
                            // Closed, not just recognised: IEND carries a CRC
                            // like any other chunk, and a stream truncated
                            // inside it is still a truncated stream.
                            self.chunks.skip_payload()?;
                            self.chunks.close()?;
                            self.input_done = true;
                            let tail = self.zlib.finish().map_err(crate::compress_error)?;
                            self.filtered.extend_from_slice(&tail);
                            return Ok(!tail.is_empty());
                        }
                        _ => {
                            if !self.chunks.is_ancillary() {
                                return Err(PixelsError::malformed(
                                    "png",
                                    format!("unknown critical chunk `{}`", self.chunks.name()),
                                ));
                            }
                            self.chunks.skip_payload()?;
                            self.chunks.close()?;
                        }
                    }
                }
            }

            let read = self.chunks.read_payload(&mut buffer)?;
            if read == 0 {
                continue;
            }
            let produced = self
                .zlib
                .push(buffer.get(..read).unwrap_or(&[]))
                .map_err(crate::compress_error)?;
            if !produced.is_empty() {
                self.filtered.extend_from_slice(&produced);
                return Ok(true);
            }
        }
    }

    /// Consume whatever follows the last scanline, so the stream is verified.
    ///
    /// The zlib Adler-32 and the trailing `IEND` both sit *after* the final
    /// row. A caller that stops reading at the last row would otherwise never
    /// reach them, and a corrupt checksum would pass unnoticed — which is
    /// exactly what PngSuite's `xcsn0g01` checks.
    fn finalize(&mut self) -> Result<()> {
        while self.refill()? {}
        if !self.input_done {
            return Err(PixelsError::malformed(
                "png",
                "stream ends without an IEND chunk",
            ));
        }
        Ok(())
    }

    /// Reconstruct the next scanline, returning it in PNG sample layout.
    fn next_scanline(&mut self, row_bytes: usize, stride: usize) -> Result<Vec<u8>> {
        let want = row_bytes + 1;
        while self.filtered.len() - self.at < want {
            if !self.refill()? {
                return Err(PixelsError::malformed(
                    "png",
                    "image data ends before the last scanline",
                ));
            }
        }

        let filter_byte = self
            .filtered
            .get(self.at)
            .copied()
            .ok_or_else(|| PixelsError::malformed("png", "scanline ends early"))?;
        let filter = Filter::from_byte(filter_byte)?;
        let start = self.at + 1;
        let mut current = self
            .filtered
            .get(start..start + row_bytes)
            .ok_or_else(|| PixelsError::malformed("png", "scanline ends early"))?
            .to_vec();
        self.at = start + row_bytes;

        // Consumed bytes are dropped rather than accumulated, which is what
        // keeps this buffer at one scanline rather than one image.
        if self.at >= self.filtered.len() {
            self.filtered.clear();
            self.at = 0;
        } else if self.at > READ_CHUNK {
            self.filtered.drain(..self.at);
            self.at = 0;
        }

        unfilter(filter, &mut current, &self.previous, stride)?;
        self.previous.clear();
        self.previous.extend_from_slice(&current);
        Ok(current)
    }
}

/// Parse a `PLTE` payload into RGB triples.
fn parse_plte(data: &[u8]) -> Result<Vec<[u8; 3]>> {
    if data.len() % 3 != 0 || data.is_empty() {
        return Err(PixelsError::malformed(
            "png",
            format!("PLTE length {} is not a positive multiple of 3", data.len()),
        ));
    }
    if data.len() / 3 > 256 {
        return Err(PixelsError::malformed(
            "png",
            "PLTE has more than 256 entries",
        ));
    }
    Ok(data
        .chunks_exact(3)
        .map(|rgb| {
            [
                rgb.first().copied().unwrap_or(0),
                rgb.get(1).copied().unwrap_or(0),
                rgb.get(2).copied().unwrap_or(0),
            ]
        })
        .collect())
}

/// Copy one pixel's bits between rasters, handling sub-byte depths.
fn copy_pixel_bits(
    source_row: &[u8],
    source_x: usize,
    out: &mut [u8],
    row_start: usize,
    dest_x: usize,
    bits_per_pixel: usize,
) {
    if bits_per_pixel >= 8 {
        let bytes = bits_per_pixel / 8;
        for byte in 0..bytes {
            let value = source_row
                .get(source_x * bytes + byte)
                .copied()
                .unwrap_or(0);
            if let Some(slot) = out.get_mut(row_start + dest_x * bytes + byte) {
                *slot = value;
            }
        }
        return;
    }
    // Sub-byte: read the packed field and write it at the destination offset.
    let value = read_bits(source_row, source_x, bits_per_pixel);
    write_bits(out, row_start, dest_x, bits_per_pixel, value);
}

/// Read a packed sub-byte field, most-significant-first within each byte.
fn read_bits(row: &[u8], index: usize, bits: usize) -> u8 {
    let per_byte = 8 / bits;
    let byte = row.get(index / per_byte).copied().unwrap_or(0);
    let shift = 8 - bits * (index % per_byte + 1);
    (byte >> shift) & ((1 << bits) - 1) as u8
}

/// Write a packed sub-byte field.
fn write_bits(out: &mut [u8], row_start: usize, index: usize, bits: usize, value: u8) {
    let per_byte = 8 / bits;
    let offset = row_start + index / per_byte;
    let shift = 8 - bits * (index % per_byte + 1);
    let mask = ((1 << bits) - 1) as u8;
    if let Some(slot) = out.get_mut(offset) {
        *slot = (*slot & !(mask << shift)) | ((value & mask) << shift);
    }
}

/// Read sample `index` of a row at `depth` bits.
fn read_sample(row: &[u8], index: usize, depth: u8) -> u16 {
    match depth {
        16 => {
            // PNG samples are big-endian (§7.1).
            let high = row.get(index * 2).copied().unwrap_or(0);
            let low = row.get(index * 2 + 1).copied().unwrap_or(0);
            u16::from_be_bytes([high, low])
        }
        8 => u16::from(row.get(index).copied().unwrap_or(0)),
        bits => u16::from(read_bits(row, index, bits as usize)),
    }
}

/// Scale a sample from `max` to the full 8-bit range.
///
/// The spec's rule: the value is replicated, not shifted, so 1-bit 1 becomes
/// 255 rather than 128 (§13.13).
const fn scale8(value: u16, max: u16) -> u8 {
    if max == 0 {
        return 0;
    }
    ((value as u32 * 255 + max as u32 / 2) / max as u32) as u8
}

/// Expand one row of 8-bit palette indices, a byte per pixel.
///
/// The per-pixel path handles this too; this one looks each index up once
/// and writes the entry whole, with the same errors.
fn expand_palette_row(
    indices: &[u8],
    format: PixelFormat,
    palette: Option<&[[u8; 3]]>,
    transparency: Option<&Transparency>,
    out: &mut [u8],
) -> Result<()> {
    let entries =
        palette.ok_or_else(|| PixelsError::malformed("png", "palette image without a palette"))?;
    let alphas = match transparency {
        Some(Transparency::Palette(alphas)) => alphas.as_slice(),
        _ => &[],
    };
    let channels = if format == PixelFormat::Rgba8 { 4 } else { 3 };
    for (&index, pixel) in indices.iter().zip(out.chunks_exact_mut(channels)) {
        let index = index as usize;
        let rgb = entries.get(index).ok_or_else(|| {
            PixelsError::malformed(
                "png",
                format!(
                    "palette index {index} is beyond the {}-entry palette",
                    entries.len()
                ),
            )
        })?;
        for (slot, &value) in pixel.iter_mut().zip(rgb) {
            *slot = value;
        }
        if let Some(alpha) = pixel.get_mut(3) {
            // Entries past the tRNS list are fully opaque.
            *alpha = alphas.get(index).copied().unwrap_or(255);
        }
    }
    Ok(())
}

/// Write one output pixel, converting from PNG's layout.
#[allow(
    clippy::too_many_arguments,
    reason = "one pixel conversion needs all of it"
)]
fn write_pixel(
    out: &mut [u8],
    at: &mut usize,
    format: PixelFormat,
    color_type: ColorType,
    channel: &[u16; 4],
    depth: u8,
    max: u16,
    palette: Option<&[[u8; 3]]>,
    transparency: Option<&Transparency>,
) -> Result<()> {
    /// Append one byte.
    fn push(out: &mut [u8], at: &mut usize, value: u8) {
        if let Some(slot) = out.get_mut(*at) {
            *slot = value;
        }
        *at += 1;
    }
    /// Append one native-endian 16-bit sample.
    fn push16(out: &mut [u8], at: &mut usize, value: u16) {
        for byte in value.to_ne_bytes() {
            push(out, at, byte);
        }
    }

    match color_type {
        ColorType::Palette => {
            let index = channel[0] as usize;
            let entries = palette
                .ok_or_else(|| PixelsError::malformed("png", "palette image without a palette"))?;
            let rgb = entries.get(index).copied().ok_or_else(|| {
                PixelsError::malformed(
                    "png",
                    format!(
                        "palette index {index} is beyond the {}-entry palette",
                        entries.len()
                    ),
                )
            })?;
            push(out, at, rgb[0]);
            push(out, at, rgb[1]);
            push(out, at, rgb[2]);
            if format == PixelFormat::Rgba8 {
                let alpha = match transparency {
                    Some(Transparency::Palette(alphas)) => {
                        // Entries past the tRNS list are fully opaque.
                        alphas.get(index).copied().unwrap_or(255)
                    }
                    _ => 255,
                };
                push(out, at, alpha);
            }
        }
        ColorType::Grayscale => {
            let transparent =
                matches!(transparency, Some(Transparency::Gray(key)) if *key == channel[0]);
            match format {
                PixelFormat::Gray8 => push(out, at, scale8(channel[0], max)),
                PixelFormat::Gray16 => push16(out, at, channel[0]),
                PixelFormat::GrayA8 => {
                    push(out, at, scale8(channel[0], max));
                    push(out, at, if transparent { 0 } else { 255 });
                }
                PixelFormat::Rgba16 => {
                    let value = if depth == 16 {
                        channel[0]
                    } else {
                        channel[0] * 257
                    };
                    push16(out, at, value);
                    push16(out, at, value);
                    push16(out, at, value);
                    push16(out, at, if transparent { 0 } else { u16::MAX });
                }
                other => {
                    return Err(PixelsError::unsupported(format!(
                        "greyscale cannot be written as {other}"
                    )));
                }
            }
        }
        ColorType::GrayscaleAlpha => match format {
            PixelFormat::GrayA8 => {
                push(out, at, scale8(channel[0], max));
                push(out, at, scale8(channel[1], max));
            }
            PixelFormat::Rgba16 => {
                push16(out, at, channel[0]);
                push16(out, at, channel[0]);
                push16(out, at, channel[0]);
                push16(out, at, channel[1]);
            }
            other => {
                return Err(PixelsError::unsupported(format!(
                    "grey+alpha cannot be written as {other}"
                )));
            }
        },
        ColorType::Rgb => {
            let transparent = matches!(
                transparency,
                Some(Transparency::Rgb(r, g, b))
                    if *r == channel[0] && *g == channel[1] && *b == channel[2]
            );
            match format {
                PixelFormat::Rgb8 => {
                    for &value in channel.iter().take(3) {
                        push(out, at, scale8(value, max));
                    }
                }
                PixelFormat::Rgb16 => {
                    for &value in channel.iter().take(3) {
                        push16(out, at, value);
                    }
                }
                PixelFormat::Rgba8 => {
                    for &value in channel.iter().take(3) {
                        push(out, at, scale8(value, max));
                    }
                    push(out, at, if transparent { 0 } else { 255 });
                }
                PixelFormat::Rgba16 => {
                    for &value in channel.iter().take(3) {
                        push16(out, at, value);
                    }
                    push16(out, at, if transparent { 0 } else { u16::MAX });
                }
                other => {
                    return Err(PixelsError::unsupported(format!(
                        "RGB cannot be written as {other}"
                    )));
                }
            }
        }
        ColorType::Rgba => match format {
            PixelFormat::Rgba8 => {
                for &value in channel {
                    push(out, at, scale8(value, max));
                }
            }
            PixelFormat::Rgba16 => {
                for &value in channel {
                    push16(out, at, value);
                }
            }
            other => {
                return Err(PixelsError::unsupported(format!(
                    "RGBA cannot be written as {other}"
                )));
            }
        },
    }
    Ok(())
}

/// Parse a `tRNS` payload for `color_type`.
fn parse_trns(data: &[u8], color_type: ColorType) -> Result<Transparency> {
    /// Read a big-endian `u16` at `offset`.
    fn be16(data: &[u8], offset: usize) -> u16 {
        u16::from_be_bytes([
            data.get(offset).copied().unwrap_or(0),
            data.get(offset + 1).copied().unwrap_or(0),
        ])
    }
    match color_type {
        ColorType::Grayscale => {
            if data.len() != 2 {
                return Err(PixelsError::malformed(
                    "png",
                    format!("greyscale tRNS must be 2 bytes, got {}", data.len()),
                ));
            }
            Ok(Transparency::Gray(be16(data, 0)))
        }
        ColorType::Rgb => {
            if data.len() != 6 {
                return Err(PixelsError::malformed(
                    "png",
                    format!("RGB tRNS must be 6 bytes, got {}", data.len()),
                ));
            }
            Ok(Transparency::Rgb(
                be16(data, 0),
                be16(data, 2),
                be16(data, 4),
            ))
        }
        ColorType::Palette => {
            if data.len() > 256 {
                return Err(PixelsError::malformed(
                    "png",
                    format!(
                        "palette tRNS has {} entries, over the 256 maximum",
                        data.len()
                    ),
                ));
            }
            Ok(Transparency::Palette(data.to_vec()))
        }
        // §11.3.2.1: tRNS is forbidden where alpha is already present.
        ColorType::GrayscaleAlpha | ColorType::Rgba => Err(PixelsError::malformed(
            "png",
            "tRNS is not allowed for colour types that already carry alpha",
        )),
    }
}

impl<S: Source + std::fmt::Debug> Decoder for PngDecoder<S> {
    fn descriptor(&self) -> ImageDescriptor {
        self.descriptor
    }

    /// From an `eXIf` chunk before the image data. One after it is not
    /// seen: by then the pipeline has been built, and §5.6 puts `eXIf` first.
    fn orientation(&self) -> Orientation {
        self.orientation
    }

    /// From an `iCCP` chunk before the image data.
    fn icc_profile(&self) -> Option<&[u8]> {
        self.icc.as_deref()
    }

    fn capability(&self) -> DecodeCapability {
        // The raster is fully materialized before the first row is served, so
        // any region could in principle be answered. Declaring `Sequential`
        // keeps the streaming contract of ADR-0005 and costs nothing, since
        // the scheduler pulls rows in order anyway.
        DecodeCapability::Sequential
    }

    fn read_row(&mut self, out: &mut [u8]) -> Result<()> {
        // Interlaced images need every pass before any row is final, so they
        // take the buffered path; everything else streams.
        if self.header.interlaced {
            return self.read_row_buffered(out);
        }
        if self.stream.is_none() {
            let started = self.begin_streaming()?;
            self.stream = Some(Box::new(started));
        }
        if self.row >= self.descriptor.height {
            return Err(PixelsError::invalid_argument(
                "out",
                format!("all {} rows have already been read", self.descriptor.height),
            ));
        }
        let row_bytes = self.descriptor.row_bytes();
        if out.len() != row_bytes {
            return Err(PixelsError::invalid_argument(
                "out",
                format!("row buffer is {} bytes, expected {row_bytes}", out.len()),
            ));
        }

        let sample_bytes = self.header.row_bytes(self.header.width);
        let stride = self.header.filter_stride();
        let Some(stream) = self.stream.as_mut() else {
            return Err(PixelsError::graph("png stream vanished after starting"));
        };
        let samples = stream.next_scanline(sample_bytes, stride)?;
        let Some(stream) = self.stream.as_deref() else {
            return Err(PixelsError::graph("png stream vanished after starting"));
        };
        self.expand_row(
            &samples,
            stream.palette.as_deref(),
            stream.transparency.as_ref(),
            out,
        )?;
        self.row += 1;

        // The checksum and IEND follow the last scanline, so the stream is
        // only fully verified once it has been read to its end.
        if self.row == self.descriptor.height {
            if let Some(stream) = self.stream.as_mut() {
                stream.finalize()?;
            }
        }
        Ok(())
    }
}

/// Whether `prefix` starts with the PNG signature.
///
/// Detection is by magic bytes only (SPEC §Formats).
#[must_use]
pub fn probe(prefix: &[u8]) -> bool {
    prefix.get(..8) == Some(&SIGNATURE[..])
}

/// The PNG entry in a sniffing registry.
///
/// Format detection is by magic bytes only (SPEC §Formats); PNG's eight-byte
/// signature is deliberately designed to survive — and detect — the transfer
/// corruptions its §5.2 enumerates, so there is nothing else worth consulting.
#[derive(Debug, Clone, Copy, Default)]
pub struct PngCodec;

impl Codec for PngCodec {
    fn format(&self) -> Format {
        Format::Png
    }

    fn magic_len(&self) -> usize {
        SIGNATURE.len()
    }

    fn probe(&self, prefix: &[u8]) -> bool {
        probe(prefix)
    }
}