euv-core 0.53.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
use super::*;

/// Decodes a standard or URL-safe Base64 ASCII string into raw bytes.
///
/// # Arguments
///
/// - `&str` - Base64-encoded ASCII text (whitespace ignored).
///
/// # Returns
///
/// - `Result<Vec<u8>, String>` - Decoded byte vector or validation error.
pub fn decode_base64(input: &str) -> Result<Vec<u8>, String> {
    let mut cleaned: Vec<u8> = Vec::with_capacity(input.len());
    for byte_val in input.bytes() {
        if !byte_val.is_ascii_whitespace() {
            cleaned.push(byte_val);
        }
    }
    if cleaned.is_empty() {
        return Ok(Vec::new());
    }
    if !cleaned.len().is_multiple_of(4) {
        return Err(ERR_BASE64_INVALID.to_string());
    }
    let mut out: Vec<u8> = Vec::with_capacity((cleaned.len() / 4) * 3);
    for quad in cleaned.as_chunks::<4>().0 {
        let v0: u8 = decode_base64_sextet(quad[0])?;
        let v1: u8 = decode_base64_sextet(quad[1])?;
        let pad2: bool = quad[2] == b'=';
        let pad3: bool = quad[3] == b'=';
        if pad2 && !pad3 {
            return Err(ERR_BASE64_INVALID.to_string());
        }
        let v2: u8 = if pad2 {
            0
        } else {
            decode_base64_sextet(quad[2])?
        };
        let v3: u8 = if pad3 {
            0
        } else {
            decode_base64_sextet(quad[3])?
        };
        let mut triple: u32 = u32::from(v0) << 18;
        triple |= u32::from(v1) << 12;
        triple |= u32::from(v2) << 6;
        triple |= u32::from(v3);
        out.push(((triple >> 16) & 0xFF) as u8);
        if !pad2 {
            out.push(((triple >> 8) & 0xFF) as u8);
        }
        if !pad3 {
            out.push((triple & 0xFF) as u8);
        }
    }
    Ok(out)
}

/// Maps a single Base64 ASCII character to its 6-bit value (`0..=63`).
///
/// # Arguments
///
/// - `u8` - Input ASCII byte.
///
/// # Returns
///
/// - `Result<u8, String>` - Sextet value or error on invalid character.
fn decode_base64_sextet(byte_val: u8) -> Result<u8, String> {
    match byte_val {
        b'A'..=b'Z' => Ok(byte_val - b'A'),
        b'a'..=b'z' => Ok(byte_val - b'a' + 26),
        b'0'..=b'9' => Ok(byte_val - b'0' + 52),
        b'+' | b'-' => Ok(62),
        b'/' | b'_' => Ok(63),
        _ => Err(ERR_BASE64_INVALID.to_string()),
    }
}

/// Computes the IEEE 802.3 CRC-32 checksum used by PNG chunks and gzip trailers.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `u32` - Computed CRC-32 digest.
#[must_use]
pub fn compute_crc32(data: &[u8]) -> u32 {
    let mut crc: u32 = 0xFFFF_FFFF;
    for &byte_val in data.iter() {
        crc ^= u32::from(byte_val);
        for _ in 0..8 {
            let mask: u32 = (crc & 1).wrapping_neg();
            crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
        }
    }
    !crc
}

/// Computes the Adler-32 checksum used by RFC 1950 zlib streams.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `u32` - Computed Adler-32 digest.
#[must_use]
pub fn compute_adler32(data: &[u8]) -> u32 {
    let mut sum_a: u32 = 1;
    let mut sum_b: u32 = 0;
    for &byte_val in data.iter() {
        sum_a = (sum_a + u32::from(byte_val)) % 65_521;
        sum_b = (sum_b + sum_a) % 65_521;
    }
    (sum_b << 16) | sum_a
}

/// Builds the RFC 1951 fixed literal/length and distance Huffman tables.
///
/// # Returns
///
/// - `Result<(DeflateHuffmanTable, DeflateHuffmanTable), String>` - Pair of fixed Huffman tables.
fn build_fixed_deflate_tables() -> Result<(DeflateHuffmanTable, DeflateHuffmanTable), String> {
    let mut lit_lengths: [u8; 288] = [0u8; 288];
    lit_lengths[0..144].fill(8);
    lit_lengths[144..256].fill(9);
    lit_lengths[256..280].fill(7);
    lit_lengths[280..288].fill(8);
    let dist_lengths: [u8; 32] = [5u8; 32];
    let lit_table: DeflateHuffmanTable = DeflateHuffmanTable::from_code_lengths(&lit_lengths)?;
    let dist_table: DeflateHuffmanTable = DeflateHuffmanTable::from_code_lengths(&dist_lengths)?;
    Ok((lit_table, dist_table))
}

/// Decodes dynamic Huffman code tables for an RFC 1951 BTYPE=2 block.
///
/// # Arguments
///
/// - `&mut DeflateBitReader<'_>` - Active DEFLATE bit reader.
///
/// # Returns
///
/// - `Result<(DeflateHuffmanTable, DeflateHuffmanTable), String>` - Dynamic literal/length and distance tables.
fn decode_dynamic_deflate_tables(
    reader: &mut DeflateBitReader<'_>,
) -> Result<(DeflateHuffmanTable, DeflateHuffmanTable), String> {
    let hlit: usize = (reader.read_bits(5)? as usize) + 257;
    let hdist: usize = (reader.read_bits(5)? as usize) + 1;
    let hclen: usize = (reader.read_bits(4)? as usize) + 4;
    if hlit > 286 || hdist > 30 {
        return Err(ERR_DEFLATE_HUFFMAN.to_string());
    }
    let mut code_len_lens: [u8; 19] = [0u8; 19];
    for idx in 0..hclen {
        code_len_lens[DEFLATE_CODE_LENGTH_ORDER[idx]] = reader.read_bits(3)? as u8;
    }
    let code_len_table: DeflateHuffmanTable =
        DeflateHuffmanTable::from_code_lengths(&code_len_lens)?;
    let total_lens: usize = hlit + hdist;
    let mut all_lens: Vec<u8> = Vec::with_capacity(total_lens);
    while all_lens.len() < total_lens {
        let sym: u16 = code_len_table.decode(reader)?;
        match sym {
            0..=15 => {
                all_lens.push(sym as u8);
            }
            16 => {
                let prev: u8 = all_lens
                    .last()
                    .copied()
                    .ok_or_else(|| ERR_DEFLATE_HUFFMAN.to_string())?;
                let repeat: usize = (reader.read_bits(2)? as usize) + 3;
                if all_lens.len() + repeat > total_lens {
                    return Err(ERR_DEFLATE_HUFFMAN.to_string());
                }
                for _ in 0..repeat {
                    all_lens.push(prev);
                }
            }
            17 => {
                let repeat: usize = (reader.read_bits(3)? as usize) + 3;
                if all_lens.len() + repeat > total_lens {
                    return Err(ERR_DEFLATE_HUFFMAN.to_string());
                }
                all_lens.resize(all_lens.len() + repeat, 0);
            }
            18 => {
                let repeat: usize = (reader.read_bits(7)? as usize) + 11;
                if all_lens.len() + repeat > total_lens {
                    return Err(ERR_DEFLATE_HUFFMAN.to_string());
                }
                all_lens.resize(all_lens.len() + repeat, 0);
            }
            _ => return Err(ERR_DEFLATE_HUFFMAN.to_string()),
        }
    }
    let lit_table: DeflateHuffmanTable = DeflateHuffmanTable::from_code_lengths(&all_lens[..hlit])?;
    let dist_table: DeflateHuffmanTable =
        DeflateHuffmanTable::from_code_lengths(&all_lens[hlit..])?;
    Ok((lit_table, dist_table))
}

/// Decompresses a raw RFC 1951 DEFLATE stream returning output bytes and consumed byte count.
///
/// # Arguments
///
/// - `&[u8]` - Raw DEFLATE stream bytes.
///
/// # Returns
///
/// - `Result<(Vec<u8>, usize), String>` - Decompressed bytes and input bytes consumed.
fn inflate_deflate_with_consumed(input: &[u8]) -> Result<(Vec<u8>, usize), String> {
    let mut reader: DeflateBitReader<'_> = DeflateBitReader::new(input);
    let mut output: Vec<u8> = Vec::with_capacity(input.len().saturating_mul(2));
    loop {
        let is_final: u32 = reader.read_bits(1)?;
        let block_type: u32 = reader.read_bits(2)?;
        match block_type {
            0 => {
                reader.align_to_byte();
                let len_lo: u16 = u16::from(reader.read_aligned_byte()?);
                let len_hi: u16 = u16::from(reader.read_aligned_byte()?);
                let nlen_lo: u16 = u16::from(reader.read_aligned_byte()?);
                let nlen_hi: u16 = u16::from(reader.read_aligned_byte()?);
                let block_len: u16 = len_lo | (len_hi << 8);
                let block_nlen: u16 = nlen_lo | (nlen_hi << 8);
                if block_len != !block_nlen {
                    return Err(ERR_DEFLATE_INVALID.to_string());
                }
                let copy_len: usize = usize::from(block_len);
                if output.len().saturating_add(copy_len) > IMAGE_MAX_DECOMPRESSED_BYTES {
                    return Err(ERR_DEFLATE_OVERFLOW.to_string());
                }
                for _ in 0..copy_len {
                    output.push(reader.read_aligned_byte()?);
                }
            }
            1 | 2 => {
                let (lit_table, dist_table): (DeflateHuffmanTable, DeflateHuffmanTable) =
                    if block_type == 1 {
                        build_fixed_deflate_tables()?
                    } else {
                        decode_dynamic_deflate_tables(&mut reader)?
                    };
                loop {
                    let symbol: u16 = lit_table.decode(&mut reader)?;
                    if symbol < 256 {
                        if output.len() >= IMAGE_MAX_DECOMPRESSED_BYTES {
                            return Err(ERR_DEFLATE_OVERFLOW.to_string());
                        }
                        output.push(symbol as u8);
                    } else if symbol == 256 {
                        break;
                    } else if symbol <= 285 {
                        let len_slot: usize = (symbol - 257) as usize;
                        let extra_len: usize =
                            reader.read_bits(DEFLATE_LENGTH_EXTRA[len_slot])? as usize;
                        let match_len: usize = DEFLATE_LENGTH_BASE[len_slot] + extra_len;
                        let dist_sym: u16 = dist_table.decode(&mut reader)?;
                        if dist_sym >= 30 {
                            return Err(ERR_DEFLATE_DISTANCE.to_string());
                        }
                        let dist_slot: usize = dist_sym as usize;
                        let extra_dist: usize =
                            reader.read_bits(DEFLATE_DIST_EXTRA[dist_slot])? as usize;
                        let distance: usize = DEFLATE_DIST_BASE[dist_slot] + extra_dist;
                        if distance == 0 || distance > output.len() {
                            return Err(ERR_DEFLATE_DISTANCE.to_string());
                        }
                        if output.len().saturating_add(match_len) > IMAGE_MAX_DECOMPRESSED_BYTES {
                            return Err(ERR_DEFLATE_OVERFLOW.to_string());
                        }
                        for _ in 0..match_len {
                            let src_byte: u8 = output[output.len() - distance];
                            output.push(src_byte);
                        }
                    } else {
                        return Err(ERR_DEFLATE_INVALID.to_string());
                    }
                }
            }
            _ => return Err(ERR_DEFLATE_INVALID.to_string()),
        }
        if is_final != 0 {
            break;
        }
    }
    let consumed: usize = reader.consumed_bytes();
    Ok((output, consumed))
}

