oximedia-codec 0.1.7

Video codec implementations for OxiMedia
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
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
//! PNG decoder implementation.
//!
//! Implements a complete PNG 1.2 specification decoder with support for:
//! - All color types (Grayscale, RGB, Palette, GrayscaleAlpha, RGBA)
//! - All bit depths (1, 2, 4, 8, 16)
//! - Interlacing (Adam7)
//! - All filter types (0-4)
//! - Ancillary chunks (tRNS, gAMA, cHRM, etc.)
//! - CRC validation

use super::filter::{unfilter, FilterType};
use crate::error::{CodecError, CodecResult};
use bytes::Bytes;
use oxiarc_deflate::ZlibStreamDecoder;
use std::io::Read;

/// PNG signature bytes.
const PNG_SIGNATURE: [u8; 8] = [137, 80, 78, 71, 13, 10, 26, 10];

/// PNG color types.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ColorType {
    /// Grayscale.
    Grayscale = 0,
    /// RGB truecolor.
    Rgb = 2,
    /// Indexed color (palette).
    Palette = 3,
    /// Grayscale with alpha.
    GrayscaleAlpha = 4,
    /// RGB with alpha.
    Rgba = 6,
}

impl ColorType {
    /// Create color type from byte.
    ///
    /// # Errors
    ///
    /// Returns error if color type is invalid.
    pub fn from_u8(value: u8) -> CodecResult<Self> {
        match value {
            0 => Ok(Self::Grayscale),
            2 => Ok(Self::Rgb),
            3 => Ok(Self::Palette),
            4 => Ok(Self::GrayscaleAlpha),
            6 => Ok(Self::Rgba),
            _ => Err(CodecError::InvalidData(format!(
                "Invalid color type: {value}"
            ))),
        }
    }

    /// Get number of samples per pixel.
    #[must_use]
    pub const fn samples_per_pixel(self) -> usize {
        match self {
            Self::Grayscale => 1,
            Self::Rgb => 3,
            Self::Palette => 1,
            Self::GrayscaleAlpha => 2,
            Self::Rgba => 4,
        }
    }

    /// Check if color type has alpha channel.
    #[must_use]
    pub const fn has_alpha(self) -> bool {
        matches!(self, Self::GrayscaleAlpha | Self::Rgba)
    }
}

/// PNG image header (IHDR chunk).
#[derive(Debug, Clone)]
pub struct ImageHeader {
    /// Image width in pixels.
    pub width: u32,
    /// Image height in pixels.
    pub height: u32,
    /// Bit depth.
    pub bit_depth: u8,
    /// Color type.
    pub color_type: ColorType,
    /// Compression method (always 0 for PNG).
    pub compression: u8,
    /// Filter method (always 0 for PNG).
    pub filter_method: u8,
    /// Interlace method (0 = none, 1 = Adam7).
    pub interlace: u8,
}

impl ImageHeader {
    /// Parse IHDR chunk data.
    ///
    /// # Errors
    ///
    /// Returns error if IHDR data is invalid.
    pub fn parse(data: &[u8]) -> CodecResult<Self> {
        if data.len() < 13 {
            return Err(CodecError::InvalidData("IHDR too short".into()));
        }

        let width = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
        let height = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
        let bit_depth = data[8];
        let color_type = ColorType::from_u8(data[9])?;
        let compression = data[10];
        let filter_method = data[11];
        let interlace = data[12];

        if width == 0 || height == 0 {
            return Err(CodecError::InvalidData("Invalid dimensions".into()));
        }

        if compression != 0 {
            return Err(CodecError::UnsupportedFeature(format!(
                "Unsupported compression method: {compression}"
            )));
        }

        if filter_method != 0 {
            return Err(CodecError::UnsupportedFeature(format!(
                "Unsupported filter method: {filter_method}"
            )));
        }

        if interlace > 1 {
            return Err(CodecError::InvalidData(format!(
                "Invalid interlace method: {interlace}"
            )));
        }

        // Validate bit depth for color type
        let valid_depths = match color_type {
            ColorType::Grayscale => &[1, 2, 4, 8, 16][..],
            ColorType::Rgb => &[8, 16][..],
            ColorType::Palette => &[1, 2, 4, 8][..],
            ColorType::GrayscaleAlpha => &[8, 16][..],
            ColorType::Rgba => &[8, 16][..],
        };

        if !valid_depths.contains(&bit_depth) {
            return Err(CodecError::InvalidData(format!(
                "Invalid bit depth {bit_depth} for color type {color_type:?}"
            )));
        }

        Ok(Self {
            width,
            height,
            bit_depth,
            color_type,
            compression,
            filter_method,
            interlace,
        })
    }

    /// Get bytes per pixel (rounded up).
    #[must_use]
    pub fn bytes_per_pixel(&self) -> usize {
        let bits_per_pixel = self.color_type.samples_per_pixel() * self.bit_depth as usize;
        (bits_per_pixel + 7) / 8
    }

    /// Get scanline length in bytes.
    #[must_use]
    pub fn scanline_length(&self) -> usize {
        let bits_per_scanline =
            self.width as usize * self.color_type.samples_per_pixel() * self.bit_depth as usize;
        (bits_per_scanline + 7) / 8
    }
}

/// PNG chunk.
#[derive(Debug)]
struct Chunk {
    /// Chunk type (4 bytes).
    chunk_type: [u8; 4],
    /// Chunk data.
    data: Vec<u8>,
}

impl Chunk {
    /// Read a chunk from data.
    fn read(data: &[u8], offset: &mut usize) -> CodecResult<Self> {
        if *offset + 12 > data.len() {
            return Err(CodecError::InvalidData("Incomplete chunk".into()));
        }

        let length = u32::from_be_bytes([
            data[*offset],
            data[*offset + 1],
            data[*offset + 2],
            data[*offset + 3],
        ]) as usize;
        *offset += 4;

        let chunk_type = [
            data[*offset],
            data[*offset + 1],
            data[*offset + 2],
            data[*offset + 3],
        ];
        *offset += 4;

        if *offset + length + 4 > data.len() {
            return Err(CodecError::InvalidData("Incomplete chunk data".into()));
        }

        let chunk_data = data[*offset..*offset + length].to_vec();
        *offset += length;

        let expected_crc = u32::from_be_bytes([
            data[*offset],
            data[*offset + 1],
            data[*offset + 2],
            data[*offset + 3],
        ]);
        *offset += 4;

        // Validate CRC
        let actual_crc = crc32(&chunk_type, &chunk_data);
        if actual_crc != expected_crc {
            return Err(CodecError::InvalidData(format!(
                "CRC mismatch for chunk {:?}",
                std::str::from_utf8(&chunk_type).unwrap_or("???")
            )));
        }

        Ok(Self {
            chunk_type,
            data: chunk_data,
        })
    }

    /// Get chunk type as string.
    fn type_str(&self) -> &str {
        std::str::from_utf8(&self.chunk_type).unwrap_or("????")
    }
}

/// Calculate CRC32 for PNG chunk.
fn crc32(chunk_type: &[u8; 4], data: &[u8]) -> u32 {
    let mut crc = !0u32;

    for &byte in chunk_type.iter().chain(data.iter()) {
        crc ^= u32::from(byte);
        for _ in 0..8 {
            crc = if crc & 1 != 0 {
                0xedb8_8320 ^ (crc >> 1)
            } else {
                crc >> 1
            };
        }
    }

    !crc
}

/// Adam7 interlacing pass information.
struct Adam7Pass {
    x_start: u32,
    y_start: u32,
    x_step: u32,
    y_step: u32,
}

const ADAM7_PASSES: [Adam7Pass; 7] = [
    Adam7Pass {
        x_start: 0,
        y_start: 0,
        x_step: 8,
        y_step: 8,
    },
    Adam7Pass {
        x_start: 4,
        y_start: 0,
        x_step: 8,
        y_step: 8,
    },
    Adam7Pass {
        x_start: 0,
        y_start: 4,
        x_step: 4,
        y_step: 8,
    },
    Adam7Pass {
        x_start: 2,
        y_start: 0,
        x_step: 4,
        y_step: 4,
    },
    Adam7Pass {
        x_start: 0,
        y_start: 2,
        x_step: 2,
        y_step: 4,
    },
    Adam7Pass {
        x_start: 1,
        y_start: 0,
        x_step: 2,
        y_step: 2,
    },
    Adam7Pass {
        x_start: 0,
        y_start: 1,
        x_step: 1,
        y_step: 2,
    },
];