/// Decompresses a raw RFC 1951 DEFLATE byte stream.
///
/// # Arguments
///
/// - `&[u8]` - Raw DEFLATE bitstream.
///
/// # Returns
///
/// - `Result<Vec<u8>, String>` - Decompressed bytes or error.
pub fn inflate_deflate_raw(input: &[u8]) -> Result<Vec<u8>, String> {
    let (out, _): (Vec<u8>, usize) = inflate_deflate_with_consumed(input)?;
    Ok(out)
}

/// Decompresses an RFC 1950 zlib stream and validates its header and Adler-32 checksum.
///
/// # Arguments
///
/// - `&[u8]` - Zlib-wrapped compressed bytes.
///
/// # Returns
///
/// - `Result<Vec<u8>, String>` - Decompressed bytes or container/checksum error.
pub fn inflate_zlib(input: &[u8]) -> Result<Vec<u8>, String> {
    if input.len() < 6 {
        return Err(ERR_ZLIB_INVALID.to_string());
    }
    let cmf: u8 = input[0];
    let flg: u8 = input[1];
    let method: u8 = cmf & 0x0F;
    let check_sum: u16 = (u16::from(cmf) << 8) | u16::from(flg);
    if method != 8 || !check_sum.is_multiple_of(31) {
        return Err(ERR_ZLIB_INVALID.to_string());
    }
    let has_dict: bool = (flg & 0x20) != 0;
    let payload_start: usize = if has_dict { 6 } else { 2 };
    if input.len() < payload_start + 4 {
        return Err(ERR_ZLIB_INVALID.to_string());
    }
    let (decoded, consumed): (Vec<u8>, usize) =
        inflate_deflate_with_consumed(&input[payload_start..])?;
    let adler_offset: usize = payload_start.saturating_add(consumed);
    if adler_offset + 4 <= input.len() {
        let expected: u32 = u32::from_be_bytes([
            input[adler_offset],
            input[adler_offset + 1],
            input[adler_offset + 2],
            input[adler_offset + 3],
        ]);
        let actual: u32 = compute_adler32(&decoded);
        if expected != actual {
            return Err(ERR_ZLIB_INVALID.to_string());
        }
    }
    Ok(decoded)
}

/// Decompresses an RFC 1952 gzip byte stream and verifies its CRC-32 trailer.
///
/// # Arguments
///
/// - `&[u8]` - Gzip-compressed byte stream.
///
/// # Returns
///
/// - `Result<Vec<u8>, String>` - Decompressed bytes or error.
pub fn inflate_gzip(input: &[u8]) -> Result<Vec<u8>, String> {
    if input.len() < 18 || input[0..2] != GZIP_SIGNATURE || input[2] != 8 {
        return Err(ERR_GZIP_INVALID.to_string());
    }
    let flags: u8 = input[3];
    let mut pos: usize = 10;
    if (flags & 0x04) != 0 {
        if pos + 2 > input.len() {
            return Err(ERR_GZIP_INVALID.to_string());
        }
        let extra_len: usize = usize::from(u16::from_le_bytes([input[pos], input[pos + 1]]));
        pos = pos.saturating_add(2).saturating_add(extra_len);
    }
    if (flags & 0x08) != 0 {
        while pos < input.len() && input[pos] != 0 {
            pos += 1;
        }
        pos = pos.saturating_add(1);
    }
    if (flags & 0x10) != 0 {
        while pos < input.len() && input[pos] != 0 {
            pos += 1;
        }
        pos = pos.saturating_add(1);
    }
    if (flags & 0x02) != 0 {
        pos = pos.saturating_add(2);
    }
    if pos + 8 > input.len() {
        return Err(ERR_GZIP_INVALID.to_string());
    }
    let (decoded, consumed): (Vec<u8>, usize) = inflate_deflate_with_consumed(&input[pos..])?;
    let trailer_pos: usize = pos.saturating_add(consumed);
    if trailer_pos + 8 <= input.len() {
        let expected_crc: u32 = u32::from_le_bytes([
            input[trailer_pos],
            input[trailer_pos + 1],
            input[trailer_pos + 2],
            input[trailer_pos + 3],
        ]);
        let expected_isize: u32 = u32::from_le_bytes([
            input[trailer_pos + 4],
            input[trailer_pos + 5],
            input[trailer_pos + 6],
            input[trailer_pos + 7],
        ]);
        if compute_crc32(&decoded) != expected_crc || (decoded.len() as u32) != expected_isize {
            return Err(ERR_GZIP_INVALID.to_string());
        }
    }
    Ok(decoded)
}

/// Evaluates the PNG Paeth predictor byte from left, above, and upper-left neighbors.
///
/// # Arguments
///
/// - `u8` - Left reconstructed byte.
/// - `u8` - Above reconstructed byte.
/// - `u8` - Upper-left reconstructed byte.
///
/// # Returns
///
/// - `u8` - Predicted byte value.
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn png_paeth_predictor(left: u8, above: u8, upper_left: u8) -> u8 {
    let left_i: i32 = i32::from(left);
    let above_i: i32 = i32::from(above);
    let upper_i: i32 = i32::from(upper_left);
    let est: i32 = left_i + above_i - upper_i;
    let dist_left: i32 = (est - left_i).abs();
    let dist_above: i32 = (est - above_i).abs();
    let dist_upper: i32 = (est - upper_i).abs();
    if dist_left <= dist_above && dist_left <= dist_upper {
        left
    } else if dist_above <= dist_upper {
        above
    } else {
        upper_left
    }
}

/// Reverses one PNG scanline filter in place into `recon`.
///
/// # Arguments
///
/// - `u8` - PNG filter method (`0..=4`).
/// - `&[u8]` - Filtered scanline bytes (without filter type byte).
/// - `&[u8]` - Previous reconstructed scanline bytes (empty for first row).
/// - `usize` - Filter byte stride (`max(1, bits_per_pixel / 8)`).
/// - `&mut [u8]` - Destination reconstructed scanline buffer.
///
/// # Returns
///
/// - `Result<(), String>` - `Ok(())` or invalid filter error.
fn png_unfilter_row(
    filter_type: u8,
    raw: &[u8],
    prev: &[u8],
    stride: usize,
    recon: &mut [u8],
) -> Result<(), String> {
    match filter_type {
        0 => {
            recon.copy_from_slice(raw);
        }
        1 => {
            for idx in 0..raw.len() {
                let left: u8 = if idx >= stride {
                    recon[idx - stride]
                } else {
                    0
                };
                recon[idx] = raw[idx].wrapping_add(left);
            }
        }
        2 => {
            for idx in 0..raw.len() {
                let above: u8 = prev.get(idx).copied().unwrap_or(0);
                recon[idx] = raw[idx].wrapping_add(above);
            }
        }
        3 => {
            for idx in 0..raw.len() {
                let left: u16 = if idx >= stride {
                    u16::from(recon[idx - stride])
                } else {
                    0
                };
                let above: u16 = u16::from(prev.get(idx).copied().unwrap_or(0));
                let avg: u8 = ((left + above) >> 1) as u8;
                recon[idx] = raw[idx].wrapping_add(avg);
            }
        }
        4 => {
            for idx in 0..raw.len() {
                let left: u8 = if idx >= stride {
                    recon[idx - stride]
                } else {
                    0
                };
                let above: u8 = prev.get(idx).copied().unwrap_or(0);
                let upper_left: u8 = if idx >= stride {
                    prev.get(idx - stride).copied().unwrap_or(0)
                } else {
                    0
                };
                recon[idx] = raw[idx].wrapping_add(png_paeth_predictor(left, above, upper_left));
            }
        }
        _ => return Err(ERR_PNG_FILTER.to_string()),
    }
    Ok(())
}

/// Scales a sub-byte PNG sample (`1`, `2`, or `4` bit) linearly to `0..=255`.
///
/// # Arguments
///
/// - `u8` - Raw bit sample.
/// - `u8` - Source bit depth (`1`, `2`, `4`, or `8`).
///
/// # Returns
///
/// - `u8` - Expanded 8-bit intensity value.
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn png_scale_sample(sample: u8, bit_depth: u8) -> u8 {
    match bit_depth {
        1 => {
            if sample != 0 {
                255
            } else {
                0
            }
        }
        2 => sample * 85,
        4 => sample * 17,
        _ => sample,
    }
}

/// Extracts a sub-byte or 8-bit sample at `index` from a reconstructed PNG scanline.
///
/// # Arguments
///
/// - `&[u8]` - Reconstructed scanline bytes.
/// - `usize` - Sample index along the scanline.
/// - `u8` - Bit depth (`1`, `2`, `4`, or `8`).
///
/// # Returns
///
/// - `u8` - Extracted sample value.
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn png_read_subbyte(row: &[u8], index: usize, bit_depth: u8) -> u8 {
    match bit_depth {
        1 => {
            let byte_val: u8 = row[index >> 3];
            (byte_val >> (7 - (index & 7))) & 1
        }
        2 => {
            let byte_val: u8 = row[index >> 2];
            (byte_val >> (6 - ((index & 3) * 2))) & 3
        }
        4 => {
            let byte_val: u8 = row[index >> 1];
            if (index & 1) == 0 {
                (byte_val >> 4) & 0x0F
            } else {
                byte_val & 0x0F
            }
        }
        _ => row[index],
    }
}