/// PNG decoder.
pub struct PngDecoder {
    header: ImageHeader,
    palette: Option<Vec<u8>>,
    transparency: Option<Vec<u8>>,
    #[allow(dead_code)]
    gamma: Option<f64>,
    image_data: Vec<u8>,
}

impl PngDecoder {
    /// Create a new PNG decoder.
    ///
    /// # Errors
    ///
    /// Returns error if PNG data is invalid.
    pub fn new(data: &[u8]) -> CodecResult<Self> {
        if data.len() < 8 {
            return Err(CodecError::InvalidData("PNG data too short".into()));
        }

        // Validate PNG signature
        if &data[0..8] != PNG_SIGNATURE {
            return Err(CodecError::InvalidData("Invalid PNG signature".into()));
        }

        let mut offset = 8;
        let mut header: Option<ImageHeader> = None;
        let mut palette: Option<Vec<u8>> = None;
        let mut transparency: Option<Vec<u8>> = None;
        let mut gamma: Option<f64> = None;
        let mut idat_chunks = Vec::new();

        // Parse chunks
        while offset < data.len() {
            let chunk = Chunk::read(data, &mut offset)?;

            match chunk.type_str() {
                "IHDR" => {
                    if header.is_some() {
                        return Err(CodecError::InvalidData("Multiple IHDR chunks".into()));
                    }
                    header = Some(ImageHeader::parse(&chunk.data)?);
                }
                "PLTE" => {
                    if palette.is_some() {
                        return Err(CodecError::InvalidData("Multiple PLTE chunks".into()));
                    }
                    if chunk.data.len() % 3 != 0 || chunk.data.is_empty() {
                        return Err(CodecError::InvalidData("Invalid PLTE chunk".into()));
                    }
                    palette = Some(chunk.data);
                }
                "IDAT" => {
                    idat_chunks.push(chunk.data);
                }
                "IEND" => {
                    break;
                }
                "tRNS" => {
                    transparency = Some(chunk.data);
                }
                "gAMA" => {
                    if chunk.data.len() == 4 {
                        let gamma_int = u32::from_be_bytes([
                            chunk.data[0],
                            chunk.data[1],
                            chunk.data[2],
                            chunk.data[3],
                        ]);
                        gamma = Some(f64::from(gamma_int) / 100_000.0);
                    }
                }
                _ => {
                    // Skip unknown ancillary chunks
                }
            }
        }

        let header = header.ok_or_else(|| CodecError::InvalidData("Missing IHDR chunk".into()))?;

        if header.color_type == ColorType::Palette && palette.is_none() {
            return Err(CodecError::InvalidData(
                "Palette color type requires PLTE chunk".into(),
            ));
        }

        // Decompress IDAT data
        let compressed_data: Vec<u8> = idat_chunks.into_iter().flatten().collect();
        let mut decoder = ZlibStreamDecoder::new(&compressed_data[..]);
        let mut image_data = Vec::new();
        decoder
            .read_to_end(&mut image_data)
            .map_err(|e| CodecError::DecoderError(format!("DEFLATE decompression failed: {e}")))?;

        Ok(Self {
            header,
            palette,
            transparency,
            gamma,
            image_data,
        })
    }

    /// Get image width.
    #[must_use]
    pub const fn width(&self) -> u32 {
        self.header.width
    }

    /// Get image height.
    #[must_use]
    pub const fn height(&self) -> u32 {
        self.header.height
    }

    /// Get color type.
    #[must_use]
    pub const fn color_type(&self) -> ColorType {
        self.header.color_type
    }

    /// Get bit depth.
    #[must_use]
    pub const fn bit_depth(&self) -> u8 {
        self.header.bit_depth
    }

    /// Check if image is interlaced.
    #[must_use]
    pub const fn is_interlaced(&self) -> bool {
        self.header.interlace == 1
    }

    /// Decode the PNG image.
    ///
    /// # Errors
    ///
    /// Returns error if decoding fails.
    pub fn decode(&self) -> CodecResult<DecodedImage> {
        let raw_data = if self.is_interlaced() {
            self.decode_interlaced()?
        } else {
            self.decode_sequential()?
        };

        let rgba_data = self.convert_to_rgba(&raw_data)?;

        Ok(DecodedImage {
            width: self.header.width,
            height: self.header.height,
            data: Bytes::from(rgba_data),
        })
    }