/// Converts a single reconstructed PNG scanline pixel at `col` into RGBA8.
///
/// # Arguments
///
/// - `&[u8]` - Reconstructed scanline bytes.
/// - `usize` - Pixel column inside the scanline.
/// - `u8` - PNG color type (`0`, `2`, `3`, `4`, `6`).
/// - `u8` - PNG bit depth (`1`, `2`, `4`, `8`, `16`).
/// - `&[[u8; 3]]` - Optional PLTE RGB palette entries.
/// - `&[u8]` - Optional raw tRNS chunk payload.
///
/// # Returns
///
/// - `[u8; 4]` - Decoded RGBA8 pixel.
#[must_use]
fn png_pixel_to_rgba(
    row: &[u8],
    col: usize,
    color_type: u8,
    bit_depth: u8,
    palette: &[[u8; 3]],
    trns: &[u8],
) -> [u8; 4] {
    match color_type {
        0 => {
            if bit_depth == 16 {
                let offset: usize = col * 2;
                let raw16: u16 = u16::from_be_bytes([row[offset], row[offset + 1]]);
                let gray: u8 = (raw16 >> 8) as u8;
                let transparent: bool =
                    trns.len() >= 2 && u16::from_be_bytes([trns[0], trns[1]]) == raw16;
                [gray, gray, gray, if transparent { 0 } else { 255 }]
            } else {
                let sample: u8 = png_read_subbyte(row, col, bit_depth);
                let gray: u8 = png_scale_sample(sample, bit_depth);
                let transparent: bool =
                    trns.len() >= 2 && u16::from_be_bytes([trns[0], trns[1]]) == u16::from(sample);
                [gray, gray, gray, if transparent { 0 } else { 255 }]
            }
        }
        2 => {
            if bit_depth == 16 {
                let offset: usize = col * 6;
                let red16: u16 = u16::from_be_bytes([row[offset], row[offset + 1]]);
                let green16: u16 = u16::from_be_bytes([row[offset + 2], row[offset + 3]]);
                let blue16: u16 = u16::from_be_bytes([row[offset + 4], row[offset + 5]]);
                let transparent: bool = trns.len() >= 6
                    && u16::from_be_bytes([trns[0], trns[1]]) == red16
                    && u16::from_be_bytes([trns[2], trns[3]]) == green16
                    && u16::from_be_bytes([trns[4], trns[5]]) == blue16;
                [
                    (red16 >> 8) as u8,
                    (green16 >> 8) as u8,
                    (blue16 >> 8) as u8,
                    if transparent { 0 } else { 255 },
                ]
            } else {
                let offset: usize = col * 3;
                let red: u8 = row[offset];
                let green: u8 = row[offset + 1];
                let blue: u8 = row[offset + 2];
                let transparent: bool = trns.len() >= 6
                    && u16::from_be_bytes([trns[0], trns[1]]) == u16::from(red)
                    && u16::from_be_bytes([trns[2], trns[3]]) == u16::from(green)
                    && u16::from_be_bytes([trns[4], trns[5]]) == u16::from(blue);
                [red, green, blue, if transparent { 0 } else { 255 }]
            }
        }
        3 => {
            let idx: usize = usize::from(png_read_subbyte(row, col, bit_depth));
            let rgb: [u8; 3] = palette.get(idx).copied().unwrap_or([0, 0, 0]);
            let alpha: u8 = trns.get(idx).copied().unwrap_or(255);
            [rgb[0], rgb[1], rgb[2], alpha]
        }
        4 => {
            if bit_depth == 16 {
                let offset: usize = col * 4;
                let gray: u8 = row[offset];
                let alpha: u8 = row[offset + 2];
                [gray, gray, gray, alpha]
            } else {
                let offset: usize = col * 2;
                let gray: u8 = row[offset];
                let alpha: u8 = row[offset + 1];
                [gray, gray, gray, alpha]
            }
        }
        6 => {
            if bit_depth == 16 {
                let offset: usize = col * 8;
                [
                    row[offset],
                    row[offset + 2],
                    row[offset + 4],
                    row[offset + 6],
                ]
            } else {
                let offset: usize = col * 4;
                [
                    row[offset],
                    row[offset + 1],
                    row[offset + 2],
                    row[offset + 3],
                ]
            }
        }
        _ => [0, 0, 0, 255],
    }
}

/// Decodes a complete PNG byte stream (IHDR/PLTE/tRNS/IDAT/IEND, filters 0..4, 1/2/4/8/16-bit, Adam7) into RGBA8.
///
/// # Arguments
///
/// - `&[u8]` - Raw `.png` file bytes.
///
/// # Returns
///
/// - `Result<DecodedRgbaImage, String>` - Decoded RGBA8 image or parse/decompression error.
pub fn decode_png_rgba(bytes: &[u8]) -> Result<DecodedRgbaImage, String> {
    if bytes.len() < 33 || bytes[0..8] != PNG_SIGNATURE {
        return Err(ERR_PNG_INVALID.to_string());
    }
    let mut cursor: usize = 8;
    let mut width: u32 = 0;
    let mut height: u32 = 0;
    let mut bit_depth: u8 = 0;
    let mut color_type: u8 = 0;
    let mut interlace: u8 = 0;
    let mut saw_ihdr: bool = false;
    let mut palette: Vec<[u8; 3]> = Vec::new();
    let mut trns: Vec<u8> = Vec::new();
    let mut idat: Vec<u8> = Vec::new();
    while cursor + 12 <= bytes.len() {
        let chunk_len: usize = u32::from_be_bytes([
            bytes[cursor],
            bytes[cursor + 1],
            bytes[cursor + 2],
            bytes[cursor + 3],
        ]) as usize;
        let chunk_type: [u8; 4] = [
            bytes[cursor + 4],
            bytes[cursor + 5],
            bytes[cursor + 6],
            bytes[cursor + 7],
        ];
        let data_start: usize = cursor + 8;
        let data_end: usize = data_start.saturating_add(chunk_len);
        if data_end.saturating_add(4) > bytes.len() {
            return Err(ERR_PNG_INVALID.to_string());
        }
        let payload: &[u8] = &bytes[data_start..data_end];
        if chunk_type == PNG_CHUNK_IHDR {
            if chunk_len != 13 {
                return Err(ERR_PNG_INVALID.to_string());
            }
            width = u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]);
            height = u32::from_be_bytes([payload[4], payload[5], payload[6], payload[7]]);
            bit_depth = payload[8];
            color_type = payload[9];
            let compression: u8 = payload[10];
            let filter_method: u8 = payload[11];
            interlace = payload[12];
            if width == 0
                || height == 0
                || width > IMAGE_MAX_DIMENSION
                || height > IMAGE_MAX_DIMENSION
                || compression != 0
                || filter_method != 0
                || interlace > 1
            {
                return Err(ERR_PNG_INVALID.to_string());
            }
            saw_ihdr = true;
        } else if chunk_type == PNG_CHUNK_PLTE {
            if !chunk_len.is_multiple_of(3) {
                return Err(ERR_PNG_INVALID.to_string());
            }
            palette.clear();
            for entry in payload.as_chunks::<3>().0 {
                palette.push(*entry);
            }
        } else if chunk_type == PNG_CHUNK_TRNS {
            trns.clear();
            trns.extend_from_slice(payload);
        } else if chunk_type == PNG_CHUNK_IDAT {
            idat.extend_from_slice(payload);
        } else if chunk_type == PNG_CHUNK_IEND {
            break;
        }
        cursor = data_end + 4;
    }
    if !saw_ihdr || idat.is_empty() {
        return Err(ERR_PNG_INVALID.to_string());
    }
    let samples_per_pixel: usize = match (color_type, bit_depth) {
        (0, 1 | 2 | 4 | 8 | 16) => 1,
        (2, 8 | 16) => 3,
        (3, 1 | 2 | 4 | 8) => 1,
        (4, 8 | 16) => 2,
        (6, 8 | 16) => 4,
        _ => return Err(ERR_PNG_UNSUPPORTED.to_string()),
    };
    let bits_per_pixel: usize = samples_per_pixel * usize::from(bit_depth);
    let filter_stride: usize = (bits_per_pixel / 8).max(1);
    let inflated: Vec<u8> = inflate_zlib(&idat)?;
    let w_usize: usize = width as usize;
    let h_usize: usize = height as usize;
    let mut rgba: Vec<u8> = vec![0u8; w_usize.saturating_mul(h_usize).saturating_mul(4)];
    if interlace == 0 {
        let row_bytes: usize = w_usize.saturating_mul(bits_per_pixel).div_ceil(8);
        let expected_len: usize = h_usize.saturating_mul(row_bytes + 1);
        if inflated.len() < expected_len {
            return Err(ERR_PNG_INVALID.to_string());
        }
        let mut prev_row: Vec<u8> = vec![0u8; row_bytes];
        let mut cur_row: Vec<u8> = vec![0u8; row_bytes];
        for row_idx in 0..h_usize {
            let src_start: usize = row_idx * (row_bytes + 1);
            let filter_type: u8 = inflated[src_start];
            let raw_slice: &[u8] = &inflated[(src_start + 1)..(src_start + 1 + row_bytes)];
            let prev_slice: &[u8] = if row_idx == 0 { &[] } else { &prev_row };
            png_unfilter_row(
                filter_type,
                raw_slice,
                prev_slice,
                filter_stride,
                &mut cur_row,
            )?;
            let dst_row_off: usize = row_idx * w_usize * 4;
            for col_idx in 0..w_usize {
                let px: [u8; 4] =
                    png_pixel_to_rgba(&cur_row, col_idx, color_type, bit_depth, &palette, &trns);
                let dst: usize = dst_row_off + col_idx * 4;
                rgba[dst..dst + 4].copy_from_slice(&px);
            }
            swap(&mut prev_row, &mut cur_row);
        }
    } else {
        let mut src_cursor: usize = 0;
        for pass_idx in 0..7usize {
            let start_x: usize = PNG_ADAM7_START_X[pass_idx];
            let start_y: usize = PNG_ADAM7_START_Y[pass_idx];
            let step_x: usize = PNG_ADAM7_STEP_X[pass_idx];
            let step_y: usize = PNG_ADAM7_STEP_Y[pass_idx];
            if start_x >= w_usize || start_y >= h_usize {
                continue;
            }
            let pass_w: usize = (w_usize - start_x).div_ceil(step_x);
            let pass_h: usize = (h_usize - start_y).div_ceil(step_y);
            let row_bytes: usize = pass_w.saturating_mul(bits_per_pixel).div_ceil(8);
            let mut prev_row: Vec<u8> = vec![0u8; row_bytes];
            let mut cur_row: Vec<u8> = vec![0u8; row_bytes];
            for pass_y in 0..pass_h {
                if src_cursor + 1 + row_bytes > inflated.len() {
                    return Err(ERR_PNG_INVALID.to_string());
                }
                let filter_type: u8 = inflated[src_cursor];
                let raw_slice: &[u8] = &inflated[(src_cursor + 1)..(src_cursor + 1 + row_bytes)];
                src_cursor += 1 + row_bytes;
                let prev_slice: &[u8] = if pass_y == 0 { &[] } else { &prev_row };
                png_unfilter_row(
                    filter_type,
                    raw_slice,
                    prev_slice,
                    filter_stride,
                    &mut cur_row,
                )?;
                let dst_y: usize = start_y + pass_y * step_y;
                for pass_x in 0..pass_w {
                    let dst_x: usize = start_x + pass_x * step_x;
                    let px: [u8; 4] =
                        png_pixel_to_rgba(&cur_row, pass_x, color_type, bit_depth, &palette, &trns);
                    let dst: usize = (dst_y * w_usize + dst_x) * 4;
                    rgba[dst..dst + 4].copy_from_slice(&px);
                }
                swap(&mut prev_row, &mut cur_row);
            }
        }
    }
    Ok(DecodedRgbaImage {
        width,
        height,
        pixels: rgba,
        format: DecodedImageFormat::Png,
    })
}