    /// Decode sequential (non-interlaced) image.
    fn decode_sequential(&self) -> CodecResult<Vec<u8>> {
        let scanline_len = self.header.scanline_length();
        let bytes_per_pixel = self.header.bytes_per_pixel();
        let expected_len = (scanline_len + 1) * self.header.height as usize;

        if self.image_data.len() < expected_len {
            return Err(CodecError::InvalidData("Insufficient image data".into()));
        }

        let mut output = Vec::with_capacity(scanline_len * self.header.height as usize);
        let mut prev_scanline: Option<Vec<u8>> = None;

        for y in 0..self.header.height as usize {
            let offset = y * (scanline_len + 1);
            let filter_type = FilterType::from_u8(self.image_data[offset])?;
            let filtered = &self.image_data[offset + 1..offset + 1 + scanline_len];

            let scanline = unfilter(
                filter_type,
                filtered,
                prev_scanline.as_deref(),
                bytes_per_pixel,
            )?;

            output.extend_from_slice(&scanline);
            prev_scanline = Some(scanline);
        }

        Ok(output)
    }

    /// Decode interlaced (Adam7) image.
    #[allow(clippy::similar_names)]
    fn decode_interlaced(&self) -> CodecResult<Vec<u8>> {
        let bytes_per_pixel = self.header.bytes_per_pixel();
        let bits_per_pixel =
            self.header.color_type.samples_per_pixel() * self.header.bit_depth as usize;
        let bytes_per_sample = (self.header.bit_depth as usize + 7) / 8;

        let total_pixels =
            self.header.width as usize * self.header.height as usize * bytes_per_pixel;
        let mut output = vec![0u8; total_pixels];

        let mut data_offset = 0;

        for pass in &ADAM7_PASSES {
            let pass_width =
                (self.header.width.saturating_sub(pass.x_start) + pass.x_step - 1) / pass.x_step;
            let pass_height =
                (self.header.height.saturating_sub(pass.y_start) + pass.y_step - 1) / pass.y_step;

            if pass_width == 0 || pass_height == 0 {
                continue;
            }

            let scanline_bits = pass_width as usize * bits_per_pixel;
            let scanline_len = (scanline_bits + 7) / 8;

            let mut prev_scanline: Option<Vec<u8>> = None;

            for py in 0..pass_height {
                if data_offset >= self.image_data.len() {
                    return Err(CodecError::InvalidData(
                        "Insufficient data for interlaced image".into(),
                    ));
                }

                let filter_type = FilterType::from_u8(self.image_data[data_offset])?;
                data_offset += 1;

                if data_offset + scanline_len > self.image_data.len() {
                    return Err(CodecError::InvalidData(
                        "Insufficient data for scanline".into(),
                    ));
                }

                let filtered = &self.image_data[data_offset..data_offset + scanline_len];
                data_offset += scanline_len;

                let scanline = unfilter(
                    filter_type,
                    filtered,
                    prev_scanline.as_deref(),
                    bytes_per_pixel,
                )?;

                // Copy pixels to output
                let y = (pass.y_start + py * pass.y_step) as usize;
                for px in 0..pass_width as usize {
                    let x = pass.x_start as usize + px * pass.x_step as usize;
                    let src_offset = px * bytes_per_pixel;
                    let dst_offset = (y * self.header.width as usize + x) * bytes_per_pixel;

                    if src_offset + bytes_per_pixel <= scanline.len()
                        && dst_offset + bytes_per_pixel <= output.len()
                    {
                        output[dst_offset..dst_offset + bytes_per_pixel]
                            .copy_from_slice(&scanline[src_offset..src_offset + bytes_per_pixel]);
                    }
                }

                prev_scanline = Some(scanline);
            }
        }

        Ok(output)
    }

    /// Convert raw image data to RGBA format.
    #[allow(clippy::too_many_lines)]
    fn convert_to_rgba(&self, raw_data: &[u8]) -> CodecResult<Vec<u8>> {
        let pixel_count = (self.header.width * self.header.height) as usize;
        let mut rgba = vec![255u8; pixel_count * 4];

        match self.header.color_type {
            ColorType::Grayscale => {
                if self.header.bit_depth == 8 {
                    for i in 0..pixel_count {
                        let gray = raw_data[i];
                        rgba[i * 4] = gray;
                        rgba[i * 4 + 1] = gray;
                        rgba[i * 4 + 2] = gray;
                        rgba[i * 4 + 3] = 255;
                    }
                } else if self.header.bit_depth == 16 {
                    for i in 0..pixel_count {
                        let gray = raw_data[i * 2];
                        rgba[i * 4] = gray;
                        rgba[i * 4 + 1] = gray;
                        rgba[i * 4 + 2] = gray;
                        rgba[i * 4 + 3] = 255;
                    }
                } else {
                    // Expand low bit depths
                    self.expand_grayscale(raw_data, &mut rgba)?;
                }
            }
            ColorType::Rgb => {
                if self.header.bit_depth == 8 {
                    for i in 0..pixel_count {
                        rgba[i * 4] = raw_data[i * 3];
                        rgba[i * 4 + 1] = raw_data[i * 3 + 1];
                        rgba[i * 4 + 2] = raw_data[i * 3 + 2];
                        rgba[i * 4 + 3] = 255;
                    }
                } else if self.header.bit_depth == 16 {
                    for i in 0..pixel_count {
                        rgba[i * 4] = raw_data[i * 6];
                        rgba[i * 4 + 1] = raw_data[i * 6 + 2];
                        rgba[i * 4 + 2] = raw_data[i * 6 + 4];
                        rgba[i * 4 + 3] = 255;
                    }
                }
            }
            ColorType::Palette => {
                let palette = self
                    .palette
                    .as_ref()
                    .ok_or_else(|| CodecError::InvalidData("Missing palette".into()))?;
                self.expand_palette(raw_data, palette, &mut rgba)?;
            }
            ColorType::GrayscaleAlpha => {
                if self.header.bit_depth == 8 {
                    for i in 0..pixel_count {
                        let gray = raw_data[i * 2];
                        let alpha = raw_data[i * 2 + 1];
                        rgba[i * 4] = gray;
                        rgba[i * 4 + 1] = gray;
                        rgba[i * 4 + 2] = gray;
                        rgba[i * 4 + 3] = alpha;
                    }
                } else if self.header.bit_depth == 16 {
                    for i in 0..pixel_count {
                        let gray = raw_data[i * 4];
                        let alpha = raw_data[i * 4 + 2];
                        rgba[i * 4] = gray;
                        rgba[i * 4 + 1] = gray;
                        rgba[i * 4 + 2] = gray;
                        rgba[i * 4 + 3] = alpha;
                    }
                }
            }
            ColorType::Rgba => {
                if self.header.bit_depth == 8 {
                    rgba.copy_from_slice(raw_data);
                } else if self.header.bit_depth == 16 {
                    for i in 0..pixel_count {
                        rgba[i * 4] = raw_data[i * 8];
                        rgba[i * 4 + 1] = raw_data[i * 8 + 2];
                        rgba[i * 4 + 2] = raw_data[i * 8 + 4];
                        rgba[i * 4 + 3] = raw_data[i * 8 + 6];
                    }
                }
            }
        }

        // Apply transparency if present
        if let Some(trns) = &self.transparency {
            self.apply_transparency(&mut rgba, trns)?;
        }

        Ok(rgba)
    }

    /// Expand low bit-depth grayscale to 8-bit.
    fn expand_grayscale(&self, raw_data: &[u8], rgba: &mut [u8]) -> CodecResult<()> {
        let pixel_count = (self.header.width * self.header.height) as usize;
        let scale = 255 / ((1 << self.header.bit_depth) - 1);

        let mut bit_pos = 0;
        for i in 0..pixel_count {
            let byte_pos = bit_pos / 8;
            let shift = 8 - (bit_pos % 8) - self.header.bit_depth as usize;
            let mask = (1 << self.header.bit_depth) - 1;

            if byte_pos >= raw_data.len() {
                return Err(CodecError::InvalidData(
                    "Insufficient grayscale data".into(),
                ));
            }

            let value = (raw_data[byte_pos] >> shift) & mask;
            let gray = value * scale;

            rgba[i * 4] = gray;
            rgba[i * 4 + 1] = gray;
            rgba[i * 4 + 2] = gray;
            rgba[i * 4 + 3] = 255;

            bit_pos += self.header.bit_depth as usize;
        }

        Ok(())
    }