/// Appends a framed PNG chunk (`length`, `chunk_type`, `payload`, `crc32`) into `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination PNG output byte vector.
/// - `[u8; 4]` - Four-byte ASCII chunk tag.
/// - `&[u8]` - Chunk payload bytes.
fn append_png_chunk(out: &mut Vec<u8>, chunk_type: [u8; 4], payload: &[u8]) {
    out.extend_from_slice(&(payload.len() as u32).to_be_bytes());
    let crc_start: usize = out.len();
    out.extend_from_slice(&chunk_type);
    out.extend_from_slice(payload);
    let crc: u32 = compute_crc32(&out[crc_start..]);
    out.extend_from_slice(&crc.to_be_bytes());
}

/// Encodes an RGBA8 image into a spec-compliant PNG byte vector using uncompressed zlib blocks.
///
/// # Arguments
///
/// - `u32` - Image width in pixels.
/// - `u32` - Image height in pixels.
/// - `&[u8]` - Packed RGBA8 pixels (`width * height * 4` bytes).
///
/// # Returns
///
/// - `Result<Vec<u8>, String>` - Encoded PNG bytes or validation error.
pub fn encode_png_rgba(width: u32, height: u32, rgba: &[u8]) -> Result<Vec<u8>, String> {
    let w_usize: usize = width as usize;
    let h_usize: usize = height as usize;
    let expected: usize = w_usize.saturating_mul(h_usize).saturating_mul(4);
    if width == 0 || height == 0 || rgba.len() != expected {
        return Err(ERR_PNG_ENCODE_ARGS.to_string());
    }
    let row_bytes: usize = w_usize * 4;
    let mut raw_scanlines: Vec<u8> = Vec::with_capacity(h_usize * (row_bytes + 1));
    for row_idx in 0..h_usize {
        raw_scanlines.push(0);
        let row_start: usize = row_idx * row_bytes;
        raw_scanlines.extend_from_slice(&rgba[row_start..(row_start + row_bytes)]);
    }
    let mut zlib_stream: Vec<u8> = Vec::with_capacity(raw_scanlines.len() + 64);
    zlib_stream.push(0x78);
    zlib_stream.push(0x01);
    let max_block: usize = 65_535;
    let mut offset: usize = 0;
    while offset < raw_scanlines.len() {
        let end: usize = (offset + max_block).min(raw_scanlines.len());
        let is_last: u8 = u8::from(end == raw_scanlines.len());
        let block_len: u16 = (end - offset) as u16;
        let block_nlen: u16 = !block_len;
        zlib_stream.push(is_last);
        zlib_stream.extend_from_slice(&block_len.to_le_bytes());
        zlib_stream.extend_from_slice(&block_nlen.to_le_bytes());
        zlib_stream.extend_from_slice(&raw_scanlines[offset..end]);
        offset = end;
    }
    let adler: u32 = compute_adler32(&raw_scanlines);
    zlib_stream.extend_from_slice(&adler.to_be_bytes());
    let mut out: Vec<u8> = Vec::with_capacity(zlib_stream.len() + 64);
    out.extend_from_slice(&PNG_SIGNATURE);
    let mut ihdr: [u8; 13] = [0u8; 13];
    ihdr[0..4].copy_from_slice(&width.to_be_bytes());
    ihdr[4..8].copy_from_slice(&height.to_be_bytes());
    ihdr[8] = 8;
    ihdr[9] = 6;
    append_png_chunk(&mut out, PNG_CHUNK_IHDR, &ihdr);
    append_png_chunk(&mut out, PNG_CHUNK_IDAT, &zlib_stream);
    append_png_chunk(&mut out, PNG_CHUNK_IEND, &[]);
    Ok(out)
}

/// Evaluates the separable 2D 8x8 inverse DCT producing level-shifted pixel values in `[0, 255]`.
///
/// # Arguments
///
/// - `&[f32; 64]` - Dequantized natural-order frequency coefficients.
///
/// # Returns
///
/// - `[u8; 64]` - Reconstructed 8x8 spatial pixel block.
#[must_use]
fn jpeg_idct_8x8(coeffs: &[f32; 64]) -> [u8; 64] {
    let mut temp: [f32; 64] = [0.0; 64];
    for row in 0..8usize {
        for col in 0..8usize {
            let mut sum: f32 = 0.0;
            for freq_u in 0..8usize {
                sum += coeffs[row * 8 + freq_u] * JPEG_DCT_BASIS[freq_u][col];
            }
            temp[row * 8 + col] = sum;
        }
    }
    let mut out: [u8; 64] = [0u8; 64];
    for row in 0..8usize {
        for col in 0..8usize {
            let mut sum: f32 = 0.0;
            for freq_v in 0..8usize {
                sum += temp[freq_v * 8 + col] * JPEG_DCT_BASIS[freq_v][row];
            }
            out[row * 8 + col] = (sum + 128.0).round().clamp(0.0, 255.0) as u8;
        }
    }
    out
}

/// Evaluates the separable 2D 8x8 forward DCT on level-shifted pixel values in `[-128.0, 127.0]`.
///
/// # Arguments
///
/// - `&[f32; 64]` - Level-shifted 8x8 spatial pixel samples.
///
/// # Returns
///
/// - `[f32; 64]` - Natural-order 8x8 DCT frequency coefficients.
#[must_use]
fn jpeg_fdct_8x8(spatial: &[f32; 64]) -> [f32; 64] {
    let mut temp: [f32; 64] = [0.0; 64];
    for row in 0..8usize {
        for freq_u in 0..8usize {
            let mut sum: f32 = 0.0;
            for col in 0..8usize {
                sum += spatial[row * 8 + col] * JPEG_DCT_BASIS[freq_u][col];
            }
            temp[row * 8 + freq_u] = sum;
        }
    }
    let mut coeffs: [f32; 64] = [0.0; 64];
    for freq_v in 0..8usize {
        for freq_u in 0..8usize {
            let mut sum: f32 = 0.0;
            for row in 0..8usize {
                sum += temp[row * 8 + freq_u] * JPEG_DCT_BASIS[freq_v][row];
            }
            coeffs[freq_v * 8 + freq_u] = sum;
        }
    }
    coeffs
}

/// Decodes a single 8x8 Huffman-coded JPEG block into spatial samples.
///
/// # Arguments
///
/// - `&mut JpegBitReader<'_>` - Active JPEG entropy reader.
/// - `&JpegHuffmanTable` - DC Huffman table.
/// - `&JpegHuffmanTable` - AC Huffman table.
/// - `&[u16; 64]` - Quantization table in zigzag order.
/// - `&mut i32` - Component running DC predictor.
///
/// # Returns
///
/// - `Result<[u8; 64], String>` - Decoded 8x8 spatial samples.
fn jpeg_decode_block(
    reader: &mut JpegBitReader<'_>,
    dc_table: &JpegHuffmanTable,
    ac_table: &JpegHuffmanTable,
    quant_zz: &[u16; 64],
    dc_pred: &mut i32,
) -> Result<[u8; 64], String> {
    let mut coeffs: [f32; 64] = [0.0; 64];
    let dc_cat: u8 = dc_table.decode(reader)?;
    let dc_diff: i32 = reader.receive_extend(dc_cat)?;
    *dc_pred += dc_diff;
    coeffs[0] = (*dc_pred as f32) * f32::from(quant_zz[0]);
    let mut zz_idx: usize = 1;
    while zz_idx < 64 {
        let rs: u8 = ac_table.decode(reader)?;
        if rs == 0 {
            break;
        }
        let run: usize = usize::from(rs >> 4);
        let cat: u8 = rs & 0x0F;
        if cat == 0 {
            if run == 15 {
                zz_idx += 16;
                continue;
            }
            break;
        }
        zz_idx += run;
        if zz_idx >= 64 {
            return Err(ERR_JPEG_INVALID.to_string());
        }
        let ac_val: i32 = reader.receive_extend(cat)?;
        let nat_idx: usize = JPEG_ZIGZAG_TO_NATURAL[zz_idx];
        coeffs[nat_idx] = (ac_val as f32) * f32::from(quant_zz[zz_idx]);
        zz_idx += 1;
    }
    Ok(jpeg_idct_8x8(&coeffs))
}