    /// Expand palette indices to RGBA.
    fn expand_palette(&self, raw_data: &[u8], palette: &[u8], rgba: &mut [u8]) -> CodecResult<()> {
        let pixel_count = (self.header.width * self.header.height) as usize;
        let mut bit_pos = 0;

        for i in 0..pixel_count {
            let byte_pos = bit_pos / 8;
            let shift = 8 - (bit_pos % 8) - self.header.bit_depth as usize;
            let mask = (1 << self.header.bit_depth) - 1;

            if byte_pos >= raw_data.len() {
                return Err(CodecError::InvalidData("Insufficient palette data".into()));
            }

            let index = ((raw_data[byte_pos] >> shift) & mask) as usize;
            let palette_offset = index * 3;

            if palette_offset + 3 > palette.len() {
                return Err(CodecError::InvalidData(format!(
                    "Invalid palette index: {index}"
                )));
            }

            rgba[i * 4] = palette[palette_offset];
            rgba[i * 4 + 1] = palette[palette_offset + 1];
            rgba[i * 4 + 2] = palette[palette_offset + 2];
            rgba[i * 4 + 3] = 255;

            bit_pos += self.header.bit_depth as usize;
        }

        Ok(())
    }

    /// Apply transparency data.
    fn apply_transparency(&self, rgba: &mut [u8], trns: &[u8]) -> CodecResult<()> {
        match self.header.color_type {
            ColorType::Grayscale => {
                if trns.len() < 2 {
                    return Ok(());
                }
                let transparent_gray = u16::from_be_bytes([trns[0], trns[1]]);
                let transparent_gray_8 = if self.header.bit_depth == 16 {
                    (transparent_gray >> 8) as u8
                } else {
                    transparent_gray as u8
                };

                for i in 0..rgba.len() / 4 {
                    if rgba[i * 4] == transparent_gray_8 {
                        rgba[i * 4 + 3] = 0;
                    }
                }
            }
            ColorType::Palette => {
                for i in 0..rgba.len() / 4 {
                    if i < trns.len() {
                        rgba[i * 4 + 3] = trns[i];
                    }
                }
            }
            ColorType::Rgb => {
                if trns.len() < 6 {
                    return Ok(());
                }
                let tr = u16::from_be_bytes([trns[0], trns[1]]);
                let tg = u16::from_be_bytes([trns[2], trns[3]]);
                let tb = u16::from_be_bytes([trns[4], trns[5]]);

                for i in 0..rgba.len() / 4 {
                    let r = u16::from(rgba[i * 4]);
                    let g = u16::from(rgba[i * 4 + 1]);
                    let b = u16::from(rgba[i * 4 + 2]);

                    if r == tr && g == tg && b == tb {
                        rgba[i * 4 + 3] = 0;
                    }
                }
            }
            _ => {}
        }

        Ok(())
    }
}

/// Decoded PNG image.
#[derive(Debug, Clone)]
pub struct DecodedImage {
    /// Image width.
    pub width: u32,
    /// Image height.
    pub height: u32,
    /// RGBA pixel data.
    pub data: Bytes,
}

/// Chromaticity coordinates (cHRM chunk).
#[derive(Debug, Clone, Copy)]
pub struct Chromaticity {
    /// White point X.
    pub white_x: f64,
    /// White point Y.
    pub white_y: f64,
    /// Red X.
    pub red_x: f64,
    /// Red Y.
    pub red_y: f64,
    /// Green X.
    pub green_x: f64,
    /// Green Y.
    pub green_y: f64,
    /// Blue X.
    pub blue_x: f64,
    /// Blue Y.
    pub blue_y: f64,
}

/// Physical pixel dimensions (pHYs chunk).
#[derive(Debug, Clone, Copy)]
pub struct PhysicalDimensions {
    /// Pixels per unit, X axis.
    pub x: u32,
    /// Pixels per unit, Y axis.
    pub y: u32,
    /// Unit specifier (0 = unknown, 1 = meter).
    pub unit: u8,
}

/// Significant bits (sBIT chunk).
#[derive(Debug, Clone)]
pub struct SignificantBits {
    /// Significant bits for each channel.
    pub bits: Vec<u8>,
}

/// Text metadata (tEXt chunk).
#[derive(Debug, Clone)]
pub struct TextChunk {
    /// Keyword.
    pub keyword: String,
    /// Text value.
    pub text: String,
}