/// Decodes a Baseline Sequential JPEG (`SOF0`) byte stream into packed RGBA8 pixels.
///
/// # Arguments
///
/// - `&[u8]` - Raw `.jpg` / `.jpeg` file bytes.
///
/// # Returns
///
/// - `Result<DecodedRgbaImage, String>` - Decoded RGBA8 image or parse error.
pub fn decode_jpeg_rgba(bytes: &[u8]) -> Result<DecodedRgbaImage, String> {
    if bytes.len() < 4 || bytes[0] != 0xFF || bytes[1] != 0xD8 {
        return Err(ERR_JPEG_INVALID.to_string());
    }
    let mut quant_tables: [[u16; 64]; 4] = [[1u16; 64]; 4];
    let mut dc_tables: [JpegHuffmanTable; 4] = [
        JpegHuffmanTable::default(),
        JpegHuffmanTable::default(),
        JpegHuffmanTable::default(),
        JpegHuffmanTable::default(),
    ];
    let mut ac_tables: [JpegHuffmanTable; 4] = [
        JpegHuffmanTable::default(),
        JpegHuffmanTable::default(),
        JpegHuffmanTable::default(),
        JpegHuffmanTable::default(),
    ];
    let mut components: Vec<JpegComponentSpec> = Vec::new();
    let mut width: u32 = 0;
    let mut height: u32 = 0;
    let mut restart_interval: u16 = 0;
    let mut pos: usize = 2;
    let mut scan_start: Option<usize> = None;
    while pos + 1 < bytes.len() {
        while pos < bytes.len() && bytes[pos] != 0xFF {
            pos += 1;
        }
        while pos < bytes.len() && bytes[pos] == 0xFF {
            pos += 1;
        }
        if pos >= bytes.len() {
            break;
        }
        let marker: u8 = bytes[pos];
        pos += 1;
        if marker == 0xD9 {
            break;
        }
        if marker == 0x00 || (0xD0..=0xD7).contains(&marker) || marker == 0x01 {
            continue;
        }
        if pos + 2 > bytes.len() {
            return Err(ERR_JPEG_INVALID.to_string());
        }
        let seg_len: usize = usize::from(u16::from_be_bytes([bytes[pos], bytes[pos + 1]]));
        if seg_len < 2 || pos + seg_len > bytes.len() {
            return Err(ERR_JPEG_INVALID.to_string());
        }
        let seg: &[u8] = &bytes[(pos + 2)..(pos + seg_len)];
        match marker {
            0xDB => {
                let mut cur: usize = 0;
                while cur < seg.len() {
                    let info: u8 = seg[cur];
                    cur += 1;
                    let precision: u8 = info >> 4;
                    let table_id: usize = usize::from(info & 0x0F);
                    if table_id >= 4 {
                        return Err(ERR_JPEG_INVALID.to_string());
                    }
                    if precision == 0 {
                        if cur + 64 > seg.len() {
                            return Err(ERR_JPEG_INVALID.to_string());
                        }
                        for idx in 0..64usize {
                            quant_tables[table_id][idx] = u16::from(seg[cur + idx]);
                        }
                        cur += 64;
                    } else {
                        if cur + 128 > seg.len() {
                            return Err(ERR_JPEG_INVALID.to_string());
                        }
                        for idx in 0..64usize {
                            quant_tables[table_id][idx] =
                                u16::from_be_bytes([seg[cur + idx * 2], seg[cur + idx * 2 + 1]]);
                        }
                        cur += 128;
                    }
                }
            }
            0xC0 | 0xC1 => {
                if seg.len() < 6 {
                    return Err(ERR_JPEG_INVALID.to_string());
                }
                let sample_bits: u8 = seg[0];
                if sample_bits != 8 {
                    return Err(ERR_JPEG_UNSUPPORTED.to_string());
                }
                height = u32::from(u16::from_be_bytes([seg[1], seg[2]]));
                width = u32::from(u16::from_be_bytes([seg[3], seg[4]]));
                let num_comp: usize = usize::from(seg[5]);
                if width == 0
                    || height == 0
                    || width > IMAGE_MAX_DIMENSION
                    || height > IMAGE_MAX_DIMENSION
                    || (num_comp != 1 && num_comp != 3)
                    || seg.len() < 6 + num_comp * 3
                {
                    return Err(ERR_JPEG_UNSUPPORTED.to_string());
                }
                components.clear();
                for idx in 0..num_comp {
                    let base: usize = 6 + idx * 3;
                    let comp_id: u8 = seg[base];
                    let samp: u8 = seg[base + 1];
                    let h_samp: u8 = samp >> 4;
                    let v_samp: u8 = samp & 0x0F;
                    let quant_id: u8 = seg[base + 2];
                    let h_invalid: bool = h_samp == 0 || h_samp > 4;
                    let v_invalid: bool = v_samp == 0 || v_samp > 4;
                    let samp_invalid: bool = h_invalid || v_invalid;
                    if samp_invalid || quant_id >= 4 {
                        return Err(ERR_JPEG_INVALID.to_string());
                    }
                    components.push(JpegComponentSpec {
                        id: comp_id,
                        h_samp,
                        v_samp,
                        quant_id,
                        dc_table_id: 0,
                        ac_table_id: 0,
                        dc_pred: 0,
                    });
                }
            }
            0xC2 => return Err(ERR_JPEG_UNSUPPORTED.to_string()),
            0xC4 => {
                let mut cur: usize = 0;
                while cur < seg.len() {
                    if cur + 17 > seg.len() {
                        return Err(ERR_JPEG_INVALID.to_string());
                    }
                    let info: u8 = seg[cur];
                    cur += 1;
                    let table_class: u8 = info >> 4;
                    let table_id: usize = usize::from(info & 0x0F);
                    if table_id >= 4 {
                        return Err(ERR_JPEG_INVALID.to_string());
                    }
                    let mut counts: [u8; 16] = [0u8; 16];
                    let mut total_vals: usize = 0;
                    for idx in 0..16usize {
                        counts[idx] = seg[cur + idx];
                        total_vals += usize::from(counts[idx]);
                    }
                    cur += 16;
                    if cur + total_vals > seg.len() {
                        return Err(ERR_JPEG_INVALID.to_string());
                    }
                    let values: Vec<u8> = seg[cur..(cur + total_vals)].to_vec();
                    cur += total_vals;
                    let built: JpegHuffmanTable = JpegHuffmanTable::from_dht(counts, values);
                    if table_class == 0 {
                        dc_tables[table_id] = built;
                    } else {
                        ac_tables[table_id] = built;
                    }
                }
            }
            0xDD => {
                if seg.len() >= 2 {
                    restart_interval = u16::from_be_bytes([seg[0], seg[1]]);
                }
            }
            0xDA => {
                if seg.is_empty() {
                    return Err(ERR_JPEG_INVALID.to_string());
                }
                let scan_comp_count: usize = usize::from(seg[0]);
                if seg.len() < 1 + scan_comp_count * 2 + 3 {
                    return Err(ERR_JPEG_INVALID.to_string());
                }
                for idx in 0..scan_comp_count {
                    let comp_id: u8 = seg[1 + idx * 2];
                    let td_ta: u8 = seg[2 + idx * 2];
                    let dc_id: u8 = td_ta >> 4;
                    let ac_id: u8 = td_ta & 0x0F;
                    if dc_id >= 4 || ac_id >= 4 {
                        return Err(ERR_JPEG_INVALID.to_string());
                    }
                    for comp in components.iter_mut() {
                        if comp.id == comp_id {
                            comp.dc_table_id = dc_id;
                            comp.ac_table_id = ac_id;
                        }
                    }
                }
                scan_start = Some(pos + seg_len);
                break;
            }
            _ => {}
        }
        pos += seg_len;
    }
    let Some(entropy_offset) = scan_start else {
        return Err(ERR_JPEG_INVALID.to_string());
    };
    if components.is_empty() || width == 0 || height == 0 {
        return Err(ERR_JPEG_INVALID.to_string());
    }
    let max_h: usize = components
        .iter()
        .map(|comp: &JpegComponentSpec| usize::from(comp.h_samp))
        .max()
        .unwrap_or(1);
    let max_v: usize = components
        .iter()
        .map(|comp: &JpegComponentSpec| usize::from(comp.v_samp))
        .max()
        .unwrap_or(1);
    let mcu_w: usize = max_h * 8;
    let mcu_h: usize = max_v * 8;
    let w_usize: usize = width as usize;
    let h_usize: usize = height as usize;
    let mcus_x: usize = w_usize.div_ceil(mcu_w);
    let mcus_y: usize = h_usize.div_ceil(mcu_h);
    let mut reader: JpegBitReader<'_> = JpegBitReader::new(bytes, entropy_offset);
    let mut rgba: Vec<u8> = vec![255u8; w_usize.saturating_mul(h_usize).saturating_mul(4)];
    let mut mcu_counter: u32 = 0;
    let mut comp_buffers: Vec<Vec<u8>> = components
        .iter()
        .map(|comp: &JpegComponentSpec| {
            vec![0u8; usize::from(comp.h_samp) * 8 * usize::from(comp.v_samp) * 8]
        })
        .collect();
    for mcu_y in 0..mcus_y {
        for mcu_x in 0..mcus_x {
            if restart_interval > 0
                && mcu_counter > 0
                && mcu_counter.is_multiple_of(u32::from(restart_interval))
            {
                reader.consume_restart_marker();
                for comp in components.iter_mut() {
                    comp.dc_pred = 0;
                }
            }
            for (comp_idx, comp) in components.iter_mut().enumerate() {
                let comp_h: usize = usize::from(comp.h_samp);
                let comp_v: usize = usize::from(comp.v_samp);
                let comp_stride: usize = comp_h * 8;
                let dc_tbl: &JpegHuffmanTable = &dc_tables[usize::from(comp.dc_table_id)];
                let ac_tbl: &JpegHuffmanTable = &ac_tables[usize::from(comp.ac_table_id)];
                let quant_tbl: &[u16; 64] = &quant_tables[usize::from(comp.quant_id)];
                let buf: &mut [u8] = &mut comp_buffers[comp_idx];
                for by in 0..comp_v {
                    for bx in 0..comp_h {
                        let block: [u8; 64] = jpeg_decode_block(
                            &mut reader,
                            dc_tbl,
                            ac_tbl,
                            quant_tbl,
                            &mut comp.dc_pred,
                        )?;
                        for row in 0..8usize {
                            let dst_off: usize = (by * 8 + row) * comp_stride + bx * 8;
                            buf[dst_off..(dst_off + 8)]
                                .copy_from_slice(&block[(row * 8)..(row * 8 + 8)]);
                        }
                    }
                }
            }
            let base_x: usize = mcu_x * mcu_w;
            let base_y: usize = mcu_y * mcu_h;
            let lim_y: usize = (base_y + mcu_h).min(h_usize);
            let lim_x: usize = (base_x + mcu_w).min(w_usize);
            for py in base_y..lim_y {
                let ly: usize = py - base_y;
                for px in base_x..lim_x {
                    let lx: usize = px - base_x;
                    let dst: usize = (py * w_usize + px) * 4;
                    if components.len() == 1 {
                        let c0: &JpegComponentSpec = &components[0];
                        let sy: usize = ly * usize::from(c0.v_samp) / max_v;
                        let sx: usize = lx * usize::from(c0.h_samp) / max_h;
                        let y_val: u8 = comp_buffers[0][sy * usize::from(c0.h_samp) * 8 + sx];
                        rgba[dst] = y_val;
                        rgba[dst + 1] = y_val;
                        rgba[dst + 2] = y_val;
                        rgba[dst + 3] = 255;
                    } else {
                        let cy: &JpegComponentSpec = &components[0];
                        let ccb: &JpegComponentSpec = &components[1];
                        let ccr: &JpegComponentSpec = &components[2];
                        let y_sy: usize = ly * usize::from(cy.v_samp) / max_v;
                        let y_sx: usize = lx * usize::from(cy.h_samp) / max_h;
                        let cb_sy: usize = ly * usize::from(ccb.v_samp) / max_v;
                        let cb_sx: usize = lx * usize::from(ccb.h_samp) / max_h;
                        let cr_sy: usize = ly * usize::from(ccr.v_samp) / max_v;
                        let cr_sx: usize = lx * usize::from(ccr.h_samp) / max_h;
                        let y_f: f32 =
                            f32::from(comp_buffers[0][y_sy * usize::from(cy.h_samp) * 8 + y_sx]);
                        let cb_f: f32 =
                            f32::from(comp_buffers[1][cb_sy * usize::from(ccb.h_samp) * 8 + cb_sx])
                                - 128.0;
                        let cr_f: f32 =
                            f32::from(comp_buffers[2][cr_sy * usize::from(ccr.h_samp) * 8 + cr_sx])
                                - 128.0;
                        rgba[dst] = (y_f + 1.402 * cr_f).round().clamp(0.0, 255.0) as u8;
                        rgba[dst + 1] = (y_f - 0.344_136 * cb_f - 0.714_136 * cr_f)
                            .round()
                            .clamp(0.0, 255.0) as u8;
                        rgba[dst + 2] = (y_f + 1.772 * cb_f).round().clamp(0.0, 255.0) as u8;
                        rgba[dst + 3] = 255;
                    }
                }
            }
            mcu_counter += 1;
        }
    }
    Ok(DecodedRgbaImage {
        width,
        height,
        pixels: rgba,
        format: DecodedImageFormat::Jpeg,
    })
}