/// PNG metadata.
#[derive(Debug, Clone, Default)]
pub struct PngMetadata {
    /// Gamma value.
    pub gamma: Option<f64>,
    /// Chromaticity coordinates.
    pub chromaticity: Option<Chromaticity>,
    /// Physical dimensions.
    pub physical_dimensions: Option<PhysicalDimensions>,
    /// Significant bits.
    pub significant_bits: Option<SignificantBits>,
    /// Text chunks.
    pub text_chunks: Vec<TextChunk>,
    /// Background color.
    pub background_color: Option<(u16, u16, u16)>,
    /// Suggested palette.
    pub suggested_palette: Option<Vec<u8>>,
}

impl Chromaticity {
    /// Parse from cHRM chunk data.
    ///
    /// # Errors
    ///
    /// Returns error if chunk data is invalid.
    pub fn parse(data: &[u8]) -> CodecResult<Self> {
        if data.len() < 32 {
            return Err(CodecError::InvalidData("cHRM chunk too short".into()));
        }

        let white_x = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
        let white_y = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
        let red_x = u32::from_be_bytes([data[8], data[9], data[10], data[11]]);
        let red_y = u32::from_be_bytes([data[12], data[13], data[14], data[15]]);
        let green_x = u32::from_be_bytes([data[16], data[17], data[18], data[19]]);
        let green_y = u32::from_be_bytes([data[20], data[21], data[22], data[23]]);
        let blue_x = u32::from_be_bytes([data[24], data[25], data[26], data[27]]);
        let blue_y = u32::from_be_bytes([data[28], data[29], data[30], data[31]]);

        Ok(Self {
            white_x: f64::from(white_x) / 100_000.0,
            white_y: f64::from(white_y) / 100_000.0,
            red_x: f64::from(red_x) / 100_000.0,
            red_y: f64::from(red_y) / 100_000.0,
            green_x: f64::from(green_x) / 100_000.0,
            green_y: f64::from(green_y) / 100_000.0,
            blue_x: f64::from(blue_x) / 100_000.0,
            blue_y: f64::from(blue_y) / 100_000.0,
        })
    }

    /// Get sRGB chromaticity.
    #[must_use]
    pub fn srgb() -> Self {
        Self {
            white_x: 0.3127,
            white_y: 0.329,
            red_x: 0.64,
            red_y: 0.33,
            green_x: 0.3,
            green_y: 0.6,
            blue_x: 0.15,
            blue_y: 0.06,
        }
    }
}

impl PhysicalDimensions {
    /// Parse from pHYs chunk data.
    ///
    /// # Errors
    ///
    /// Returns error if chunk data is invalid.
    pub fn parse(data: &[u8]) -> CodecResult<Self> {
        if data.len() < 9 {
            return Err(CodecError::InvalidData("pHYs chunk too short".into()));
        }

        let x = u32::from_be_bytes([data[0], data[1], data[2], data[3]]);
        let y = u32::from_be_bytes([data[4], data[5], data[6], data[7]]);
        let unit = data[8];

        Ok(Self { x, y, unit })
    }

    /// Get DPI if unit is meter.
    #[must_use]
    pub fn dpi(&self) -> Option<(f64, f64)> {
        if self.unit == 1 {
            const METERS_PER_INCH: f64 = 0.0254;
            Some((
                f64::from(self.x) * METERS_PER_INCH,
                f64::from(self.y) * METERS_PER_INCH,
            ))
        } else {
            None
        }
    }
}

impl SignificantBits {
    /// Parse from sBIT chunk data.
    ///
    /// # Errors
    ///
    /// Returns error if chunk data is invalid.
    pub fn parse(data: &[u8]) -> CodecResult<Self> {
        if data.is_empty() {
            return Err(CodecError::InvalidData("sBIT chunk is empty".into()));
        }

        Ok(Self {
            bits: data.to_vec(),
        })
    }
}

impl TextChunk {
    /// Parse from tEXt chunk data.
    ///
    /// # Errors
    ///
    /// Returns error if chunk data is invalid.
    pub fn parse(data: &[u8]) -> CodecResult<Self> {
        // Find null separator
        let null_pos = data
            .iter()
            .position(|&b| b == 0)
            .ok_or_else(|| CodecError::InvalidData("tEXt chunk missing null separator".into()))?;

        let keyword = String::from_utf8_lossy(&data[..null_pos]).into_owned();
        let text = String::from_utf8_lossy(&data[null_pos + 1..]).into_owned();

        Ok(Self { keyword, text })
    }
}

/// Extended PNG decoder with metadata support.
pub struct PngDecoderExtended {
    /// Base decoder.
    pub decoder: PngDecoder,
    /// Metadata.
    pub metadata: PngMetadata,
}