/// Computes JPEG Huffman magnitude category (`0..=11`) and bit representation for a signed coefficient.
///
/// # Arguments
///
/// - `i32` - Signed quantized DCT coefficient.
///
/// # Returns
///
/// - `(u8, u32)` - Tuple `(bit_length, encoded_bits)`.
#[must_use]
fn jpeg_encode_magnitude(value: i32) -> (u8, u32) {
    if value == 0 {
        return (0, 0);
    }
    let abs_val: u32 = value.unsigned_abs();
    let bits: u8 = (32 - abs_val.leading_zeros()) as u8;
    let code: u32 = if value > 0 {
        abs_val
    } else {
        ((1u32 << bits) - 1) - abs_val
    };
    (bits, code)
}

/// Encodes one 8x8 spatial block into the JPEG entropy writer.
///
/// # Arguments
///
/// - `&mut JpegBitWriter` - Destination entropy writer.
/// - `&[f32; 64]` - Level-shifted 8x8 spatial samples.
/// - `&[u8; 64]` - Quantization table in natural order.
/// - `&JpegHuffmanEncodeTable` - DC Huffman encode table.
/// - `&JpegHuffmanEncodeTable` - AC Huffman encode table.
/// - `&mut i32` - Running DC predictor.
fn jpeg_encode_block(
    writer: &mut JpegBitWriter,
    spatial: &[f32; 64],
    quant_nat: &[u8; 64],
    dc_tbl: &JpegHuffmanEncodeTable,
    ac_tbl: &JpegHuffmanEncodeTable,
    dc_pred: &mut i32,
) {
    let dct: [f32; 64] = jpeg_fdct_8x8(spatial);
    let mut zz: [i32; 64] = [0i32; 64];
    for zz_idx in 0..64usize {
        let nat_idx: usize = JPEG_ZIGZAG_TO_NATURAL[zz_idx];
        let q: f32 = f32::from(quant_nat[nat_idx]).max(1.0);
        zz[zz_idx] = (dct[nat_idx] / q).round() as i32;
    }
    let dc_diff: i32 = zz[0] - *dc_pred;
    *dc_pred = zz[0];
    let (dc_bits, dc_code): (u8, u32) = jpeg_encode_magnitude(dc_diff);
    let dc_sym: usize = usize::from(dc_bits);
    writer.write_bits(u32::from(dc_tbl.codes[dc_sym]), dc_tbl.lengths[dc_sym]);
    writer.write_bits(dc_code, dc_bits);
    let mut zero_run: u8 = 0;
    for &coeff in zz.iter().skip(1) {
        if coeff == 0 {
            zero_run += 1;
        } else {
            while zero_run >= 16 {
                writer.write_bits(u32::from(ac_tbl.codes[0xF0]), ac_tbl.lengths[0xF0]);
                zero_run -= 16;
            }
            let (ac_bits, ac_code): (u8, u32) = jpeg_encode_magnitude(coeff);
            let ac_sym: usize = usize::from((zero_run << 4) | ac_bits);
            writer.write_bits(u32::from(ac_tbl.codes[ac_sym]), ac_tbl.lengths[ac_sym]);
            writer.write_bits(ac_code, ac_bits);
            zero_run = 0;
        }
    }
    if zero_run > 0 {
        writer.write_bits(u32::from(ac_tbl.codes[0x00]), ac_tbl.lengths[0x00]);
    }
}

/// Scales a standard quantization table by JPEG quality (`1..=100`).
///
/// # Arguments
///
/// - `&[u8; 64]` - Base Annex K quantization table.
/// - `u8` - Quality level (`1..=100`).
///
/// # Returns
///
/// - `[u8; 64]` - Quality-scaled quantization table.
#[must_use]
fn jpeg_scale_quant_table(base: &[u8; 64], quality: u8) -> [u8; 64] {
    let q_clamped: u32 = u32::from(quality.clamp(1, 100));
    let scale: u32 = if q_clamped < 50 {
        5000 / q_clamped
    } else {
        200 - q_clamped * 2
    };
    let mut out: [u8; 64] = [1u8; 64];
    for idx in 0..64usize {
        let val: u32 = (u32::from(base[idx]) * scale + 50) / 100;
        out[idx] = val.clamp(1, 255) as u8;
    }
    out
}

/// Appends a JPEG DHT segment into `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination JPEG byte vector.
/// - `u8` - Class/slot byte (`(class << 4) | table_id`).
/// - `&[u8; 16]` - Code count array.
/// - `&[u8]` - Symbol array.
fn append_jpeg_dht(out: &mut Vec<u8>, tc_th: u8, bits: &[u8; 16], values: &[u8]) {
    let seg_len: u16 = (2 + 1 + 16 + values.len()) as u16;
    out.push(0xFF);
    out.push(0xC4);
    out.extend_from_slice(&seg_len.to_be_bytes());
    out.push(tc_th);
    out.extend_from_slice(bits);
    out.extend_from_slice(values);
}

/// Encodes an RGBA8 image into a spec-compliant 4:4:4 Baseline Sequential JPEG (`SOF0`) byte vector.
///
/// # Arguments
///
/// - `u32` - Image width in pixels.
/// - `u32` - Image height in pixels.
/// - `&[u8]` - Packed RGBA8 pixels (`width * height * 4` bytes).
/// - `u8` - Quality level (`1..=100`, e.g. `90`).
///
/// # Returns
///
/// - `Result<Vec<u8>, String>` - Encoded JPEG bytes or validation error.
pub fn encode_jpeg_rgba(
    width: u32,
    height: u32,
    rgba: &[u8],
    quality: u8,
) -> Result<Vec<u8>, String> {
    let w_usize: usize = width as usize;
    let h_usize: usize = height as usize;
    let expected: usize = w_usize.saturating_mul(h_usize).saturating_mul(4);
    let w_invalid: bool = width == 0 || width > 65_535;
    let h_invalid: bool = height == 0 || height > 65_535;
    let dims_invalid: bool = w_invalid || h_invalid;
    if dims_invalid || rgba.len() != expected {
        return Err(ERR_JPEG_ENCODE_ARGS.to_string());
    }
    let q_luma: [u8; 64] = jpeg_scale_quant_table(&JPEG_STD_LUMA_QUANT, quality);
    let q_chroma: [u8; 64] = jpeg_scale_quant_table(&JPEG_STD_CHROMA_QUANT, quality);
    let dc_luma: JpegHuffmanEncodeTable =
        JpegHuffmanEncodeTable::from_spec(&JPEG_STD_DC_LUMA_BITS, &JPEG_STD_DC_LUMA_VALS);
    let dc_chroma: JpegHuffmanEncodeTable =
        JpegHuffmanEncodeTable::from_spec(&JPEG_STD_DC_CHROMA_BITS, &JPEG_STD_DC_CHROMA_VALS);
    let ac_luma: JpegHuffmanEncodeTable =
        JpegHuffmanEncodeTable::from_spec(&JPEG_STD_AC_LUMA_BITS, &JPEG_STD_AC_LUMA_VALS);
    let ac_chroma: JpegHuffmanEncodeTable =
        JpegHuffmanEncodeTable::from_spec(&JPEG_STD_AC_CHROMA_BITS, &JPEG_STD_AC_CHROMA_VALS);
    let mut out: Vec<u8> = Vec::with_capacity(expected / 2 + 512);
    out.extend_from_slice(&[0xFF, 0xD8]);
    for (slot, table) in [(0u8, &q_luma), (1u8, &q_chroma)] {
        out.extend_from_slice(&[0xFF, 0xDB, 0x00, 0x43, slot]);
        for &nat_idx in JPEG_ZIGZAG_TO_NATURAL.iter() {
            out.push(table[nat_idx]);
        }
    }
    out.extend_from_slice(&[0xFF, 0xC0, 0x00, 0x11, 0x08]);
    out.extend_from_slice(&(height as u16).to_be_bytes());
    out.extend_from_slice(&(width as u16).to_be_bytes());
    out.extend_from_slice(&[3, 1, 0x11, 0, 2, 0x11, 1, 3, 0x11, 1]);
    append_jpeg_dht(
        &mut out,
        0x00,
        &JPEG_STD_DC_LUMA_BITS,
        &JPEG_STD_DC_LUMA_VALS,
    );
    append_jpeg_dht(
        &mut out,
        0x01,
        &JPEG_STD_DC_CHROMA_BITS,
        &JPEG_STD_DC_CHROMA_VALS,
    );
    append_jpeg_dht(
        &mut out,
        0x10,
        &JPEG_STD_AC_LUMA_BITS,
        &JPEG_STD_AC_LUMA_VALS,
    );
    append_jpeg_dht(
        &mut out,
        0x11,
        &JPEG_STD_AC_CHROMA_BITS,
        &JPEG_STD_AC_CHROMA_VALS,
    );
    out.extend_from_slice(&[
        0xFF, 0xDA, 0x00, 0x0C, 3, 1, 0x00, 2, 0x11, 3, 0x11, 0x00, 0x3F, 0x00,
    ]);
    let mut writer: JpegBitWriter = JpegBitWriter::default();
    let mut dc_y: i32 = 0;
    let mut dc_cb: i32 = 0;
    let mut dc_cr: i32 = 0;
    let mcus_x: usize = w_usize.div_ceil(8);
    let mcus_y: usize = h_usize.div_ceil(8);
    for mcu_y in 0..mcus_y {
        for mcu_x in 0..mcus_x {
            let mut blk_y: [f32; 64] = [0.0; 64];
            let mut blk_cb: [f32; 64] = [0.0; 64];
            let mut blk_cr: [f32; 64] = [0.0; 64];
            for row in 0..8usize {
                let sy: usize = (mcu_y * 8 + row).min(h_usize - 1);
                for col in 0..8usize {
                    let sx: usize = (mcu_x * 8 + col).min(w_usize - 1);
                    let src: usize = (sy * w_usize + sx) * 4;
                    let r_f: f32 = f32::from(rgba[src]);
                    let g_f: f32 = f32::from(rgba[src + 1]);
                    let b_f: f32 = f32::from(rgba[src + 2]);
                    let idx: usize = row * 8 + col;
                    blk_y[idx] = 0.299 * r_f + 0.587 * g_f + 0.114 * b_f - 128.0;
                    blk_cb[idx] = -0.168_736 * r_f - 0.331_264 * g_f + 0.5 * b_f;
                    blk_cr[idx] = 0.5 * r_f - 0.418_688 * g_f - 0.081_312 * b_f;
                }
            }
            jpeg_encode_block(&mut writer, &blk_y, &q_luma, &dc_luma, &ac_luma, &mut dc_y);
            jpeg_encode_block(
                &mut writer,
                &blk_cb,
                &q_chroma,
                &dc_chroma,
                &ac_chroma,
                &mut dc_cb,
            );
            jpeg_encode_block(
                &mut writer,
                &blk_cr,
                &q_chroma,
                &dc_chroma,
                &ac_chroma,
                &mut dc_cr,
            );
        }
    }
    writer.flush_ones();
    out.extend_from_slice(&writer.out);
    out.extend_from_slice(&[0xFF, 0xD9]);
    Ok(out)
}