impl PngDecoderExtended {
    /// Create a new extended PNG decoder.
    ///
    /// # Errors
    ///
    /// Returns error if PNG data is invalid.
    #[allow(clippy::too_many_lines)]
    pub fn new(data: &[u8]) -> CodecResult<Self> {
        if data.len() < 8 {
            return Err(CodecError::InvalidData("PNG data too short".into()));
        }

        if &data[0..8] != PNG_SIGNATURE {
            return Err(CodecError::InvalidData("Invalid PNG signature".into()));
        }

        let mut offset = 8;
        let mut header: Option<ImageHeader> = None;
        let mut palette: Option<Vec<u8>> = None;
        let mut transparency: Option<Vec<u8>> = None;
        let mut metadata = PngMetadata::default();
        let mut idat_chunks = Vec::new();

        while offset < data.len() {
            let chunk = Chunk::read(data, &mut offset)?;

            match chunk.type_str() {
                "IHDR" => {
                    if header.is_some() {
                        return Err(CodecError::InvalidData("Multiple IHDR chunks".into()));
                    }
                    header = Some(ImageHeader::parse(&chunk.data)?);
                }
                "PLTE" => {
                    if palette.is_some() {
                        return Err(CodecError::InvalidData("Multiple PLTE chunks".into()));
                    }
                    if chunk.data.len() % 3 != 0 || chunk.data.is_empty() {
                        return Err(CodecError::InvalidData("Invalid PLTE chunk".into()));
                    }
                    palette = Some(chunk.data);
                }
                "IDAT" => {
                    idat_chunks.push(chunk.data);
                }
                "IEND" => {
                    break;
                }
                "tRNS" => {
                    transparency = Some(chunk.data);
                }
                "gAMA" => {
                    if chunk.data.len() == 4 {
                        let gamma_int = u32::from_be_bytes([
                            chunk.data[0],
                            chunk.data[1],
                            chunk.data[2],
                            chunk.data[3],
                        ]);
                        metadata.gamma = Some(f64::from(gamma_int) / 100_000.0);
                    }
                }
                "cHRM" => {
                    metadata.chromaticity = Some(Chromaticity::parse(&chunk.data)?);
                }
                "pHYs" => {
                    metadata.physical_dimensions = Some(PhysicalDimensions::parse(&chunk.data)?);
                }
                "sBIT" => {
                    metadata.significant_bits = Some(SignificantBits::parse(&chunk.data)?);
                }
                "tEXt" => {
                    if let Ok(text_chunk) = TextChunk::parse(&chunk.data) {
                        metadata.text_chunks.push(text_chunk);
                    }
                }
                "bKGD" => {
                    if chunk.data.len() >= 6 {
                        let r = u16::from_be_bytes([chunk.data[0], chunk.data[1]]);
                        let g = u16::from_be_bytes([chunk.data[2], chunk.data[3]]);
                        let b = u16::from_be_bytes([chunk.data[4], chunk.data[5]]);
                        metadata.background_color = Some((r, g, b));
                    }
                }
                "sPLT" => {
                    metadata.suggested_palette = Some(chunk.data);
                }
                _ => {
                    // Skip unknown ancillary chunks
                }
            }
        }

        let header = header.ok_or_else(|| CodecError::InvalidData("Missing IHDR chunk".into()))?;

        if header.color_type == ColorType::Palette && palette.is_none() {
            return Err(CodecError::InvalidData(
                "Palette color type requires PLTE chunk".into(),
            ));
        }

        let compressed_data: Vec<u8> = idat_chunks.into_iter().flatten().collect();
        let mut zlib_decoder = ZlibStreamDecoder::new(&compressed_data[..]);
        let mut image_data = Vec::new();
        zlib_decoder
            .read_to_end(&mut image_data)
            .map_err(|e| CodecError::DecoderError(format!("DEFLATE decompression failed: {e}")))?;

        let decoder = PngDecoder {
            header,
            palette,
            transparency,
            gamma: metadata.gamma,
            image_data,
        };

        Ok(Self { decoder, metadata })
    }

    /// Decode the PNG image.
    ///
    /// # Errors
    ///
    /// Returns error if decoding fails.
    pub fn decode(&self) -> CodecResult<DecodedImage> {
        self.decoder.decode()
    }
}