/// Converts an IEEE 754 binary16 half-float bit pattern into `f32`.
///
/// # Arguments
///
/// - `u16` - Raw 16-bit half-float bit pattern.
///
/// # Returns
///
/// - `f32` - Equivalent single-precision floating-point value.
#[must_use]
pub fn f16_bits_to_f32(half_bits: u16) -> f32 {
    let sign: u32 = u32::from(half_bits & 0x8000) << 16;
    let exp: u32 = u32::from((half_bits >> 10) & 0x1F);
    let mant: u32 = u32::from(half_bits & 0x03FF);
    let bits32: u32 = if exp == 0 {
        if mant == 0 {
            sign
        } else {
            let mut shift: u32 = 0;
            let mut sub: u32 = mant;
            while (sub & 0x0400) == 0 {
                sub <<= 1;
                shift += 1;
            }
            let exp32: u32 = 127 - 15 - shift;
            let mant32: u32 = (sub & 0x03FF) << 13;
            sign | (exp32 << 23) | mant32
        }
    } else if exp == 31 {
        let base: u32 = sign | 0x7F80_0000;
        base | (mant << 13)
    } else {
        let exp32: u32 = exp + (127 - 15);
        let base: u32 = sign | (exp32 << 23);
        base | (mant << 13)
    };
    f32::from_bits(bits32)
}

/// Converts a single-precision `f32` into an IEEE 754 binary16 half-float bit pattern.
///
/// # Arguments
///
/// - `f32` - Source single-precision value.
///
/// # Returns
///
/// - `u16` - Rounded 16-bit half-float bit pattern.
#[must_use]
pub fn f32_to_f16_bits(value: f32) -> u16 {
    let bits: u32 = value.to_bits();
    let sign: u16 = ((bits >> 16) & 0x8000) as u16;
    let exp: i32 = ((bits >> 23) & 0xFF) as i32;
    let mant: u32 = bits & 0x007F_FFFF;
    if exp == 255 {
        let inf_bits: u16 = sign | 0x7C00;
        let nan_bit: u16 = if mant != 0 { 0x0200 } else { 0 };
        return inf_bits | nan_bit;
    }
    let exp16: i32 = exp - 127 + 15;
    if exp16 >= 31 {
        return sign | 0x7C00;
    }
    if exp16 <= 0 {
        if exp16 < -10 {
            return sign;
        }
        let full_mant: u32 = mant | 0x0080_0000;
        let shift: u32 = (14 - exp16) as u32;
        return sign | ((full_mant >> shift) as u16);
    }
    sign | ((exp16 as u16) << 10) | ((mant >> 13) as u16)
}

/// Converts a Radiance RGBE quad into linear floating-point RGB radiance.
///
/// # Arguments
///
/// - `[u8; 4]` - Encoded RGBE pixel `[r, g, b, exponent]`.
///
/// # Returns
///
/// - `[f32; 3]` - Linear RGB floating-point color.
#[cfg_attr(not(target_arch = "wasm32"), inline)]
#[must_use]
fn rgbe_to_linear(rgbe: [u8; 4]) -> [f32; 3] {
    if rgbe[3] == 0 {
        return [0.0, 0.0, 0.0];
    }
    let exp_val: i32 = i32::from(rgbe[3]) - 128 - 8;
    let scale: f32 = 2.0f32.powi(exp_val);
    [
        (f32::from(rgbe[0]) + 0.5) * scale,
        (f32::from(rgbe[1]) + 0.5) * scale,
        (f32::from(rgbe[2]) + 0.5) * scale,
    ]
}

/// Decodes a Radiance `.hdr` (RGBE + adaptive RLE) file into linear RGBA32F floats.
///
/// # Arguments
///
/// - `&[u8]` - Raw `.hdr` file bytes.
///
/// # Returns
///
/// - `Result<DecodedHdrImage, String>` - Decoded linear HDR image or parse error.
pub fn decode_radiance_hdr(bytes: &[u8]) -> Result<DecodedHdrImage, String> {
    let valid_magic: bool =
        bytes.starts_with(HDR_MAGIC_RADIANCE) || bytes.starts_with(HDR_MAGIC_RGBE);
    if !valid_magic {
        return Err(ERR_HDR_INVALID.to_string());
    }
    let mut pos: usize = 0;
    while pos < bytes.len() {
        let line_start: usize = pos;
        while pos < bytes.len() && bytes[pos] != b'\n' {
            pos += 1;
        }
        let line_end: usize = pos;
        if pos < bytes.len() {
            pos += 1;
        }
        let line: &[u8] = &bytes[line_start..line_end];
        let trimmed: &[u8] = if line.ends_with(b"\r") {
            &line[..line.len() - 1]
        } else {
            line
        };
        if trimmed.is_empty() {
            break;
        }
    }
    let res_start: usize = pos;
    while pos < bytes.len() && bytes[pos] != b'\n' {
        pos += 1;
    }
    let res_line_bytes: &[u8] = &bytes[res_start..pos];
    if pos < bytes.len() {
        pos += 1;
    }
    let res_str: &str = from_utf8(res_line_bytes)
        .ok()
        .ok_or_else(|| ERR_HDR_INVALID.to_string())?;
    let tokens: Vec<&str> = res_str.split_whitespace().collect();
    if tokens.len() < 4 {
        return Err(ERR_HDR_INVALID.to_string());
    }
    let height: u32 = tokens[1]
        .parse::<u32>()
        .ok()
        .ok_or_else(|| ERR_HDR_INVALID.to_string())?;
    let width: u32 = tokens[3]
        .parse::<u32>()
        .ok()
        .ok_or_else(|| ERR_HDR_INVALID.to_string())?;
    let w_bad: bool = width == 0 || width > IMAGE_MAX_DIMENSION;
    let h_bad: bool = height == 0 || height > IMAGE_MAX_DIMENSION;
    if w_bad || h_bad {
        return Err(ERR_HDR_INVALID.to_string());
    }
    let w_usize: usize = width as usize;
    let h_usize: usize = height as usize;
    let mut pixels: Vec<f32> =
        Vec::with_capacity(w_usize.saturating_mul(h_usize).saturating_mul(4));
    let mut scanline: Vec<[u8; 4]> = vec![[0u8; 4]; w_usize];
    for _ in 0..h_usize {
        if pos + 4 > bytes.len() {
            return Err(ERR_HDR_INVALID.to_string());
        }
        let is_new_rle: bool = bytes[pos] == 2
            && bytes[pos + 1] == 2
            && ((usize::from(bytes[pos + 2]) << 8) | usize::from(bytes[pos + 3])) == w_usize;
        if is_new_rle && (8..=32_767).contains(&w_usize) {
            pos += 4;
            for ch in 0..4usize {
                let mut col: usize = 0;
                while col < w_usize {
                    if pos >= bytes.len() {
                        return Err(ERR_HDR_INVALID.to_string());
                    }
                    let count_byte: u8 = bytes[pos];
                    pos += 1;
                    if count_byte > 128 {
                        let run_len: usize = usize::from(count_byte - 128);
                        if pos >= bytes.len() || col + run_len > w_usize {
                            return Err(ERR_HDR_INVALID.to_string());
                        }
                        let val: u8 = bytes[pos];
                        pos += 1;
                        for step in 0..run_len {
                            scanline[col + step][ch] = val;
                        }
                        col += run_len;
                    } else {
                        let lit_len: usize = usize::from(count_byte);
                        if lit_len == 0 || pos + lit_len > bytes.len() || col + lit_len > w_usize {
                            return Err(ERR_HDR_INVALID.to_string());
                        }
                        for step in 0..lit_len {
                            scanline[col + step][ch] = bytes[pos + step];
                        }
                        pos += lit_len;
                        col += lit_len;
                    }
                }
            }
        } else {
            let need: usize = w_usize * 4;
            if pos + need > bytes.len() {
                return Err(ERR_HDR_INVALID.to_string());
            }
            for (col, chunk) in bytes[pos..(pos + need)]
                .as_chunks::<4>()
                .0
                .iter()
                .enumerate()
            {
                scanline[col] = *chunk;
            }
            pos += need;
        }
        for &rgbe in scanline.iter() {
            let rgb: [f32; 3] = rgbe_to_linear(rgbe);
            pixels.push(rgb[0]);
            pixels.push(rgb[1]);
            pixels.push(rgb[2]);
            pixels.push(1.0);
        }
    }
    Ok(DecodedHdrImage {
        width,
        height,
        pixels,
        format: DecodedImageFormat::RadianceHdr,
    })
}

/// Reads a null-terminated ASCII string from `bytes` starting at `*pos`.
///
/// # Arguments
///
/// - `&[u8]` - Source byte buffer.
/// - `&mut usize` - Mutable cursor advanced past the terminating null byte.
///
/// # Returns
///
/// - `Result<String, String>` - Decoded ASCII string or bounds error.
fn read_cstr_at(bytes: &[u8], pos: &mut usize) -> Result<String, String> {
    let start: usize = *pos;
    while *pos < bytes.len() && bytes[*pos] != 0 {
        *pos += 1;
    }
    if *pos >= bytes.len() {
        return Err(ERR_EXR_INVALID.to_string());
    }
    let text: String = from_utf8(&bytes[start..*pos])
        .ok()
        .ok_or_else(|| ERR_EXR_INVALID.to_string())?
        .to_string();
    *pos += 1;
    Ok(text)
}

/// Undoes OpenEXR horizontal byte prediction and even/odd planar interleaving.
///
/// # Arguments
///
/// - `&mut [u8]` - Decompressed planar predictor bytes.
///
/// # Returns
///
/// - `Vec<u8>` - Restored raw scanline bytes.
#[must_use]
fn exr_undo_predictor_and_interleave(data: &mut [u8]) -> Vec<u8> {
    for idx in 1..data.len() {
        let sum: i32 = i32::from(data[idx - 1]) + i32::from(data[idx]) - 128;
        data[idx] = (sum & 0xFF) as u8;
    }
    let len: usize = data.len();
    let mut out: Vec<u8> = vec![0u8; len];
    let half: usize = len.div_ceil(2);
    let mut t1: usize = 0;
    let mut t2: usize = half;
    let mut dst: usize = 0;
    while dst < len {
        if t1 < half {
            out[dst] = data[t1];
            t1 += 1;
            dst += 1;
        }
        if dst < len && t2 < len {
            out[dst] = data[t2];
            t2 += 1;
            dst += 1;
        }
    }
    out
}

/// Decompresses an OpenEXR RLE-encoded byte buffer.
///
/// # Arguments
///
/// - `&[u8]` - RLE-compressed OpenEXR chunk payload.
/// - `usize` - Expected unpacked byte size.
///
/// # Returns
///
/// - `Result<Vec<u8>, String>` - Unpacked bytes or error.
fn exr_decompress_rle(input: &[u8], expected_len: usize) -> Result<Vec<u8>, String> {
    let mut out: Vec<u8> = Vec::with_capacity(expected_len);
    let mut pos: usize = 0;
    while pos < input.len() && out.len() < expected_len {
        let count: i8 = input[pos] as i8;
        pos += 1;
        if count < 0 {
            let lit_len: usize = usize::from(count.unsigned_abs());
            if pos + lit_len > input.len() {
                return Err(ERR_EXR_INVALID.to_string());
            }
            out.extend_from_slice(&input[pos..(pos + lit_len)]);
            pos += lit_len;
        } else {
            let run_len: usize = usize::from(count as u8) + 1;
            if pos >= input.len() {
                return Err(ERR_EXR_INVALID.to_string());
            }
            let val: u8 = input[pos];
            pos += 1;
            for _ in 0..run_len {
                out.push(val);
            }
        }
    }
    if out.len() != expected_len {
        return Err(ERR_EXR_INVALID.to_string());
    }
    Ok(exr_undo_predictor_and_interleave(&mut out))
}

/// Decodes a single-part scanline OpenEXR `.exr` image (NO_COMPRESSION, RLE, ZIPS, ZIP; HALF/FLOAT) into linear RGBA32F.
///
/// # Arguments
///
/// - `&[u8]` - Raw `.exr` file bytes.
///
/// # Returns
///
/// - `Result<DecodedHdrImage, String>` - Decoded linear HDR image or parse error.
pub fn decode_openexr_hdr(bytes: &[u8]) -> Result<DecodedHdrImage, String> {
    if bytes.len() < 16 || bytes[0..4] != OPENEXR_SIGNATURE {
        return Err(ERR_EXR_INVALID.to_string());
    }
    let version_field: u32 = u32::from_le_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]);
    if (version_field & 0xFF) != 2 || (version_field & 0x0E00) != 0 {
        return Err(ERR_EXR_INVALID.to_string());
    }
    let mut pos: usize = 8;
    let mut channels: Vec<ExrChannelDesc> = Vec::new();
    let mut compression: u8 = 0;
    let mut data_window: Option<[i32; 4]> = None;
    loop {
        if pos >= bytes.len() {
            return Err(ERR_EXR_INVALID.to_string());
        }
        if bytes[pos] == 0 {
            pos += 1;
            break;
        }
        let attr_name: String = read_cstr_at(bytes, &mut pos)?;
        let _attr_type: String = read_cstr_at(bytes, &mut pos)?;
        if pos + 4 > bytes.len() {
            return Err(ERR_EXR_INVALID.to_string());
        }
        let attr_size: usize =
            u32::from_le_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
                as usize;
        pos += 4;
        if pos + attr_size > bytes.len() {
            return Err(ERR_EXR_INVALID.to_string());
        }
        let payload: &[u8] = &bytes[pos..(pos + attr_size)];
        if attr_name == EXR_ATTR_CHANNELS {
            let mut cpos: usize = 0;
            while cpos < payload.len() && payload[cpos] != 0 {
                let ch_name: String = read_cstr_at(payload, &mut cpos)?;
                if cpos + 16 > payload.len() {
                    return Err(ERR_EXR_INVALID.to_string());
                }
                let pixel_type: i32 = i32::from_le_bytes([
                    payload[cpos],
                    payload[cpos + 1],
                    payload[cpos + 2],
                    payload[cpos + 3],
                ]);
                cpos += 16;
                channels.push(ExrChannelDesc {
                    name: ch_name,
                    pixel_type,
                });
            }
        } else if attr_name == EXR_ATTR_COMPRESSION && !payload.is_empty() {
            compression = payload[0];
        } else if attr_name == EXR_ATTR_DATA_WINDOW && payload.len() >= 16 {
            let x_min: i32 = i32::from_le_bytes([payload[0], payload[1], payload[2], payload[3]]);
            let y_min: i32 = i32::from_le_bytes([payload[4], payload[5], payload[6], payload[7]]);
            let x_max: i32 = i32::from_le_bytes([payload[8], payload[9], payload[10], payload[11]]);
            let y_max: i32 =
                i32::from_le_bytes([payload[12], payload[13], payload[14], payload[15]]);
            data_window = Some([x_min, y_min, x_max, y_max]);
        }
        pos += attr_size;
    }
    let Some(win) = data_window else {
        return Err(ERR_EXR_INVALID.to_string());
    };
    let win_bad: bool = win[2] < win[0] || win[3] < win[1];
    let header_bad: bool = channels.is_empty() || win_bad;
    if header_bad || compression > 3 {
        return Err(ERR_EXR_INVALID.to_string());
    }
    let width: u32 = (win[2] - win[0] + 1) as u32;
    let height: u32 = (win[3] - win[1] + 1) as u32;
    if width > IMAGE_MAX_DIMENSION || height > IMAGE_MAX_DIMENSION {
        return Err(ERR_EXR_INVALID.to_string());
    }
    let w_usize: usize = width as usize;
    let h_usize: usize = height as usize;
    let lines_per_block: usize = if compression == 3 { 16 } else { 1 };
    let block_count: usize = h_usize.div_ceil(lines_per_block);
    if pos + block_count * 8 > bytes.len() {
        return Err(ERR_EXR_INVALID.to_string());
    }
    let mut offsets: Vec<usize> = Vec::with_capacity(block_count);
    for idx in 0..block_count {
        let base: usize = pos + idx * 8;
        let off: u64 = u64::from_le_bytes([
            bytes[base],
            bytes[base + 1],
            bytes[base + 2],
            bytes[base + 3],
            bytes[base + 4],
            bytes[base + 5],
            bytes[base + 6],
            bytes[base + 7],
        ]);
        offsets.push(off as usize);
    }
    let mut bytes_per_pixel_line: usize = 0;
    for ch in channels.iter() {
        let elem_size: usize = match ch.pixel_type {
            1 => 2,
            0 | 2 => 4,
            _ => return Err(ERR_EXR_INVALID.to_string()),
        };
        bytes_per_pixel_line = bytes_per_pixel_line.saturating_add(elem_size * w_usize);
    }
    let mut pixels: Vec<f32> = vec![0.0; w_usize.saturating_mul(h_usize).saturating_mul(4)];
    for px_idx in 0..(w_usize * h_usize) {
        pixels[px_idx * 4 + 3] = 1.0;
    }
    for &chunk_off in offsets.iter() {
        if chunk_off + 8 > bytes.len() {
            return Err(ERR_EXR_INVALID.to_string());
        }
        let y_coord: i32 = i32::from_le_bytes([
            bytes[chunk_off],
            bytes[chunk_off + 1],
            bytes[chunk_off + 2],
            bytes[chunk_off + 3],
        ]);
        let packed_size: usize = u32::from_le_bytes([
            bytes[chunk_off + 4],
            bytes[chunk_off + 5],
            bytes[chunk_off + 6],
            bytes[chunk_off + 7],
        ]) as usize;
        let payload_start: usize = chunk_off + 8;
        if payload_start + packed_size > bytes.len() {
            return Err(ERR_EXR_INVALID.to_string());
        }
        let row_start: usize = (y_coord - win[1]).max(0) as usize;
        let block_lines: usize = lines_per_block.min(h_usize.saturating_sub(row_start));
        let expected_raw: usize = block_lines.saturating_mul(bytes_per_pixel_line);
        let packed: &[u8] = &bytes[payload_start..(payload_start + packed_size)];
        let unpacked: Vec<u8> = if compression == 0 || packed_size == expected_raw {
            packed.to_vec()
        } else if compression == 1 {
            exr_decompress_rle(packed, expected_raw)?
        } else {
            let mut raw_zlib: Vec<u8> = inflate_zlib(packed)?;
            if raw_zlib.len() != expected_raw {
                return Err(ERR_EXR_INVALID.to_string());
            }
            exr_undo_predictor_and_interleave(&mut raw_zlib)
        };
        let mut cursor: usize = 0;
        for line_offset in 0..block_lines {
            let dst_y: usize = row_start + line_offset;
            for ch in channels.iter() {
                let target_slot: Option<usize> = match ch.name.as_str() {
                    "R" => Some(0),
                    "G" => Some(1),
                    "B" => Some(2),
                    "A" => Some(3),
                    _ => None,
                };
                let elem_size: usize = if ch.pixel_type == 1 { 2 } else { 4 };
                if cursor + elem_size * w_usize > unpacked.len() {
                    return Err(ERR_EXR_INVALID.to_string());
                }
                if let Some(slot) = target_slot {
                    for col in 0..w_usize {
                        let src_off: usize = cursor + col * elem_size;
                        let val: f32 = if ch.pixel_type == 1 {
                            f16_bits_to_f32(u16::from_le_bytes([
                                unpacked[src_off],
                                unpacked[src_off + 1],
                            ]))
                        } else if ch.pixel_type == 2 {
                            f32::from_le_bytes([
                                unpacked[src_off],
                                unpacked[src_off + 1],
                                unpacked[src_off + 2],
                                unpacked[src_off + 3],
                            ])
                        } else {
                            u32::from_le_bytes([
                                unpacked[src_off],
                                unpacked[src_off + 1],
                                unpacked[src_off + 2],
                                unpacked[src_off + 3],
                            ]) as f32
                        };
                        pixels[(dst_y * w_usize + col) * 4 + slot] = val;
                    }
                }
                cursor += elem_size * w_usize;
            }
        }
    }
    Ok(DecodedHdrImage {
        width,
        height,
        pixels,
        format: DecodedImageFormat::OpenExr,
    })
}

/// Automatically detects and decodes a PNG, JPEG, BMP, Radiance HDR, or OpenEXR byte slice into RGBA8.
///
/// # Arguments
///
/// - `&[u8]` - Raw encoded image file bytes.
///
/// # Returns
///
/// - `Result<DecodedRgbaImage, String>` - Decoded RGBA8 raster image or format error.
pub fn decode_raster_image_rgba(bytes: &[u8]) -> Result<DecodedRgbaImage, String> {
    if bytes.len() >= 8 && bytes[0..8] == PNG_SIGNATURE {
        return decode_png_rgba(bytes);
    }
    if bytes.len() >= 3 && bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF {
        return decode_jpeg_rgba(bytes);
    }
    if bytes.len() >= 2 && &bytes[0..2] == MAGIC_BMP {
        let asset: ImageAsset = MediaCodecRegistry::decode_bmp(bytes, IMAGE_LABEL_PNG)?;
        let buf: &ImageBuffer = asset.get_buffer();
        return Ok(DecodedRgbaImage {
            width: buf.get_width(),
            height: buf.get_height(),
            pixels: buf.get_pixels().to_vec(),
            format: DecodedImageFormat::Bmp,
        });
    }
    if bytes.starts_with(HDR_MAGIC_RADIANCE) || bytes.starts_with(HDR_MAGIC_RGBE) {
        let hdr: DecodedHdrImage = decode_radiance_hdr(bytes)?;
        return Ok(hdr.to_tonemapped_rgba8(1.0));
    }
    if bytes.len() >= 4 && bytes[0..4] == OPENEXR_SIGNATURE {
        let hdr: DecodedHdrImage = decode_openexr_hdr(bytes)?;
        return Ok(hdr.to_tonemapped_rgba8(1.0));
    }
    Err(ERR_IMAGE_UNSUPPORTED.to_string())
}