zenpng 0.1.4

PNG encoding and decoding with zencodec trait integration
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
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
//! zencodec trait implementations for PNG.
//!
//! Provides [`PngEncoderConfig`] and [`PngDecoderConfig`] types that implement the
//! [`EncoderConfig`] / [`DecoderConfig`] traits from zencodec.
#![allow(dead_code)]

extern crate std;

use alloc::borrow::Cow;
use alloc::vec::Vec;

use whereat::{At, at};
use zencodec::decode::{AnimationFrame, DecodeCapabilities, DecodeOutput, OutputInfo};
use zencodec::encode::{EncodeCapabilities, EncodeOutput};
use zencodec::{ImageFormat, ImageInfo, Metadata, ResourceLimits};
use zenpixels::{Pixel, PixelDescriptor, PixelSlice, PixelSliceMut};

use crate::decode::PngDecodeConfig;
use crate::encode::EncodeConfig;
use crate::error::PngError;

/// Default encode timeout: 120 seconds.
const DEFAULT_TIMEOUT_MS: u64 = 120_000;

/// Create a default encode deadline.
///
/// On native targets, returns a `WithTimeout` that expires after `DEFAULT_TIMEOUT_MS`.
/// On `wasm32`, `Instant::now()` panics (no system clock), so we return `Unstoppable`.
fn default_deadline() -> impl enough::Stop {
    #[cfg(not(target_arch = "wasm32"))]
    {
        almost_enough::time::WithTimeout::new(
            enough::Unstoppable,
            std::time::Duration::from_millis(DEFAULT_TIMEOUT_MS),
        )
    }
    #[cfg(target_arch = "wasm32")]
    {
        enough::Unstoppable
    }
}

// ── Supported descriptors ────────────────────────────────────────────

static ENCODE_DESCRIPTORS: &[PixelDescriptor] = &[
    PixelDescriptor::RGB8_SRGB,
    PixelDescriptor::RGBA8_SRGB,
    PixelDescriptor::GRAY8_SRGB,
    PixelDescriptor::BGRA8_SRGB,
    PixelDescriptor::RGBX8_SRGB,
    PixelDescriptor::BGRX8_SRGB,
    PixelDescriptor::RGB16_SRGB,
    PixelDescriptor::RGBA16_SRGB,
    PixelDescriptor::GRAY16_SRGB,
    PixelDescriptor::RGBF32_LINEAR,
    PixelDescriptor::RGBAF32_LINEAR,
    PixelDescriptor::GRAYF32_LINEAR,
];

static DECODE_DESCRIPTORS: &[PixelDescriptor] = &[
    PixelDescriptor::RGB8_SRGB,
    PixelDescriptor::RGBA8_SRGB,
    PixelDescriptor::GRAY8_SRGB,
    PixelDescriptor::BGRA8_SRGB,
    PixelDescriptor::RGB16_SRGB,
    PixelDescriptor::RGBA16_SRGB,
    PixelDescriptor::GRAY16_SRGB,
    PixelDescriptor::RGBF32_LINEAR,
    PixelDescriptor::RGBAF32_LINEAR,
    PixelDescriptor::GRAYF32_LINEAR,
];

// ── PngEncoderConfig ─────────────────────────────────────────────────

/// PNG encoder configuration implementing [`EncoderConfig`](zencodec::EncoderConfig).
///
/// Use [`with_compression`](PngEncoderConfig::with_compression) to control compression level.
/// When the `quantize` feature is enabled, setting quality < 100 enables
/// auto-indexed encoding via [`encode_auto`](crate::encode_auto),
/// which quantizes RGBA8 images to ≤256 colors when quality is acceptable.
#[derive(Clone, Debug)]
pub struct PngEncoderConfig {
    config: EncodeConfig,
    effort: Option<i32>,
    quality: Option<f32>,
    lossless: bool,
}

impl PngEncoderConfig {
    /// Create a default PNG encoder config.
    #[must_use]
    pub fn new() -> Self {
        Self {
            config: EncodeConfig::default(),
            effort: None,
            quality: None,
            lossless: true,
        }
    }

    /// Set PNG compression level directly.
    #[must_use]
    pub fn with_compression(mut self, compression: crate::Compression) -> Self {
        self.config.compression = compression;
        self
    }

    /// Set PNG row filter strategy directly.
    #[must_use]
    pub fn with_filter(mut self, filter: crate::Filter) -> Self {
        self.config.filter = filter;
        self
    }

    /// Set near-lossless bit rounding (0-4).
    ///
    /// Rounds least-significant bits of each 8-bit sample to improve
    /// compression without palette quantization.
    #[must_use]
    pub fn with_near_lossless_bits(mut self, bits: u8) -> Self {
        self.config.near_lossless_bits = bits;
        self
    }

    /// Convenience: encode RGB8 pixels in one call.
    pub fn encode_rgb8(
        &self,
        img: imgref::ImgRef<'_, Rgb<u8>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode RGBA8 pixels in one call.
    pub fn encode_rgba8(
        &self,
        img: imgref::ImgRef<'_, Rgba<u8>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode Gray8 pixels in one call.
    pub fn encode_gray8(
        &self,
        img: imgref::ImgRef<'_, Gray<u8>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode RGB16 pixels in one call.
    pub fn encode_rgb16(
        &self,
        img: imgref::ImgRef<'_, Rgb<u16>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode RGBA16 pixels in one call.
    pub fn encode_rgba16(
        &self,
        img: imgref::ImgRef<'_, Rgba<u16>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode Gray16 pixels in one call.
    pub fn encode_gray16(
        &self,
        img: imgref::ImgRef<'_, Gray<u16>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode RGB F32 pixels in one call.
    pub fn encode_rgb_f32(
        &self,
        img: imgref::ImgRef<'_, Rgb<f32>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode RGBA F32 pixels in one call.
    pub fn encode_rgba_f32(
        &self,
        img: imgref::ImgRef<'_, Rgba<f32>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode Gray F32 pixels in one call.
    pub fn encode_gray_f32(
        &self,
        img: imgref::ImgRef<'_, Gray<f32>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }

    /// Convenience: encode BGRA8 pixels (swizzles to RGBA) in one call.
    pub fn encode_bgra8(
        &self,
        img: imgref::ImgRef<'_, rgb::alt::BGRA<u8>>,
    ) -> Result<EncodeOutput, At<PngError>> {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};
        self.clone()
            .job()
            .encoder()?
            .encode(PixelSlice::from(img).erase())
    }
}

impl Default for PngEncoderConfig {
    fn default() -> Self {
        Self::new()
    }
}

fn effort_to_compression(effort: i32) -> crate::Compression {
    use crate::Compression;
    match effort {
        ..=0 => Compression::None,
        1 => Compression::Fastest,
        2 => Compression::Turbo,
        3 => Compression::Fast,
        4 => Compression::Balanced,
        5 => Compression::Thorough,
        6 => Compression::High,
        7 => Compression::Aggressive,
        8 => Compression::Intense,
        9 => Compression::Crush,
        10 => Compression::Maniac,
        11 => Compression::Brag,
        _ => Compression::Minutes,
    }
}

/// Convert generic quality (0–100) to MPE threshold.
///
/// Piecewise-linear interpolation calibrated so that `quality=Q` produces
/// the same SSIMULACRA2 score as libjpeg-turbo at quality Q, via the chain:
///
///   quality → MPE threshold → (zenquant quantization) → MPE → SSIM2
///
/// Derived from 27,170 libjpeg-turbo measurements across 209 CID22-512
/// images (SSIM2 anchor), plus zenquant's 1992-image MPE↔SSIM2 calibration.
///
/// | quality | libjpeg SSIM2 | MPE    |
/// |---------|---------------|--------|
/// | 100     | lossless      | 0.000  |
/// | 99      | 95.9          | 0.003  |
/// | 95      | 91.5          | 0.007  |
/// | 90      | 87.7          | 0.011  |
/// | 85      | 84.3          | 0.015  |
/// | 80      | 81.2          | 0.020  |
/// | 75      | 78.3          | 0.026  |
/// | 70      | 75.3          | 0.031  |
/// | 60      | 72.0          | 0.037  |
/// | 50      | 68.4          | 0.044  |
/// | 40      | 63.9          | 0.052  |
/// | 30      | 59.2          | 0.060  |
/// | 0       | —             | 0.100  |
fn quality_to_mpe(quality: f32) -> f32 {
    // (quality, mpe) — sorted descending by quality.
    // Calibrated to match libjpeg-turbo SSIMULACRA2 at each quality level.
    const TABLE: [(f32, f32); 14] = [
        (100.0, 0.000),
        (99.0, 0.003),
        (95.0, 0.007),
        (90.0, 0.011),
        (85.0, 0.015),
        (80.0, 0.020),
        (75.0, 0.026),
        (70.0, 0.031),
        (60.0, 0.037),
        (50.0, 0.044),
        (40.0, 0.052),
        (30.0, 0.060),
        (10.0, 0.085),
        (0.0, 0.100),
    ];

    let quality = quality.clamp(0.0, 100.0);

    // Exact endpoint matches
    if quality >= TABLE[0].0 {
        return TABLE[0].1;
    }
    let last = TABLE.len() - 1;
    if quality <= TABLE[last].0 {
        return TABLE[last].1;
    }

    // Find the bracketing interval (table is sorted descending by quality)
    for i in 0..last {
        let (q_hi, mpe_hi) = TABLE[i];
        let (q_lo, mpe_lo) = TABLE[i + 1];
        if quality >= q_lo {
            let t = (q_hi - quality) / (q_hi - q_lo);
            return mpe_hi + t * (mpe_lo - mpe_hi);
        }
    }
    TABLE[last].1
}

/// Apply threading policy to PNG encode config fields.
fn apply_threading(config: &mut crate::encode::EncodeConfig, policy: zencodec::ThreadingPolicy) {
    if policy.is_parallel() {
        // max_threads 0 = no limit (use ambient pool / all cores)
        config.max_threads = 0;
    } else {
        config.max_threads = 1;
        config.parallel = false;
    }
}

static PNG_ENCODE_CAPS: EncodeCapabilities = EncodeCapabilities::new()
    .with_icc(true)
    .with_exif(true)
    .with_xmp(true)
    .with_cicp(true)
    .with_stop(true)
    .with_animation(true)
    .with_lossless(true)
    .with_lossy(true)
    .with_native_gray(true)
    .with_native_16bit(true)
    .with_native_f32(true)
    .with_native_alpha(true)
    .with_push_rows(true)
    .with_enforces_max_pixels(true)
    .with_enforces_max_memory(true)
    .with_effort_range(0, 12)
    .with_quality_range(0.0, 100.0)
    .with_threads_supported_range(1, 16);

impl zencodec::encode::EncoderConfig for PngEncoderConfig {
    type Error = At<PngError>;
    type Job = PngEncodeJob;

    fn format() -> ImageFormat {
        ImageFormat::Png
    }

    fn supported_descriptors() -> &'static [PixelDescriptor] {
        ENCODE_DESCRIPTORS
    }

    fn capabilities() -> &'static EncodeCapabilities {
        &PNG_ENCODE_CAPS
    }

    fn with_generic_effort(mut self, effort: i32) -> Self {
        self.effort = Some(effort);
        self.config.compression = effort_to_compression(effort);
        self
    }

    fn generic_effort(&self) -> Option<i32> {
        self.effort
    }

    fn with_generic_quality(mut self, quality: f32) -> Self {
        self.quality = Some(quality);
        // Setting quality < 100 implicitly enables lossy (auto-indexed) mode
        if quality < 100.0 {
            self.lossless = false;
        }
        self
    }

    fn generic_quality(&self) -> Option<f32> {
        self.quality
    }

    fn with_lossless(mut self, lossless: bool) -> Self {
        self.lossless = lossless;
        self
    }

    fn is_lossless(&self) -> Option<bool> {
        Some(self.lossless)
    }

    fn job(self) -> PngEncodeJob {
        PngEncodeJob {
            config: self,
            stop: None,
            metadata: None,
            limits: None,
            policy: None,
            canvas_width: 0,
            canvas_height: 0,
            loop_count: None,
        }
    }
}

// ── PngEncodeJob ─────────────────────────────────────────────────────

/// Per-operation PNG encode job.
pub struct PngEncodeJob {
    config: PngEncoderConfig,
    stop: Option<zencodec::StopToken>,
    metadata: Option<Metadata>,
    limits: Option<ResourceLimits>,
    policy: Option<zencodec::encode::EncodePolicy>,
    canvas_width: u32,
    canvas_height: u32,
    loop_count: Option<u32>,
}

impl zencodec::encode::EncodeJob for PngEncodeJob {
    type Error = At<PngError>;
    type Enc = PngEncoder;
    type AnimationFrameEnc = PngAnimationFrameEncoder;

    fn with_stop(mut self, stop: zencodec::StopToken) -> Self {
        self.stop = Some(stop);
        self
    }

    fn with_metadata(mut self, meta: Metadata) -> Self {
        self.metadata = Some(meta);
        self
    }

    fn with_limits(mut self, limits: ResourceLimits) -> Self {
        self.limits = Some(limits);
        self
    }

    fn with_policy(mut self, policy: zencodec::encode::EncodePolicy) -> Self {
        self.policy = Some(policy);
        self
    }

    fn with_canvas_size(mut self, width: u32, height: u32) -> Self {
        self.canvas_width = width;
        self.canvas_height = height;
        self
    }

    fn with_loop_count(mut self, count: Option<u32>) -> Self {
        self.loop_count = count;
        self
    }

    fn encoder(self) -> Result<PngEncoder, At<PngError>> {
        Ok(PngEncoder {
            config: self.config,
            stop: self.stop,
            metadata: self.metadata,
            limits: self.limits,
            policy: self.policy,
            canvas_width: self.canvas_width,
            canvas_height: self.canvas_height,
            streaming: None,
        })
    }

    fn animation_frame_encoder(self) -> Result<PngAnimationFrameEncoder, At<PngError>> {
        let effective_meta = apply_encode_policy(self.metadata.as_ref(), self.policy.as_ref());
        let mut config = self.config.config.clone();
        if let Some(ref limits) = self.limits {
            apply_threading(&mut config, limits.threading());
        }
        let mut enc = PngAnimationFrameEncoder::new(
            config,
            self.canvas_width,
            self.canvas_height,
            effective_meta,
        );
        enc.loop_count = self.loop_count.unwrap_or(0);
        enc.limits = self.limits;
        Ok(enc)
    }
}

// ── PngEncoder ───────────────────────────────────────────────────────

/// Single-image PNG encoder.
pub struct PngEncoder {
    config: PngEncoderConfig,
    stop: Option<zencodec::StopToken>,
    metadata: Option<Metadata>,
    limits: Option<ResourceLimits>,
    policy: Option<zencodec::encode::EncodePolicy>,
    /// Canvas dimensions for push_rows mode (set via `with_canvas_size`).
    canvas_width: u32,
    canvas_height: u32,
    /// Streaming state, lazily initialized on first push_rows() call.
    streaming: Option<StreamingMode>,
}

/// Streaming mode selection for push_rows/finish.
enum StreamingMode {
    /// Buffer all pixel data, encode in finish() (effort > 1).
    Buffered(BufferedStreamingState),
    /// True streaming: emit stored DEFLATE blocks as rows arrive (effort 0).
    TrueStreaming(TrueStreamingState),
    /// Pre-filtered streaming: filter rows on arrival, compress in finish() (effort 1).
    /// Saves ~1× image size vs Buffered by eliminating the raw pixel buffer.
    PreFiltered(PreFilteredState),
}

/// Buffered state: accumulates raw pixel bytes, delegates to encode_raw in finish().
struct BufferedStreamingState {
    /// Accumulated raw pixel bytes in PNG's native byte order.
    pixel_data: Vec<u8>,
    /// PNG color type (0=Gray, 2=RGB, 4=GrayAlpha, 6=RGBA).
    color_type: crate::encode::ColorType,
    /// PNG bit depth.
    bit_depth: crate::encode::BitDepth,
    /// Bytes per row (width × bpp, no filter byte).
    row_bytes: usize,
    /// Rows received so far.
    rows_pushed: u32,
}

/// True streaming state: writes PNG output incrementally as rows arrive.
///
/// At effort 0, rows are written as stored DEFLATE blocks (no compression).
/// This avoids buffering the full image — only one previous row is kept for
/// filtering. Output bytes are built directly in the output Vec.
struct TrueStreamingState {
    /// Growing PNG output (signature + IHDR + metadata already written).
    output: Vec<u8>,
    /// Scratch buffer for format conversion (row_bytes). Only allocated for
    /// formats that need conversion (float, 16-bit, BGRA); empty otherwise.
    convert_buf: Vec<u8>,
    /// Bytes per row (width × bpp, no filter byte).
    row_bytes: usize,
    /// Rows received so far.
    rows_pushed: u32,
    /// Running Adler-32 checksum for zlib.
    adler: u32,
    /// Position of IDAT length field in output (for backpatching).
    idat_len_pos: usize,
    /// Remaining bytes in current stored DEFLATE block.
    block_remaining: usize,
    /// Remaining filtered bytes in the entire image.
    filtered_remaining: usize,
}

/// Pre-filtered streaming state: filters rows on arrival, compresses in finish().
///
/// At effort 1, the single Paeth filter is applied per-row as data arrives.
/// The filtered bytes (filter_byte + row_data per row) accumulate in `filtered_data`.
/// On finish(), the buffer is compressed with Turbo and assembled into a PNG.
///
/// Peak memory: ~1× image (filtered data) + compressed output.
/// vs Buffered: ~2× image (raw pixels + filter pass inside compress_filtered).
struct PreFilteredState {
    /// PNG preamble: signature + IHDR + metadata chunks.
    preamble: Vec<u8>,
    /// Accumulated pre-filtered row data ([filter_byte, filtered_row...] per row).
    filtered_data: Vec<u8>,
    /// Previous row in PNG byte order (for Paeth reference). Zeroed for first row.
    prev_row: Vec<u8>,
    /// Scratch buffer for format conversion (row_bytes).
    convert_buf: Vec<u8>,
    /// PNG filter type (4 = Paeth).
    filter_type: u8,
    /// Bytes per pixel in PNG output format.
    bpp: usize,
    /// Bytes per row (width × bpp, no filter byte).
    row_bytes: usize,
    /// Rows received so far.
    rows_pushed: u32,
    /// PNG color type.
    color_type: crate::encode::ColorType,
    /// PNG bit depth.
    bit_depth: crate::encode::BitDepth,
    /// Zenflate compression effort for finish().
    zenflate_effort: u32,
}

impl PngEncoder {
    fn config_with_threading(&self) -> EncodeConfig {
        let mut config = self.config.config.clone();
        if let Some(ref limits) = self.limits {
            apply_threading(&mut config, limits.threading());
        }
        config
    }

    fn do_encode(
        &self,
        bytes: &[u8],
        w: u32,
        h: u32,
        color_type: crate::encode::ColorType,
    ) -> Result<EncodeOutput, At<PngError>> {
        self.do_encode_with_depth(bytes, w, h, color_type, crate::encode::BitDepth::Eight)
    }

    fn do_encode_with_depth(
        &self,
        bytes: &[u8],
        w: u32,
        h: u32,
        color_type: crate::encode::ColorType,
        bit_depth: crate::encode::BitDepth,
    ) -> Result<EncodeOutput, At<PngError>> {
        let cancel: &dyn enough::Stop = match self.stop {
            Some(ref s) => s as &dyn enough::Stop,
            None => &enough::Unstoppable,
        };
        // Pre-flight stop check
        cancel.check().map_err(|e| at!(PngError::from(e)))?;
        // Pre-flight limit checks
        if let Some(ref limits) = self.limits {
            limits
                .check_dimensions(w, h)
                .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
            let channels: u64 = match color_type {
                crate::encode::ColorType::Grayscale => 1,
                crate::encode::ColorType::Rgb => 3,
                crate::encode::ColorType::GrayscaleAlpha => 2,
                crate::encode::ColorType::Rgba => 4,
            };
            let depth_bytes: u64 = match bit_depth {
                crate::encode::BitDepth::Eight => 1,
                crate::encode::BitDepth::Sixteen => 2,
            };
            let bpp = channels * depth_bytes;
            let estimated_mem = w as u64 * h as u64 * bpp;
            limits
                .check_memory(estimated_mem)
                .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
        }
        let config = self.config_with_threading();
        let deadline = default_deadline();
        // Apply encode policy to filter metadata
        let effective_meta = apply_encode_policy(self.metadata.as_ref(), self.policy.as_ref());
        let meta_ref = effective_meta.as_ref();
        let data = crate::encode::encode_raw(
            bytes, w, h, color_type, bit_depth, meta_ref, &config, cancel, &deadline,
        )?;
        // Post-encode output size check
        if let Some(ref limits) = self.limits {
            limits
                .check_output_size(data.len() as u64)
                .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
        }
        Ok(EncodeOutput::new(data, ImageFormat::Png))
    }
}

impl zencodec::encode::Encoder for PngEncoder {
    type Error = At<PngError>;

    fn reject(op: zencodec::UnsupportedOperation) -> At<PngError> {
        at!(PngError::from(op))
    }

    fn preferred_strip_height(&self) -> u32 {
        1 // PNG uses row-at-a-time filtering
    }

    fn encode(self, pixels: PixelSlice<'_>) -> Result<EncodeOutput, At<PngError>> {
        use linear_srgb::default::{linear_to_srgb_u8_rgba_slice, linear_to_srgb_u8_slice};
        use zenpixels::PixelFormat;

        let w = pixels.width();
        let h = pixels.rows();
        // Policy-filtered metadata for auto-indexed paths (used by auto-quantize paths)
        #[cfg(any(feature = "quantize", feature = "imagequant", feature = "quantette"))]
        let effective_meta = apply_encode_policy(self.metadata.as_ref(), self.policy.as_ref());
        #[cfg(any(feature = "quantize", feature = "imagequant", feature = "quantette"))]
        let meta_ref = effective_meta.as_ref();

        match pixels.descriptor().pixel_format() {
            PixelFormat::Rgb8 => {
                let bytes = contiguous_bytes(&pixels);
                self.do_encode(&bytes, w, h, crate::encode::ColorType::Rgb)
            }
            PixelFormat::Rgba8 => {
                // Auto-indexed path when not lossless and quality < 100
                #[cfg(any(feature = "quantize", feature = "imagequant", feature = "quantette"))]
                if !self.config.lossless
                    && let Some(q) = self.config.quality
                    && q < 100.0
                {
                    let bytes = contiguous_bytes(&pixels);
                    let rgba: &[Rgba<u8>] = bytemuck::cast_slice(&bytes);
                    let img = imgref::Img::new(rgba, w as usize, h as usize);
                    let mpe = quality_to_mpe(q);
                    let cancel: &dyn enough::Stop = match self.stop {
                        Some(ref s) => s as &dyn enough::Stop,
                        None => &enough::Unstoppable,
                    };
                    let deadline = default_deadline();
                    let quantizer = crate::default_quantizer();
                    let config = self.config_with_threading();
                    let result = crate::encode_auto(
                        img,
                        &config,
                        &*quantizer,
                        crate::QualityGate::MaxMpe(mpe),
                        meta_ref,
                        cancel,
                        &deadline,
                    )?;
                    return Ok(EncodeOutput::new(result.data, ImageFormat::Png));
                }

                let bytes = contiguous_bytes(&pixels);
                self.do_encode(&bytes, w, h, crate::encode::ColorType::Rgba)
            }
            PixelFormat::Gray8 => {
                let bytes = contiguous_bytes(&pixels);
                self.do_encode(&bytes, w, h, crate::encode::ColorType::Grayscale)
            }
            PixelFormat::Rgb16 => {
                let bytes = contiguous_bytes(&pixels);
                let be = native_to_be_16(&bytes);
                self.do_encode_with_depth(
                    &be,
                    w,
                    h,
                    crate::encode::ColorType::Rgb,
                    crate::encode::BitDepth::Sixteen,
                )
            }
            PixelFormat::Rgba16 => {
                let bytes = contiguous_bytes(&pixels);
                let be = native_to_be_16(&bytes);
                self.do_encode_with_depth(
                    &be,
                    w,
                    h,
                    crate::encode::ColorType::Rgba,
                    crate::encode::BitDepth::Sixteen,
                )
            }
            PixelFormat::Gray16 => {
                let bytes = contiguous_bytes(&pixels);
                let be = native_to_be_16(&bytes);
                self.do_encode_with_depth(
                    &be,
                    w,
                    h,
                    crate::encode::ColorType::Grayscale,
                    crate::encode::BitDepth::Sixteen,
                )
            }
            PixelFormat::RgbF32 => {
                let src = contiguous_bytes(&pixels);
                let floats: &[f32] = bytemuck::cast_slice(&src);
                let mut srgb = vec![0u8; floats.len()];
                linear_to_srgb_u8_slice(floats, &mut srgb);
                self.do_encode(&srgb, w, h, crate::encode::ColorType::Rgb)
            }
            PixelFormat::RgbaF32 => {
                let src = contiguous_bytes(&pixels);
                let floats: &[f32] = bytemuck::cast_slice(&src);
                let mut srgb = vec![0u8; floats.len()];
                linear_to_srgb_u8_rgba_slice(floats, &mut srgb);

                // Auto-indexed path when not lossless and quality < 100
                #[cfg(any(feature = "quantize", feature = "imagequant", feature = "quantette"))]
                if !self.config.lossless
                    && let Some(q) = self.config.quality
                    && q < 100.0
                {
                    let rgba: &[Rgba<u8>] = bytemuck::cast_slice(&srgb);
                    let img = imgref::Img::new(rgba, w as usize, h as usize);
                    let mpe = quality_to_mpe(q);
                    let cancel: &dyn enough::Stop = match self.stop {
                        Some(ref s) => s as &dyn enough::Stop,
                        None => &enough::Unstoppable,
                    };
                    let deadline = default_deadline();
                    let quantizer = crate::default_quantizer();
                    let config = self.config_with_threading();
                    let result = crate::encode_auto(
                        img,
                        &config,
                        &*quantizer,
                        crate::QualityGate::MaxMpe(mpe),
                        meta_ref,
                        cancel,
                        &deadline,
                    )?;
                    return Ok(EncodeOutput::new(result.data, ImageFormat::Png));
                }

                self.do_encode(&srgb, w, h, crate::encode::ColorType::Rgba)
            }
            PixelFormat::GrayF32 => {
                let src = contiguous_bytes(&pixels);
                let floats: &[f32] = bytemuck::cast_slice(&src);
                let mut srgb = vec![0u8; floats.len()];
                linear_to_srgb_u8_slice(floats, &mut srgb);
                self.do_encode(&srgb, w, h, crate::encode::ColorType::Grayscale)
            }
            PixelFormat::Bgra8 => {
                let raw = contiguous_bytes(&pixels);
                let rgba: Vec<u8> = raw
                    .chunks_exact(4)
                    .flat_map(|c| [c[2], c[1], c[0], c[3]])
                    .collect();
                self.do_encode(&rgba, w, h, crate::encode::ColorType::Rgba)
            }
            PixelFormat::Rgbx8 => {
                // Padding byte 3 is undefined — strip to RGB.
                let raw = contiguous_bytes(&pixels);
                let rgb: Vec<u8> = raw
                    .chunks_exact(4)
                    .flat_map(|c| [c[0], c[1], c[2]])
                    .collect();
                self.do_encode(&rgb, w, h, crate::encode::ColorType::Rgb)
            }
            PixelFormat::Bgrx8 => {
                // BGRA layout with padding byte 3 — strip to RGB via swap.
                let raw = contiguous_bytes(&pixels);
                let rgb: Vec<u8> = raw
                    .chunks_exact(4)
                    .flat_map(|c| [c[2], c[1], c[0]])
                    .collect();
                self.do_encode(&rgb, w, h, crate::encode::ColorType::Rgb)
            }
            _ => Err(at!(PngError::from(
                zencodec::UnsupportedOperation::PixelFormat
            ))),
        }
    }

    fn push_rows(&mut self, rows: PixelSlice<'_>) -> Result<(), At<PngError>> {
        use linear_srgb::default::{linear_to_srgb_u8_rgba_slice, linear_to_srgb_u8_slice};
        use zenpixels::PixelFormat;

        let w = rows.width();
        let h = rows.rows();

        if h == 0 {
            return Ok(());
        }

        // Initialize streaming state on first call.
        if self.streaming.is_none() {
            let (color_type, bit_depth) = pixel_format_to_png(rows.descriptor().pixel_format())
                .ok_or_else(|| at!(PngError::from(zencodec::UnsupportedOperation::PixelFormat)))?;

            // Infer width from first push if not set via with_canvas_size
            if self.canvas_width == 0 {
                self.canvas_width = w;
            }

            let channels: usize = match color_type {
                crate::encode::ColorType::Grayscale => 1,
                crate::encode::ColorType::Rgb => 3,
                crate::encode::ColorType::GrayscaleAlpha => 2,
                crate::encode::ColorType::Rgba => 4,
            };
            let depth_bytes: usize = match bit_depth {
                crate::encode::BitDepth::Eight => 1,
                crate::encode::BitDepth::Sixteen => 2,
            };
            let row_bytes = self.canvas_width as usize * channels * depth_bytes;
            let effort = self.config.config.compression.effort();

            let bpp = channels * depth_bytes;
            if effort == 0 && self.canvas_height > 0 {
                // True streaming: write PNG header and IDAT incrementally.
                self.streaming = Some(StreamingMode::TrueStreaming(TrueStreamingState::new(
                    self.canvas_width,
                    self.canvas_height,
                    color_type,
                    bit_depth,
                    row_bytes,
                    self.metadata.as_ref(),
                    self.policy.as_ref(),
                    &self.config.config,
                )?));
            } else if effort == 1 && self.canvas_height > 0 {
                // Pre-filtered streaming: filter rows on arrival, compress in finish().
                self.streaming = Some(StreamingMode::PreFiltered(PreFilteredState::new(
                    self.canvas_width,
                    self.canvas_height,
                    color_type,
                    bit_depth,
                    row_bytes,
                    bpp,
                    self.metadata.as_ref(),
                    self.policy.as_ref(),
                    &self.config.config,
                )?));
            } else {
                // Buffered: accumulate pixel data, encode in finish().
                let capacity = if self.canvas_height > 0 {
                    row_bytes * self.canvas_height as usize
                } else {
                    row_bytes * h as usize
                };
                self.streaming = Some(StreamingMode::Buffered(BufferedStreamingState {
                    pixel_data: Vec::with_capacity(capacity),
                    color_type,
                    bit_depth,
                    row_bytes,
                    rows_pushed: 0,
                }));
            }
        }

        // Width must be consistent across calls.
        if w != self.canvas_width && self.canvas_width > 0 {
            return Err(at!(PngError::InvalidInput(alloc::format!(
                "push_rows: width {} does not match canvas width {}",
                w,
                self.canvas_width
            ))));
        }

        let format = rows.descriptor().pixel_format();
        let mode = self.streaming.as_mut().unwrap();

        match mode {
            StreamingMode::Buffered(state) => {
                // Check for overflow
                if self.canvas_height > 0 && state.rows_pushed + h > self.canvas_height {
                    return Err(at!(PngError::InvalidInput(alloc::format!(
                        "push_rows: would exceed canvas height {} (already pushed {}, pushing {})",
                        self.canvas_height,
                        state.rows_pushed,
                        h
                    ))));
                }

                // Reserve all needed capacity in one shot — no per-row reallocs.
                state.pixel_data.reserve(state.row_bytes * h as usize);

                for y in 0..h {
                    let src = rows.row(y);
                    match format {
                        PixelFormat::Rgb8 | PixelFormat::Rgba8 | PixelFormat::Gray8 => {
                            state.pixel_data.extend_from_slice(&src[..state.row_bytes]);
                        }
                        PixelFormat::Rgb16 | PixelFormat::Rgba16 | PixelFormat::Gray16 => {
                            let samples: &[u16] = bytemuck::cast_slice(&src[..state.row_bytes]);
                            for &val in samples {
                                state.pixel_data.extend_from_slice(&val.to_be_bytes());
                            }
                        }
                        PixelFormat::RgbF32 | PixelFormat::GrayF32 => {
                            let floats: &[f32] = bytemuck::cast_slice(src);
                            let start = state.pixel_data.len();
                            state.pixel_data.resize(start + floats.len(), 0);
                            linear_to_srgb_u8_slice(floats, &mut state.pixel_data[start..]);
                        }
                        PixelFormat::RgbaF32 => {
                            let floats: &[f32] = bytemuck::cast_slice(src);
                            let start = state.pixel_data.len();
                            state.pixel_data.resize(start + floats.len(), 0);
                            linear_to_srgb_u8_rgba_slice(floats, &mut state.pixel_data[start..]);
                        }
                        PixelFormat::Bgra8 => {
                            for c in src.chunks_exact(4) {
                                state
                                    .pixel_data
                                    .extend_from_slice(&[c[2], c[1], c[0], c[3]]);
                            }
                        }
                        PixelFormat::Rgbx8 => {
                            let row_pixels = self.canvas_width as usize;
                            for c in src.chunks_exact(4).take(row_pixels) {
                                state.pixel_data.extend_from_slice(&[c[0], c[1], c[2]]);
                            }
                        }
                        PixelFormat::Bgrx8 => {
                            let row_pixels = self.canvas_width as usize;
                            for c in src.chunks_exact(4).take(row_pixels) {
                                state.pixel_data.extend_from_slice(&[c[2], c[1], c[0]]);
                            }
                        }
                        _ => {
                            return Err(at!(PngError::from(
                                zencodec::UnsupportedOperation::PixelFormat
                            )));
                        }
                    }
                }
                state.rows_pushed += h;
            }
            StreamingMode::TrueStreaming(state) => {
                // Check for overflow
                if state.rows_pushed + h > self.canvas_height {
                    return Err(at!(PngError::InvalidInput(alloc::format!(
                        "push_rows: would exceed canvas height {} (already pushed {}, pushing {})",
                        self.canvas_height,
                        state.rows_pushed,
                        h
                    ))));
                }

                for y in 0..h {
                    let src = rows.row(y);
                    // Convert source pixels into PNG byte order, then write
                    // as a stored DEFLATE row. convert_buf is reused per row.
                    match format {
                        PixelFormat::Rgb8 | PixelFormat::Rgba8 | PixelFormat::Gray8 => {
                            state.push_raw_row(&src[..state.row_bytes]);
                        }
                        PixelFormat::Rgb16 | PixelFormat::Rgba16 | PixelFormat::Gray16 => {
                            let samples: &[u16] = bytemuck::cast_slice(&src[..state.row_bytes]);
                            for (i, &val) in samples.iter().enumerate() {
                                let be = val.to_be_bytes();
                                state.convert_buf[i * 2] = be[0];
                                state.convert_buf[i * 2 + 1] = be[1];
                            }
                            state.push_converted_row();
                        }
                        PixelFormat::RgbF32 | PixelFormat::GrayF32 => {
                            let floats: &[f32] = bytemuck::cast_slice(src);
                            linear_to_srgb_u8_slice(floats, &mut state.convert_buf);
                            state.push_converted_row();
                        }
                        PixelFormat::RgbaF32 => {
                            let floats: &[f32] = bytemuck::cast_slice(src);
                            linear_to_srgb_u8_rgba_slice(floats, &mut state.convert_buf);
                            state.push_converted_row();
                        }
                        PixelFormat::Bgra8 => {
                            for (i, c) in src.chunks_exact(4).enumerate() {
                                state.convert_buf[i * 4] = c[2];
                                state.convert_buf[i * 4 + 1] = c[1];
                                state.convert_buf[i * 4 + 2] = c[0];
                                state.convert_buf[i * 4 + 3] = c[3];
                            }
                            state.push_converted_row();
                        }
                        PixelFormat::Rgbx8 => {
                            let row_pixels = self.canvas_width as usize;
                            for (i, c) in src.chunks_exact(4).enumerate().take(row_pixels) {
                                state.convert_buf[i * 3] = c[0];
                                state.convert_buf[i * 3 + 1] = c[1];
                                state.convert_buf[i * 3 + 2] = c[2];
                            }
                            state.push_converted_row();
                        }
                        PixelFormat::Bgrx8 => {
                            let row_pixels = self.canvas_width as usize;
                            for (i, c) in src.chunks_exact(4).enumerate().take(row_pixels) {
                                state.convert_buf[i * 3] = c[2];
                                state.convert_buf[i * 3 + 1] = c[1];
                                state.convert_buf[i * 3 + 2] = c[0];
                            }
                            state.push_converted_row();
                        }
                        _ => {
                            return Err(at!(PngError::from(
                                zencodec::UnsupportedOperation::PixelFormat
                            )));
                        }
                    }
                }
            }
            StreamingMode::PreFiltered(state) => {
                // Check for overflow
                if state.rows_pushed + h > self.canvas_height {
                    return Err(at!(PngError::InvalidInput(alloc::format!(
                        "push_rows: would exceed canvas height {} (already pushed {}, pushing {})",
                        self.canvas_height,
                        state.rows_pushed,
                        h
                    ))));
                }

                for y in 0..h {
                    let src = rows.row(y);
                    match format {
                        PixelFormat::Rgb8 | PixelFormat::Rgba8 | PixelFormat::Gray8 => {
                            state.push_raw_row(&src[..state.row_bytes]);
                        }
                        PixelFormat::Rgb16 | PixelFormat::Rgba16 | PixelFormat::Gray16 => {
                            let samples: &[u16] = bytemuck::cast_slice(&src[..state.row_bytes]);
                            for (i, &val) in samples.iter().enumerate() {
                                let be = val.to_be_bytes();
                                state.convert_buf[i * 2] = be[0];
                                state.convert_buf[i * 2 + 1] = be[1];
                            }
                            state.push_converted_row();
                        }
                        PixelFormat::RgbF32 | PixelFormat::GrayF32 => {
                            let floats: &[f32] = bytemuck::cast_slice(src);
                            linear_to_srgb_u8_slice(floats, &mut state.convert_buf);
                            state.push_converted_row();
                        }
                        PixelFormat::RgbaF32 => {
                            let floats: &[f32] = bytemuck::cast_slice(src);
                            linear_to_srgb_u8_rgba_slice(floats, &mut state.convert_buf);
                            state.push_converted_row();
                        }
                        PixelFormat::Bgra8 => {
                            for (i, c) in src.chunks_exact(4).enumerate() {
                                state.convert_buf[i * 4] = c[2];
                                state.convert_buf[i * 4 + 1] = c[1];
                                state.convert_buf[i * 4 + 2] = c[0];
                                state.convert_buf[i * 4 + 3] = c[3];
                            }
                            state.push_converted_row();
                        }
                        PixelFormat::Rgbx8 => {
                            let row_pixels = self.canvas_width as usize;
                            for (i, c) in src.chunks_exact(4).enumerate().take(row_pixels) {
                                state.convert_buf[i * 3] = c[0];
                                state.convert_buf[i * 3 + 1] = c[1];
                                state.convert_buf[i * 3 + 2] = c[2];
                            }
                            state.push_converted_row();
                        }
                        PixelFormat::Bgrx8 => {
                            let row_pixels = self.canvas_width as usize;
                            for (i, c) in src.chunks_exact(4).enumerate().take(row_pixels) {
                                state.convert_buf[i * 3] = c[2];
                                state.convert_buf[i * 3 + 1] = c[1];
                                state.convert_buf[i * 3 + 2] = c[0];
                            }
                            state.push_converted_row();
                        }
                        _ => {
                            return Err(at!(PngError::from(
                                zencodec::UnsupportedOperation::PixelFormat
                            )));
                        }
                    }
                }
            }
        }
        Ok(())
    }

    fn finish(mut self) -> Result<EncodeOutput, At<PngError>> {
        let mode = self.streaming.take().ok_or_else(|| {
            at!(PngError::InvalidInput(
                "finish() called without any push_rows() calls".into()
            ))
        })?;

        match mode {
            StreamingMode::Buffered(state) => {
                let h = state.rows_pushed;
                let w = self.canvas_width;

                if w == 0 || h == 0 {
                    return Err(at!(PngError::InvalidInput("no pixel data pushed".into())));
                }

                // Validate total data size
                let expected = state.row_bytes * h as usize;
                if state.pixel_data.len() != expected {
                    return Err(at!(PngError::InvalidInput(alloc::format!(
                        "finish: pixel data size {} does not match expected {} ({}×{} rows)",
                        state.pixel_data.len(),
                        expected,
                        state.row_bytes,
                        h
                    ))));
                }

                self.do_encode_with_depth(
                    &state.pixel_data,
                    w,
                    h,
                    state.color_type,
                    state.bit_depth,
                )
            }
            StreamingMode::TrueStreaming(state) => {
                if state.rows_pushed == 0 {
                    return Err(at!(PngError::InvalidInput("no pixel data pushed".into())));
                }
                let data = state.finish();
                if let Some(ref limits) = self.limits {
                    limits
                        .check_output_size(data.len() as u64)
                        .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
                }
                Ok(EncodeOutput::new(data, ImageFormat::Png))
            }
            StreamingMode::PreFiltered(state) => {
                if state.rows_pushed == 0 {
                    return Err(at!(PngError::InvalidInput("no pixel data pushed".into())));
                }
                let cancel: &dyn enough::Stop = match self.stop {
                    Some(ref s) => s as &dyn enough::Stop,
                    None => &enough::Unstoppable,
                };
                let data = state.finish(cancel)?;
                if let Some(ref limits) = self.limits {
                    limits
                        .check_output_size(data.len() as u64)
                        .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
                }
                Ok(EncodeOutput::new(data, ImageFormat::Png))
            }
        }
    }
}

// ── PngAnimationFrameEncoder ──────────────────────────────────────────────

/// Accumulated frame data for APNG encoding.
struct AccumulatedFrame {
    pixels: Vec<u8>, // RGBA8 canvas-sized
    duration_ms: u32,
}

/// APNG frame-by-frame encoder implementing [`AnimationFrameEncoder`](zencodec::encode::AnimationFrameEncoder).
///
/// Accumulates canvas-sized RGBA8 frames, then encodes them all on [`finish()`](PngAnimationFrameEncoder::do_finish).
pub struct PngAnimationFrameEncoder {
    frames: Vec<AccumulatedFrame>,
    canvas_width: u32,
    canvas_height: u32,
    config: crate::encode::EncodeConfig,
    metadata: Option<Metadata>,
    loop_count: u32,
    /// In-progress frame being built row-by-row.
    building_frame: Option<BuildingFrame>,
    /// Resource limits for frame accumulation.
    limits: Option<ResourceLimits>,
    /// Cumulative pixel data size across all accumulated frames.
    cumulative_pixel_bytes: u64,
}

/// State for row-by-row frame construction.
struct BuildingFrame {
    pixels: Vec<u8>,
    duration_ms: u32,
    rows_pushed: u32,
}

impl PngAnimationFrameEncoder {
    fn new(
        config: crate::encode::EncodeConfig,
        canvas_width: u32,
        canvas_height: u32,
        metadata: Option<Metadata>,
    ) -> Self {
        Self {
            frames: Vec::new(),
            canvas_width,
            canvas_height,
            config,
            metadata,
            loop_count: 0,
            building_frame: None,
            limits: None,
            cumulative_pixel_bytes: 0,
        }
    }

    /// Extract RGBA8 bytes from a PixelSlice, converting as needed.
    ///
    /// Supports RGBA8, BGRA8, RGB8, and Gray8 inputs. Other formats
    /// (16-bit, float) are rejected with a clear error listing the
    /// supported formats.
    fn pixels_to_rgba8(pixels: &PixelSlice<'_>) -> Result<Vec<u8>, At<PngError>> {
        let desc = pixels.descriptor();
        match (desc.channel_type(), desc.layout()) {
            (zenpixels::ChannelType::U8, zenpixels::ChannelLayout::Rgba) => {
                Ok(contiguous_bytes(pixels).into_owned())
            }
            (zenpixels::ChannelType::U8, zenpixels::ChannelLayout::Bgra) => {
                let src = contiguous_bytes(pixels);
                Ok(src
                    .chunks_exact(4)
                    .flat_map(|c| [c[2], c[1], c[0], c[3]])
                    .collect())
            }
            (zenpixels::ChannelType::U8, zenpixels::ChannelLayout::Rgb) => {
                let src = contiguous_bytes(pixels);
                Ok(src
                    .chunks_exact(3)
                    .flat_map(|c| [c[0], c[1], c[2], 255])
                    .collect())
            }
            (zenpixels::ChannelType::U8, zenpixels::ChannelLayout::Gray) => {
                let src = contiguous_bytes(pixels);
                Ok(src.iter().flat_map(|&g| [g, g, g, 255]).collect())
            }
            _ => Err(at!(PngError::InvalidInput(alloc::format!(
                "APNG frame encoder: unsupported pixel format {:?}; \
                 supported formats are RGBA8, BGRA8, RGB8, and Gray8",
                desc
            )))),
        }
    }
}

impl zencodec::encode::AnimationFrameEncoder for PngAnimationFrameEncoder {
    type Error = At<PngError>;

    fn reject(op: zencodec::UnsupportedOperation) -> At<PngError> {
        at!(PngError::from(op))
    }

    fn push_frame(
        &mut self,
        pixels: PixelSlice<'_>,
        duration_ms: u32,
        _stop: Option<&dyn enough::Stop>,
    ) -> Result<(), At<PngError>> {
        let rgba = Self::pixels_to_rgba8(&pixels)?;
        // Check resource limits before accumulating
        if let Some(ref limits) = self.limits {
            // Check max_frames (new frame count = current + 1)
            limits
                .check_frames(self.frames.len() as u32 + 1)
                .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
            // Check max_memory (cumulative pixel data size)
            let new_cumulative = self.cumulative_pixel_bytes + rgba.len() as u64;
            limits
                .check_memory(new_cumulative)
                .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
        }
        self.cumulative_pixel_bytes += rgba.len() as u64;
        self.frames.push(AccumulatedFrame {
            pixels: rgba,
            duration_ms,
        });
        Ok(())
    }

    fn finish(self, stop: Option<&dyn enough::Stop>) -> Result<EncodeOutput, At<PngError>> {
        self.do_finish(stop)
    }
}

impl PngAnimationFrameEncoder {
    fn do_finish(self, stop: Option<&dyn enough::Stop>) -> Result<EncodeOutput, At<PngError>> {
        let cancel: &dyn enough::Stop = stop.unwrap_or(&enough::Unstoppable);
        cancel.check().map_err(|e| at!(PngError::from(e)))?;

        if self.frames.is_empty() {
            return Err(at!(PngError::InvalidInput(
                "APNG frame encoder: no frames pushed".into(),
            )));
        }

        // Convert accumulated frames to ApngFrameInput
        let inputs: Vec<crate::encode::ApngFrameInput<'_>> = self
            .frames
            .iter()
            .map(|f| {
                // Convert ms to delay_num/delay_den
                // Use den=1000 for ms precision
                crate::encode::ApngFrameInput {
                    pixels: &f.pixels,
                    delay_num: f.duration_ms.min(65535) as u16,
                    delay_den: 1000,
                }
            })
            .collect();

        let apng_config = crate::encode::ApngEncodeConfig {
            encode: self.config.clone(),
            num_plays: self.loop_count,
        };

        let deadline = default_deadline();

        let data = crate::encode::encode_apng(
            &inputs,
            self.canvas_width,
            self.canvas_height,
            &apng_config,
            self.metadata.as_ref(),
            cancel,
            &deadline,
        )
        .map_err(|e| e.decompose().0)?;

        Ok(EncodeOutput::new(data, ImageFormat::Png))
    }
}

// ── PngDecoderConfig ─────────────────────────────────────────────────

/// PNG decoder configuration implementing [`DecoderConfig`](zencodec::DecoderConfig).
#[derive(Clone, Debug)]
pub struct PngDecoderConfig {
    limits: ResourceLimits,
}

impl PngDecoderConfig {
    /// Create a default PNG decoder config with safe resource limits.
    #[must_use]
    pub fn new() -> Self {
        Self {
            limits: ResourceLimits::none()
                .with_max_pixels(PngDecodeConfig::DEFAULT_MAX_PIXELS)
                .with_max_memory(PngDecodeConfig::DEFAULT_MAX_MEMORY),
        }
    }
}

impl PngDecoderConfig {
    /// Create a decode job by consuming this config.
    ///
    /// This is an inherent convenience that avoids importing `DecoderConfig`.
    /// Equivalent to `DecoderConfig::job(self)`.
    #[must_use]
    pub fn job_static(self) -> PngDecodeJob {
        PngDecodeJob {
            config: self,
            stop: None,
            limits: None,
            policy: None,
            start_frame_index: 0,
        }
    }

    /// Convenience: decode in one call (native format).
    pub fn decode(&self, data: &[u8]) -> Result<DecodeOutput, At<PngError>> {
        use zencodec::decode::{Decode, DecodeJob, DecoderConfig};
        self.clone()
            .job()
            .decoder(Cow::Borrowed(data), &[])?
            .decode()
    }

    /// Convenience: probe image header.
    pub fn probe(&self, data: &[u8]) -> Result<ImageInfo, At<PngError>> {
        use zencodec::decode::{DecodeJob, DecoderConfig};
        self.clone().job().probe(data)
    }

    /// Convenience: probe header (alias for backwards compatibility).
    pub fn probe_header(&self, data: &[u8]) -> Result<ImageInfo, At<PngError>> {
        self.probe(data)
    }

    /// Convenience: decode into an RGB8 target buffer.
    pub fn decode_into_rgb8(
        &self,
        data: &[u8],
        dst: imgref::ImgRefMut<'_, Rgb<u8>>,
    ) -> Result<ImageInfo, At<PngError>> {
        let mut dst: PixelSliceMut<'_> = PixelSliceMut::from(dst).erase();
        let output = self.decode(data)?;
        let info = output.info().clone();
        let pixels = output.into_buffer();
        let src = to_rgb8(pixels);
        copy_rows_u8(&src, &mut dst);
        Ok(info)
    }

    /// Convenience: decode into an RGB16 target buffer.
    pub fn decode_into_rgb16(
        &self,
        data: &[u8],
        dst: imgref::ImgRefMut<'_, Rgb<u16>>,
    ) -> Result<ImageInfo, At<PngError>> {
        let mut dst: PixelSliceMut<'_> = PixelSliceMut::from(dst).erase();
        let output = self.decode(data)?;
        let info = output.info().clone();
        let pixels = output.into_buffer();
        decode_into_rgb16(pixels, &mut dst);
        Ok(info)
    }

    /// Convenience: decode into an RGB F32 target buffer.
    pub fn decode_into_rgb_f32(
        &self,
        data: &[u8],
        dst: imgref::ImgRefMut<'_, Rgb<f32>>,
    ) -> Result<ImageInfo, At<PngError>> {
        let mut dst: PixelSliceMut<'_> = PixelSliceMut::from(dst).erase();
        let output = self.decode(data)?;
        let info = output.info().clone();
        let pixels = output.into_buffer();
        decode_into_rgb_f32(pixels, &mut dst);
        Ok(info)
    }

    /// Convenience: decode into an RGBA F32 target buffer.
    pub fn decode_into_rgba_f32(
        &self,
        data: &[u8],
        dst: imgref::ImgRefMut<'_, Rgba<f32>>,
    ) -> Result<ImageInfo, At<PngError>> {
        let mut dst: PixelSliceMut<'_> = PixelSliceMut::from(dst).erase();
        let output = self.decode(data)?;
        let info = output.info().clone();
        let pixels = output.into_buffer();
        decode_into_rgba_f32(pixels, &mut dst);
        Ok(info)
    }

    /// Convenience: decode into a Gray F32 target buffer.
    pub fn decode_into_gray_f32(
        &self,
        data: &[u8],
        dst: imgref::ImgRefMut<'_, Gray<f32>>,
    ) -> Result<ImageInfo, At<PngError>> {
        let mut dst: PixelSliceMut<'_> = PixelSliceMut::from(dst).erase();
        let output = self.decode(data)?;
        let info = output.info().clone();
        let pixels = output.into_buffer();
        decode_into_gray_f32(pixels, &mut dst);
        Ok(info)
    }
}

impl Default for PngDecoderConfig {
    fn default() -> Self {
        Self::new()
    }
}

static PNG_DECODE_CAPS: DecodeCapabilities = DecodeCapabilities::new()
    .with_icc(true)
    .with_exif(true)
    .with_xmp(true)
    .with_cicp(true)
    .with_stop(true)
    .with_animation(true)
    .with_cheap_probe(true)
    .with_native_gray(true)
    .with_native_16bit(true)
    .with_native_alpha(true)
    .with_streaming(true)
    .with_decode_into(true)
    .with_enforces_max_pixels(true)
    .with_enforces_max_memory(true)
    .with_enforces_max_input_bytes(true);

impl zencodec::decode::DecoderConfig for PngDecoderConfig {
    type Error = At<PngError>;
    type Job<'a> = PngDecodeJob;

    fn formats() -> &'static [ImageFormat] {
        &[ImageFormat::Png]
    }

    fn supported_descriptors() -> &'static [PixelDescriptor] {
        DECODE_DESCRIPTORS
    }

    fn capabilities() -> &'static DecodeCapabilities {
        &PNG_DECODE_CAPS
    }

    fn job<'a>(self) -> Self::Job<'a> {
        PngDecodeJob {
            config: self,
            stop: None,
            limits: None,
            policy: None,
            start_frame_index: 0,
        }
    }
}

// ── PngDecodeJob ─────────────────────────────────────────────────────

/// Per-operation PNG decode job.
pub struct PngDecodeJob {
    config: PngDecoderConfig,
    stop: Option<zencodec::StopToken>,
    limits: Option<ResourceLimits>,
    policy: Option<zencodec::decode::DecodePolicy>,
    start_frame_index: u32,
}

impl<'a> zencodec::decode::DecodeJob<'a> for PngDecodeJob {
    type Error = At<PngError>;
    type Dec = PngDecoder<'a>;
    type StreamDec = PngStreamingDecoder<'a>;
    type AnimationFrameDec = PngAnimationFrameDecoder;

    fn with_stop(mut self, stop: zencodec::StopToken) -> Self {
        self.stop = Some(stop);
        self
    }

    fn with_limits(mut self, limits: ResourceLimits) -> Self {
        self.limits = Some(limits);
        self
    }

    fn with_policy(mut self, policy: zencodec::decode::DecodePolicy) -> Self {
        self.policy = Some(policy);
        self
    }

    fn with_start_frame_index(mut self, index: u32) -> Self {
        self.start_frame_index = index;
        self
    }

    fn probe(&self, data: &[u8]) -> Result<ImageInfo, At<PngError>> {
        let info = crate::decode::probe(data)?;
        let mut image_info = convert_info(&info);
        if let Ok(probe) = crate::detect::probe(data) {
            image_info = image_info.with_source_encoding_details(probe);
        }
        apply_policy_to_info(&mut image_info, self.policy.as_ref());
        Ok(image_info)
    }

    fn output_info(&self, data: &[u8]) -> Result<OutputInfo, At<PngError>> {
        let info = crate::decode::probe(data)?;
        // Derive has_trns: has_alpha is set for color types 4/6 (intrinsic alpha)
        // or when a tRNS chunk is present. If has_alpha is true but color_type
        // doesn't have intrinsic alpha, then tRNS must be present.
        let intrinsic_alpha = info.color_type == 4 || info.color_type == 6;
        let has_trns = info.has_alpha && !intrinsic_alpha;
        let native_format = native_output_descriptor(info.color_type, info.bit_depth, has_trns);
        Ok(
            OutputInfo::full_decode(info.width, info.height, native_format)
                .with_alpha(info.has_alpha),
        )
    }

    fn decoder(
        self,
        data: Cow<'a, [u8]>,
        preferred: &[PixelDescriptor],
    ) -> Result<PngDecoder<'a>, At<PngError>> {
        Ok(PngDecoder {
            config: self.config,
            stop: self.stop,
            limits: self.limits,
            policy: self.policy,
            data,
            preferred: preferred.to_vec(),
        })
    }

    fn streaming_decoder(
        self,
        data: Cow<'a, [u8]>,
        preferred: &[PixelDescriptor],
    ) -> Result<PngStreamingDecoder<'a>, At<PngError>> {
        PngStreamingDecoder::new(
            data,
            &self.config,
            self.stop,
            self.limits.as_ref(),
            self.policy.as_ref(),
            preferred,
        )
    }

    fn animation_frame_decoder(
        self,
        data: Cow<'a, [u8]>,
        preferred: &[PixelDescriptor],
    ) -> Result<PngAnimationFrameDecoder, At<PngError>> {
        // Reject animation when policy forbids it
        if let Some(ref policy) = self.policy
            && !policy.resolve_animation(true)
        {
            return Err(at!(PngError::InvalidInput(
                "animation rejected by decode policy".into()
            )));
        }
        // Check input size limit
        let effective_limits = self.limits.as_ref().unwrap_or(&self.config.limits);
        effective_limits
            .check_input_size(data.len() as u64)
            .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
        PngAnimationFrameDecoder::new(
            &data,
            &self.config,
            self.stop,
            self.policy.as_ref(),
            preferred,
            self.start_frame_index,
        )
    }

    fn push_decoder(
        self,
        data: Cow<'a, [u8]>,
        sink: &mut dyn zencodec::decode::DecodeRowSink,
        preferred: &[PixelDescriptor],
    ) -> Result<OutputInfo, At<PngError>> {
        push_decoder_native(self, data, sink, preferred)
    }
}

// ── PngDecoder ───────────────────────────────────────────────────────

/// Single-image PNG decoder.
pub struct PngDecoder<'a> {
    config: PngDecoderConfig,
    stop: Option<zencodec::StopToken>,
    limits: Option<ResourceLimits>,
    policy: Option<zencodec::decode::DecodePolicy>,
    data: Cow<'a, [u8]>,
    preferred: Vec<PixelDescriptor>,
}

impl PngDecoder<'_> {
    fn effective_config(&self) -> PngDecodeConfig {
        let limits = self.limits.as_ref().unwrap_or(&self.config.limits);
        let config = PngDecodeConfig {
            max_pixels: limits.max_pixels,
            max_memory_bytes: limits.max_memory_bytes,
            skip_decompression_checksum: true,
            skip_critical_chunk_crc: true,
        };
        apply_decode_policy(config, self.policy.as_ref())
    }
}

impl zencodec::decode::Decode for PngDecoder<'_> {
    type Error = At<PngError>;

    fn decode(self) -> Result<DecodeOutput, At<PngError>> {
        let cancel: &dyn enough::Stop = match self.stop {
            Some(ref s) => s as &dyn enough::Stop,
            None => &enough::Unstoppable,
        };
        cancel.check().map_err(|e| at!(PngError::from(e)))?;
        // Check progressive policy before decoding
        check_progressive_policy(&self.data, self.policy.as_ref())?;
        // Check input size limit
        let effective_limits = self.limits.as_ref().unwrap_or(&self.config.limits);
        effective_limits
            .check_input_size(self.data.len() as u64)
            .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
        // Check max_width / max_height before decoding
        let probe_info = crate::decode::probe(&self.data)?;
        effective_limits
            .check_dimensions(probe_info.width, probe_info.height)
            .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
        let png_config = self.effective_config();
        let result = crate::decode::decode(&self.data, &png_config, cancel)?;
        // Build the probe from decoder state instead of a second full-file
        // chunk scan. Every PngProbe field is already present in PngInfo
        // (palette_size, compressed_data_size, creating_tool, dimensions,
        // color type, bit depth, alpha, interlace, sequence). The previous
        // `crate::detect::probe(&self.data)` call re-parsed the entire file.
        // Other detect::probe call sites (probe-only paths) are untouched.
        let probe = crate::detect::PngProbe::from_info(&result.info);
        let mut info = convert_info(&result.info);
        apply_policy_to_info(&mut info, self.policy.as_ref());
        let pixels = if self.preferred.is_empty() {
            result.pixels
        } else {
            negotiate_and_convert(result.pixels, &self.preferred)
        };
        let output = DecodeOutput::new(pixels, info).with_source_encoding_details(probe);
        Ok(output)
    }
}

// ── Native push_decoder ─────────────────────────────────────────────

/// Determine the native output `PixelDescriptor` for a given PNG color
/// type, bit depth, and tRNS presence. Must match `build_pixel_data`.
fn native_output_descriptor(color_type: u8, bit_depth: u8, has_trns: bool) -> PixelDescriptor {
    match (color_type, bit_depth, has_trns) {
        (0, 16, false) => PixelDescriptor::GRAY16_SRGB,
        (0, 16, true) => GrayAlpha16::DESCRIPTOR, // GRAYA16
        (0, _, false) => PixelDescriptor::GRAY8_SRGB,
        (0, _, true) => PixelDescriptor::RGBA8_SRGB,
        (2, 16, false) => PixelDescriptor::RGB16_SRGB,
        (2, 16, true) => PixelDescriptor::RGBA16_SRGB,
        (2, 8, false) => PixelDescriptor::RGB8_SRGB,
        (2, 8, true) => PixelDescriptor::RGBA8_SRGB,
        (3, _, true) => PixelDescriptor::RGBA8_SRGB,
        (3, _, false) => PixelDescriptor::RGB8_SRGB,
        (4, 16, _) => GrayAlpha16::DESCRIPTOR, // GRAYA16
        (4, 8, _) => PixelDescriptor::RGBA8_SRGB,
        (6, 16, _) => PixelDescriptor::RGBA16_SRGB,
        (6, 8, _) => PixelDescriptor::RGBA8_SRGB,
        _ => PixelDescriptor::RGBA8_SRGB, // fallback
    }
}

/// Native row-streaming push decoder. Decodes PNG rows one at a time
/// directly into the sink buffer, avoiding the 2x peak memory of the
/// full-decode-then-copy fallback.
///
/// Falls back to `helpers::copy_decode_to_sink` for interlaced PNGs
/// (Adam7 scatters pixels across 7 passes and requires a full canvas).
fn push_decoder_native<'a>(
    job: PngDecodeJob,
    data: Cow<'a, [u8]>,
    sink: &mut dyn zencodec::decode::DecodeRowSink,
    preferred: &[PixelDescriptor],
) -> Result<OutputInfo, At<PngError>> {
    use crate::decoder::postprocess::post_process_row;
    use crate::decoder::row::RowDecoder;

    let wrap_sink = |e: zencodec::decode::SinkError| -> At<PngError> {
        at!(PngError::InvalidInput(alloc::format!("sink error: {e}")))
    };

    // Check progressive policy before decoding
    check_progressive_policy(&data, job.policy.as_ref())?;

    // Check input size limit
    let effective_limits = job.limits.as_ref().unwrap_or(&job.config.limits);
    effective_limits
        .check_input_size(data.len() as u64)
        .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;

    // Check for interlacing — fall back to full decode for Adam7
    if data.len() >= 29 && data[..8] == crate::chunk::PNG_SIGNATURE && data[28] == 1 {
        return zencodec::helpers::copy_decode_to_sink(job, data, sink, preferred, |e| {
            at!(PngError::InvalidInput(alloc::format!("sink error: {e}")))
        });
    }

    // Build effective config (limits + policy)
    let limits = job.limits.as_ref().unwrap_or(&job.config.limits);
    let png_config = PngDecodeConfig {
        max_pixels: limits.max_pixels,
        max_memory_bytes: limits.max_memory_bytes,
        skip_decompression_checksum: true,
        skip_critical_chunk_crc: true,
    };
    let png_config = apply_decode_policy(png_config, job.policy.as_ref());

    let cancel: &dyn enough::Stop = match &job.stop {
        Some(s) => s,
        None => &enough::Unstoppable,
    };
    cancel.check().map_err(|e| at!(PngError::from(e)))?;

    let mut reader = RowDecoder::new(data, &png_config)?;
    let ihdr = *reader.ihdr();
    let has_trns = reader.ancillary().trns.is_some();

    let w = ihdr.width;
    let h = ihdr.height;

    // Check max_width / max_height before allocating pixel buffers
    limits
        .check_dimensions(w, h)
        .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;

    let descriptor = native_output_descriptor(ihdr.color_type, ihdr.bit_depth, has_trns);

    sink.begin(w, h, descriptor).map_err(wrap_sink)?;

    // Passthrough fast path: RGB8 or RGBA8 without tRNS — raw unfiltered
    // data IS the output pixels. Decode directly into the sink buffer.
    let is_passthrough =
        !has_trns && ihdr.bit_depth == 8 && (ihdr.color_type == 6 || ihdr.color_type == 2);

    if is_passthrough {
        let raw_row_bytes = ihdr.raw_row_bytes()?;

        // Request the full sink buffer up front so we can use split_at_mut
        // for zero-copy prev-row references during unfiltering.
        let mut dst = sink
            .provide_next_buffer(0, h, w, descriptor)
            .map_err(wrap_sink)?;

        // Row 0: prev is zeros
        if h > 0 {
            let zeros = alloc::vec![0u8; raw_row_bytes];
            let row_slice = dst.row_mut(0);
            match reader.next_raw_row_direct(&mut row_slice[..raw_row_bytes], &zeros) {
                Some(Ok(())) => {}
                Some(Err(e)) => return Err(e),
                None => {
                    return Err(at!(PngError::Decode(
                        "unexpected end of image data at row 0".into()
                    )));
                }
            }
            cancel.check().map_err(|e| at!(PngError::from(e)))?;
        }

        // Rows 1..h: prev is the previous row in the sink buffer.
        // We cannot borrow two rows from PixelSliceMut simultaneously via
        // row_mut, so copy the previous row into a temp buffer for unfilter.
        let mut prev_buf = alloc::vec![0u8; raw_row_bytes];
        for y in 1..h {
            // Save previous row for unfilter reference
            prev_buf.copy_from_slice(&dst.row_mut(y - 1)[..raw_row_bytes]);
            let row_slice = dst.row_mut(y);
            match reader.next_raw_row_direct(&mut row_slice[..raw_row_bytes], &prev_buf) {
                Some(Ok(())) => {}
                Some(Err(e)) => return Err(e),
                None => {
                    return Err(at!(PngError::Decode(alloc::format!(
                        "unexpected end of image data at row {y}"
                    ))));
                }
            }
            cancel.check().map_err(|e| at!(PngError::from(e)))?;
        }
        drop(dst);
    } else {
        // General path: post-process each raw row, then write to sink.
        let out_bpp = descriptor.bytes_per_pixel();
        let out_row_bytes = w as usize * out_bpp;
        let mut row_buf = Vec::new();
        let mut raw_copy = alloc::vec![0u8; ihdr.raw_row_bytes()?];

        let mut dst = sink
            .provide_next_buffer(0, h, w, descriptor)
            .map_err(wrap_sink)?;

        let mut y = 0u32;
        while let Some(result) = reader.next_raw_row() {
            let raw = result?;
            cancel.check().map_err(|e| at!(PngError::from(e)))?;

            // Copy raw row data so the borrow on reader is released (NLL),
            // allowing reader.ancillary() below.
            raw_copy[..raw.len()].copy_from_slice(raw);

            post_process_row(
                &raw_copy[..ihdr.raw_row_bytes()?],
                &ihdr,
                reader.ancillary(),
                &mut row_buf,
            );

            let sink_row = dst.row_mut(y);
            let copy_len = out_row_bytes.min(row_buf.len()).min(sink_row.len());
            sink_row[..copy_len].copy_from_slice(&row_buf[..copy_len]);
            y += 1;
        }
        drop(dst);
    }

    reader.finish_metadata();
    sink.finish().map_err(wrap_sink)?;

    let has_alpha = descriptor.has_alpha();
    Ok(OutputInfo::full_decode(w, h, descriptor).with_alpha(has_alpha))
}

// ── PngStreamingDecoder ──────────────────────────────────────────────

/// Pull-based streaming PNG decoder implementing [`StreamingDecode`](zencodec::decode::StreamingDecode).
///
/// Yields one post-processed row per `next_batch()` call, backed by
/// [`RowDecoder`](crate::decoder::row::RowDecoder). Only non-interlaced
/// PNGs are supported; interlaced images are rejected at construction.
pub struct PngStreamingDecoder<'a> {
    reader: crate::decoder::row::RowDecoder<'a>,
    info: ImageInfo,
    descriptor: PixelDescriptor,
    /// Post-processed row buffer, reused across calls.
    row_buf: Vec<u8>,
    /// Raw row copy buffer (needed to release borrow on reader before
    /// calling `reader.ancillary()` for post-processing).
    raw_copy: Vec<u8>,
    /// Current row index (y coordinate).
    y: u32,
    width: u32,
    height: u32,
    /// True when the raw format is passthrough (no post-processing needed).
    is_passthrough: bool,
    /// Cooperative cancellation token, checked per-row in `next_batch()`.
    stop: Option<zencodec::StopToken>,
}

impl<'a> PngStreamingDecoder<'a> {
    fn new(
        data: Cow<'a, [u8]>,
        config: &PngDecoderConfig,
        stop: Option<zencodec::StopToken>,
        limits: Option<&ResourceLimits>,
        policy: Option<&zencodec::decode::DecodePolicy>,
        _preferred: &[PixelDescriptor],
    ) -> Result<Self, At<PngError>> {
        // Check progressive policy before the structural interlace rejection
        check_progressive_policy(&data, policy)?;

        // Reject interlaced PNGs — Adam7 requires full-canvas buffering
        if data.len() >= 29 && data[..8] == crate::chunk::PNG_SIGNATURE && data[28] == 1 {
            return Err(at!(PngError::from(
                zencodec::UnsupportedOperation::RowLevelDecode
            )));
        }

        let cancel: &dyn enough::Stop = match &stop {
            Some(s) => s,
            None => &enough::Unstoppable,
        };
        cancel.check().map_err(|e| at!(PngError::from(e)))?;

        let effective_limits = limits.unwrap_or(&config.limits);
        // Check input size limit
        effective_limits
            .check_input_size(data.len() as u64)
            .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;
        let png_config = PngDecodeConfig {
            max_pixels: effective_limits.max_pixels,
            max_memory_bytes: effective_limits.max_memory_bytes,
            skip_decompression_checksum: true,
            skip_critical_chunk_crc: true,
        };
        let png_config = apply_decode_policy(png_config, policy);

        // Probe before moving data into RowDecoder (probe only needs &[u8])
        let probe_info = crate::decode::probe(&data)?;
        let mut info = convert_info(&probe_info);
        apply_policy_to_info(&mut info, policy);

        let reader = crate::decoder::row::RowDecoder::new(data, &png_config)?;
        let ihdr = *reader.ihdr();
        let has_trns = reader.ancillary().trns.is_some();

        let w = ihdr.width;
        let h = ihdr.height;

        // Check max_width / max_height before allocating pixel buffers
        effective_limits
            .check_dimensions(w, h)
            .map_err(|e| at!(PngError::LimitExceeded(alloc::format!("{e}"))))?;

        let descriptor = native_output_descriptor(ihdr.color_type, ihdr.bit_depth, has_trns);

        let is_passthrough =
            !has_trns && ihdr.bit_depth == 8 && (ihdr.color_type == 6 || ihdr.color_type == 2);

        let raw_row_bytes = ihdr.raw_row_bytes()?;
        let out_row_bytes = w as usize * descriptor.bytes_per_pixel();

        Ok(Self {
            reader,
            info,
            descriptor,
            row_buf: alloc::vec![0u8; out_row_bytes],
            raw_copy: alloc::vec![0u8; raw_row_bytes],
            y: 0,
            width: w,
            height: h,
            is_passthrough,
            stop,
        })
    }
}

impl zencodec::decode::StreamingDecode for PngStreamingDecoder<'_> {
    type Error = At<PngError>;

    fn next_batch(&mut self) -> Result<Option<(u32, PixelSlice<'_>)>, At<PngError>> {
        use crate::decoder::postprocess::post_process_row;

        if self.y >= self.height {
            return Ok(None);
        }

        // Check cooperative cancellation per-row
        if let Some(ref stop) = self.stop {
            let cancel: &dyn enough::Stop = stop;
            cancel.check().map_err(|e| at!(PngError::from(e)))?;
        }

        let raw = match self.reader.next_raw_row() {
            Some(Ok(row)) => row,
            Some(Err(e)) => return Err(e),
            None => return Ok(None),
        };

        let y = self.y;
        self.y += 1;

        if self.is_passthrough {
            // Raw unfiltered data IS the output — copy into row_buf
            let copy_len = raw.len().min(self.row_buf.len());
            self.row_buf[..copy_len].copy_from_slice(&raw[..copy_len]);
        } else {
            // Need post-processing: copy raw to release borrow on reader
            self.raw_copy[..raw.len()].copy_from_slice(raw);
            let raw_len = self.reader.ihdr().raw_row_bytes()?;

            // Post-process expands/converts the raw row into row_buf
            let mut tmp = core::mem::take(&mut self.row_buf);
            post_process_row(
                &self.raw_copy[..raw_len],
                self.reader.ihdr(),
                self.reader.ancillary(),
                &mut tmp,
            );
            self.row_buf = tmp;
        }

        let stride = self.width as usize * self.descriptor.bytes_per_pixel();
        let slice = PixelSlice::new(
            &self.row_buf[..stride],
            self.width,
            1,
            stride,
            self.descriptor,
        )
        .map_err(|e| at!(PngError::InvalidInput(alloc::format!("pixel slice: {e}"))))?;

        Ok(Some((y, slice)))
    }

    fn info(&self) -> &ImageInfo {
        &self.info
    }
}

// ── PngAnimationFrameDecoder ──────────────────────────────────────────────

/// APNG frame-by-frame decoder implementing [`AnimationFrameDecoder`](zencodec::decode::AnimationFrameDecoder).
///
/// Yields composited full-canvas frames. The returned [`AnimationFrame`] borrows
/// the decoder's internal canvas buffer; calling `render_next_frame()` again
/// invalidates the previous borrow.
pub struct PngAnimationFrameDecoder {
    /// Owned copy of the PNG file data.
    file_data: Vec<u8>,
    /// Image info for all frames.
    info: ImageInfo,
    /// Saved decoder state for O(1) resumption between frames.
    decoder_state: crate::decoder::apng::ApngDecoderState,
    /// Preferred output pixel formats for format negotiation.
    preferred: Vec<PixelDescriptor>,
    /// Internal canvas buffer holding the last rendered frame's pixels.
    canvas: Option<PixelBuffer>,
    /// Cooperative cancellation token from the decode job.
    stop: Option<zencodec::StopToken>,
    /// First frame index to yield (skip earlier frames, but still decode them
    /// because APNG compositing depends on prior frames).
    start_frame_index: u32,
    /// Number of frames decoded so far (used to track position vs `start_frame_index`).
    frames_decoded: u32,
}

impl PngAnimationFrameDecoder {
    fn new(
        data: &[u8],
        config: &PngDecoderConfig,
        stop: Option<zencodec::StopToken>,
        policy: Option<&zencodec::decode::DecodePolicy>,
        preferred: &[PixelDescriptor],
        start_frame_index: u32,
    ) -> Result<Self, At<PngError>> {
        let probe_info = crate::decode::probe(data)?;
        let mut image_info = convert_info(&probe_info);
        apply_policy_to_info(&mut image_info, policy);

        let decode_config = PngDecodeConfig {
            max_pixels: config.limits.max_pixels,
            max_memory_bytes: config.limits.max_memory_bytes,
            skip_decompression_checksum: true,
            skip_critical_chunk_crc: true,
        };

        // Create ApngDecoder once and save its state for O(1) resumption.
        let decoder = crate::decoder::apng::ApngDecoder::new(data, &decode_config)?;
        let decoder_state = decoder.save_state();

        Ok(Self {
            file_data: data.to_vec(),
            info: image_info,
            decoder_state,
            preferred: preferred.to_vec(),
            canvas: None,
            stop,
            start_frame_index,
            frames_decoded: 0,
        })
    }
}

impl zencodec::decode::AnimationFrameDecoder for PngAnimationFrameDecoder {
    type Error = At<PngError>;

    fn wrap_sink_error(err: zencodec::decode::SinkError) -> At<PngError> {
        at!(PngError::InvalidInput(alloc::format!("sink error: {err}")))
    }

    fn info(&self) -> &ImageInfo {
        &self.info
    }

    fn frame_count(&self) -> Option<u32> {
        Some(self.decoder_state.num_frames)
    }

    fn loop_count(&self) -> Option<u32> {
        Some(self.decoder_state.num_plays)
    }

    fn render_next_frame_to_sink(
        &mut self,
        stop: Option<&dyn enough::Stop>,
        sink: &mut dyn zencodec::decode::DecodeRowSink,
    ) -> Result<Option<OutputInfo>, At<PngError>> {
        zencodec::helpers::copy_frame_to_sink(self, stop, sink)
    }

    fn render_next_frame(
        &mut self,
        stop: Option<&dyn enough::Stop>,
    ) -> Result<Option<AnimationFrame<'_>>, At<PngError>> {
        // Use per-call stop token, fall back to stored job-level token, then unstoppable.
        let cancel: &dyn enough::Stop = if let Some(s) = stop {
            s
        } else if let Some(ref s) = self.stop {
            s as &dyn enough::Stop
        } else {
            &enough::Unstoppable
        };
        loop {
            // Restore decoder from saved state (O(1), no re-scanning)
            let mut decoder = crate::decoder::apng::ApngDecoder::from_state(
                &self.file_data,
                self.decoder_state.clone(),
            );

            let raw = match decoder.next_frame(cancel)? {
                Some(f) => f,
                None => return Ok(None),
            };

            // Save updated state (chunk_pos / current_frame advanced)
            let idx = self.decoder_state.current_frame;
            self.decoder_state = decoder.save_state();
            self.frames_decoded += 1;

            // Skip frames before start_frame_index. We must still decode them
            // (not skip) because APNG compositing depends on prior frame disposal
            // and blending, but we don't yield them to the caller.
            if idx < self.start_frame_index {
                continue;
            }

            let delay_ms = raw.fctl.delay_ms();

            // Apply format negotiation to frame pixels if preferred formats specified
            let pixels = if self.preferred.is_empty() {
                raw.pixels
            } else {
                negotiate_and_convert(raw.pixels, &self.preferred)
            };

            // Store the rendered frame in the internal canvas buffer
            self.canvas = Some(pixels);

            // Borrow from the canvas we just stored
            let canvas = self.canvas.as_ref().unwrap();
            let pixel_slice = canvas.as_slice();
            let frame = AnimationFrame::new(pixel_slice, delay_ms, idx);

            return Ok(Some(frame));
        }
    }
}

// ── Pixel format negotiation ─────────────────────────────────────────

use rgb::{Gray, Rgb, Rgba};
use zenpixels::{ChannelLayout, ChannelType, GrayAlpha16, PixelBuffer};
use zenpixels_convert::{PixelBufferConvertExt as _, PixelBufferConvertTypedExt as _};

/// Negotiate output format from the caller's preference list and convert.
///
/// Uses `negotiate_pixel_format` to pick the best match, then converts
/// if the native format doesn't already match.
///
/// When the source has no alpha channel but the target layout does, the
/// synthesized alpha bytes are all 0xFF — promote the output descriptor's
/// `AlphaMode` from `Straight` to `Opaque` so callers can skip alpha
/// compositing / premultiplication work downstream. (We don't scan pixels
/// to detect the all-opaque case for sources that *do* carry alpha.)
fn negotiate_and_convert(pixels: PixelBuffer, preferred: &[PixelDescriptor]) -> PixelBuffer {
    let native_desc = pixels.descriptor();
    let target = zencodec::decode::negotiate_pixel_format(preferred, DECODE_DESCRIPTORS);

    // Already in the target format — no conversion needed
    let Some(target) = target else {
        return pixels;
    };
    if native_desc == target {
        return pixels;
    }

    let source_had_no_alpha = native_desc.alpha().is_none();

    // Use convert_to() for all format conversions (8/16/F32, all layouts)
    let converted = match pixels.convert_to(target) {
        Ok(c) => c,
        Err(_) => return pixels, // Fallback to native format if conversion unavailable
    };

    // Promote Straight → Opaque when source contributed no alpha information.
    if source_had_no_alpha
        && matches!(
            converted.descriptor().alpha(),
            Some(zenpixels::AlphaMode::Straight)
        )
    {
        let opaque_desc = converted
            .descriptor()
            .with_alpha(Some(zenpixels::AlphaMode::Opaque));
        return converted.with_descriptor(opaque_desc);
    }
    converted
}

// ── Pixel conversion helpers ─────────────────────────────────────────
//
// PNG decoder produces Rgb8, Rgba8, Gray8, Rgb16, Rgba16, Gray16,
// GrayAlpha16. These helpers convert to any requested target format.

/// Convert native PNG pixel data to Rgb8. Delegates to `PixelBuffer::to_rgb8()`.
#[allow(unused_imports)]
use zenpixels_convert::PixelBufferConvertTypedExt as _;
fn to_rgb8(pixels: PixelBuffer) -> imgref::ImgVec<Rgb<u8>> {
    let converted = pixels.to_rgb8();
    let w = converted.width() as usize;
    let h = converted.height() as usize;
    let img = converted.as_imgref();
    let buf: Vec<Rgb<u8>> = img.pixels().collect();
    imgref::ImgVec::new(buf, w, h)
}

/// Convert native PNG pixel data to Rgba8. Delegates to `PixelBuffer::to_rgba8()`.
fn to_rgba8(pixels: PixelBuffer) -> imgref::ImgVec<Rgba<u8>> {
    let converted = pixels.to_rgba8();
    let w = converted.width() as usize;
    let h = converted.height() as usize;
    let img = converted.as_imgref();
    let buf: Vec<Rgba<u8>> = img.pixels().collect();
    imgref::ImgVec::new(buf, w, h)
}

/// Convert native PNG pixel data to Gray8. Delegates to `PixelBuffer::to_gray8()`.
fn to_gray8(pixels: PixelBuffer) -> imgref::ImgVec<Gray<u8>> {
    let converted = pixels.to_gray8();
    let w = converted.width() as usize;
    let h = converted.height() as usize;
    let img = converted.as_imgref();
    let buf: Vec<Gray<u8>> = img.pixels().collect();
    imgref::ImgVec::new(buf, w, h)
}

/// Convert native PNG pixel data to Bgra8. Delegates to `PixelBuffer::to_bgra8()`.
fn to_bgra8(pixels: PixelBuffer) -> imgref::ImgVec<rgb::alt::BGRA<u8>> {
    let converted = pixels.to_bgra8();
    let w = converted.width() as usize;
    let h = converted.height() as usize;
    let img = converted.as_imgref();
    let buf: Vec<rgb::alt::BGRA<u8>> = img.pixels().collect();
    imgref::ImgVec::new(buf, w, h)
}

// ── Helpers ──────────────────────────────────────────────────────────

fn convert_info(info: &crate::decode::PngInfo) -> ImageInfo {
    let mut zi = ImageInfo::new(info.width, info.height, ImageFormat::Png);
    if info.has_alpha {
        zi = zi.with_alpha(true);
    }
    zi = zi.with_sequence(info.sequence.clone());
    zi = zi.with_bit_depth(info.bit_depth);
    // PNG color_type → channel count: 0=gray→1, 2=rgb→3, 3=indexed→1, 4=gray+alpha→2, 6=rgba→4
    let channel_count = match info.color_type {
        0 => 1,
        2 => 3,
        3 => 1,
        4 => 2,
        6 => 4,
        _ => 1,
    };
    zi = zi.with_channel_count(channel_count);
    // Map pHYs data to resolution
    if let (Some(ppx), Some(ppy)) = (info.pixels_per_unit_x, info.pixels_per_unit_y) {
        let unit = match info.phys_unit {
            Some(crate::decode::PhysUnit::Meter) => zencodec::ResolutionUnit::Meter,
            _ => zencodec::ResolutionUnit::Unknown,
        };
        zi = zi.with_resolution(zencodec::Resolution {
            x: ppx as f64,
            y: ppy as f64,
            unit,
        });
    }
    if let Some(ref icc) = info.icc_profile {
        zi = zi.with_icc_profile(icc.clone());
    }
    if let Some(ref exif) = info.exif {
        zi = zi.with_exif(exif.clone());
    }
    if let Some(ref xmp) = info.xmp {
        zi = zi.with_xmp(xmp.clone());
    }
    if let Some(cicp) = info.cicp {
        zi = zi.with_cicp(cicp);
        zi = zi.with_color_authority(zencodec::ColorAuthority::Cicp);
    }
    if let Some(clli) = info.content_light_level {
        zi = zi.with_content_light_level(clli);
    }
    if let Some(mdcv) = info.mastering_display {
        zi = zi.with_mastering_display(mdcv);
    }
    zi = zi.with_progressive(info.interlaced);
    zi
}

/// Apply encode policy to filter metadata fields.
///
/// Returns a new `Metadata` with fields stripped according to the policy,
/// or `None` if no metadata was provided.
fn apply_encode_policy(
    metadata: Option<&Metadata>,
    policy: Option<&zencodec::encode::EncodePolicy>,
) -> Option<Metadata> {
    let meta = metadata?;
    let Some(policy) = policy else {
        return Some(meta.clone());
    };
    let mut filtered = meta.clone();
    if policy.embed_icc == Some(false) {
        filtered.icc_profile = None;
    }
    if policy.embed_exif == Some(false) {
        filtered.exif = None;
    }
    if policy.embed_xmp == Some(false) {
        filtered.xmp = None;
    }
    Some(filtered)
}

/// Apply decode policy to control metadata extraction and strictness.
///
/// Returns adjusted `PngDecodeConfig` based on the policy.
fn apply_decode_policy(
    mut config: PngDecodeConfig,
    policy: Option<&zencodec::decode::DecodePolicy>,
) -> PngDecodeConfig {
    let Some(policy) = policy else {
        return config;
    };
    // Strict policy: enable CRC and Adler-32 verification
    if policy.strict == Some(true) {
        config.skip_critical_chunk_crc = false;
        config.skip_decompression_checksum = false;
    }
    config
}

/// Strip metadata fields from `ImageInfo` according to the decode policy.
///
/// Called after building `ImageInfo` from decoded data. When a policy flag
/// suppresses a metadata category, the corresponding field is cleared.
fn apply_policy_to_info(info: &mut ImageInfo, policy: Option<&zencodec::decode::DecodePolicy>) {
    let Some(policy) = policy else {
        return;
    };
    if !policy.resolve_icc(true) {
        info.source_color.icc_profile = None;
    }
    if !policy.resolve_exif(true) {
        info.embedded_metadata.exif = None;
    }
    if !policy.resolve_xmp(true) {
        info.embedded_metadata.xmp = None;
    }
}

/// Check whether an interlaced (progressive) PNG should be rejected by policy.
///
/// Returns `Err` if `data` contains an Adam7-interlaced PNG and policy
/// forbids progressive images.
fn check_progressive_policy(
    data: &[u8],
    policy: Option<&zencodec::decode::DecodePolicy>,
) -> Result<(), At<PngError>> {
    let Some(policy) = policy else {
        return Ok(());
    };
    if policy.resolve_progressive(true) {
        return Ok(());
    }
    // IHDR interlace byte is at offset 28 in a valid PNG file
    if data.len() >= 29 && data[..8] == crate::chunk::PNG_SIGNATURE && data[28] == 1 {
        return Err(at!(PngError::InvalidInput(
            "interlaced (progressive) PNG rejected by decode policy".into()
        )));
    }
    Ok(())
}

/// Get contiguous pixel bytes from a PixelSlice, borrowing when possible.
///
/// Returns `Cow::Borrowed` when rows are tightly packed (zero-copy),
/// `Cow::Owned` when stride padding must be stripped.
fn contiguous_bytes<'a>(pixels: &'a PixelSlice<'a>) -> alloc::borrow::Cow<'a, [u8]> {
    pixels.contiguous_bytes()
}

/// Map a PixelFormat to the corresponding PNG color type and bit depth.
fn pixel_format_to_png(
    format: zenpixels::PixelFormat,
) -> Option<(crate::encode::ColorType, crate::encode::BitDepth)> {
    use zenpixels::PixelFormat;
    match format {
        PixelFormat::Rgb8 => Some((
            crate::encode::ColorType::Rgb,
            crate::encode::BitDepth::Eight,
        )),
        PixelFormat::Rgba8 => Some((
            crate::encode::ColorType::Rgba,
            crate::encode::BitDepth::Eight,
        )),
        PixelFormat::Gray8 => Some((
            crate::encode::ColorType::Grayscale,
            crate::encode::BitDepth::Eight,
        )),
        PixelFormat::Rgb16 => Some((
            crate::encode::ColorType::Rgb,
            crate::encode::BitDepth::Sixteen,
        )),
        PixelFormat::Rgba16 => Some((
            crate::encode::ColorType::Rgba,
            crate::encode::BitDepth::Sixteen,
        )),
        PixelFormat::Gray16 => Some((
            crate::encode::ColorType::Grayscale,
            crate::encode::BitDepth::Sixteen,
        )),
        // Float and BGRA are converted to 8-bit on the fly
        PixelFormat::RgbF32 => Some((
            crate::encode::ColorType::Rgb,
            crate::encode::BitDepth::Eight,
        )),
        PixelFormat::RgbaF32 => Some((
            crate::encode::ColorType::Rgba,
            crate::encode::BitDepth::Eight,
        )),
        PixelFormat::GrayF32 => Some((
            crate::encode::ColorType::Grayscale,
            crate::encode::BitDepth::Eight,
        )),
        PixelFormat::Bgra8 => Some((
            crate::encode::ColorType::Rgba,
            crate::encode::BitDepth::Eight,
        )),
        // Rgbx8 and Bgrx8 are 4-byte layouts with undefined padding; emit 3-channel RGB.
        PixelFormat::Rgbx8 | PixelFormat::Bgrx8 => Some((
            crate::encode::ColorType::Rgb,
            crate::encode::BitDepth::Eight,
        )),
        _ => None,
    }
}

impl TrueStreamingState {
    /// Initialize true streaming state: write PNG signature, IHDR, and metadata,
    /// then start the IDAT chunk with a zlib header.
    #[allow(clippy::too_many_arguments)]
    fn new(
        width: u32,
        height: u32,
        color_type: crate::encode::ColorType,
        bit_depth: crate::encode::BitDepth,
        row_bytes: usize,
        metadata: Option<&Metadata>,
        policy: Option<&zencodec::encode::EncodePolicy>,
        config: &EncodeConfig,
    ) -> Result<Self, At<PngError>> {
        use crate::chunk::{PNG_SIGNATURE, write::write_chunk};
        use crate::encoder::{PngWriteMetadata, metadata_size_estimate, write_all_metadata};

        let filtered_row = row_bytes + 1; // filter byte + row data
        let total_filtered = filtered_row * height as usize;
        let num_blocks = if total_filtered == 0 {
            1
        } else {
            total_filtered.div_ceil(65535)
        };
        let idat_data_len = 2 + 5 * num_blocks + total_filtered + 4; // zlib header + blocks + adler

        // PNG chunk lengths are u32. Reject images whose stored IDAT exceeds this.
        if idat_data_len > u32::MAX as usize {
            return Err(at!(PngError::LimitExceeded(
                "image too large for single IDAT chunk at effort 0".into(),
            )));
        }

        // Build metadata
        let effective_meta = apply_encode_policy(metadata, policy);
        let mut write_meta = PngWriteMetadata::from_metadata(effective_meta.as_ref());
        write_meta.source_gamma = config.source_gamma;
        write_meta.srgb_intent = config.srgb_intent;
        write_meta.chromaticities = config.chromaticities;
        write_meta.pixels_per_unit_x = config.pixels_per_unit_x;
        write_meta.pixels_per_unit_y = config.pixels_per_unit_y;
        write_meta.phys_unit = config.phys_unit;
        write_meta.text_chunks.clone_from(&config.text_chunks);
        write_meta.last_modified = config.last_modified;

        let est = 8 + 25 + (12 + idat_data_len) + 12 + metadata_size_estimate(&write_meta);
        let mut output = Vec::with_capacity(est);

        // PNG signature
        output.extend_from_slice(&PNG_SIGNATURE);

        // IHDR
        let mut ihdr = [0u8; 13];
        ihdr[0..4].copy_from_slice(&width.to_be_bytes());
        ihdr[4..8].copy_from_slice(&height.to_be_bytes());
        ihdr[8] = match bit_depth {
            crate::encode::BitDepth::Eight => 8,
            crate::encode::BitDepth::Sixteen => 16,
        };
        ihdr[9] = match color_type {
            crate::encode::ColorType::Grayscale => 0,
            crate::encode::ColorType::Rgb => 2,
            crate::encode::ColorType::GrayscaleAlpha => 4,
            crate::encode::ColorType::Rgba => 6,
        };
        write_chunk(&mut output, b"IHDR", &ihdr);

        // Metadata chunks
        write_all_metadata(&mut output, &write_meta)?;

        // Start IDAT chunk: length (placeholder) + "IDAT"
        let idat_len_pos = output.len();
        output.extend_from_slice(&(idat_data_len as u32).to_be_bytes());
        output.extend_from_slice(b"IDAT");

        // Zlib header (no compression)
        output.extend_from_slice(&[0x78, 0x01]);

        Ok(Self {
            output,
            convert_buf: vec![0u8; row_bytes],
            row_bytes,
            rows_pushed: 0,
            adler: 1,
            idat_len_pos,
            block_remaining: 0,
            filtered_remaining: total_filtered,
        })
    }

    /// Push one row from `self.convert_buf` (already written by caller).
    /// Avoids passing a borrow of self's own field to push_raw_row.
    fn push_converted_row(&mut self) {
        // Write filter byte (0x00 = None).
        if self.block_remaining == 0 {
            let block_len = self.filtered_remaining.min(65535);
            let is_final = block_len >= self.filtered_remaining;
            write_stored_block_header(&mut self.output, block_len, is_final);
            self.block_remaining = block_len;
        }
        self.output.push(0u8);
        self.block_remaining -= 1;
        self.filtered_remaining -= 1;

        // Write row data from convert_buf, splitting across blocks.
        let mut pos = 0;
        let row_bytes = self.row_bytes;
        while pos < row_bytes {
            if self.block_remaining == 0 {
                let block_len = self.filtered_remaining.min(65535);
                let is_final = block_len >= self.filtered_remaining;
                write_stored_block_header(&mut self.output, block_len, is_final);
                self.block_remaining = block_len;
            }
            let n = (row_bytes - pos).min(self.block_remaining);
            self.output
                .extend_from_slice(&self.convert_buf[pos..pos + n]);
            pos += n;
            self.block_remaining -= n;
            self.filtered_remaining -= n;
        }

        // Adler-32: filter byte (0x00) then row data.
        let s1 = self.adler & 0xFFFF;
        let s2 = ((self.adler >> 16) + s1) % 65521;
        self.adler = (s2 << 16) | s1;
        self.adler = zenflate::adler32(self.adler, &self.convert_buf[..row_bytes]);

        self.rows_pushed += 1;
    }

    /// Push one row of converted pixel data (already in PNG byte order).
    /// Writes filter byte + row data as stored DEFLATE blocks.
    fn push_raw_row(&mut self, row: &[u8]) {
        debug_assert_eq!(row.len(), self.row_bytes);

        // Write filter byte (0x00 = None) — effort 0 always uses None filter.
        if self.block_remaining == 0 {
            let block_len = self.filtered_remaining.min(65535);
            let is_final = block_len >= self.filtered_remaining;
            write_stored_block_header(&mut self.output, block_len, is_final);
            self.block_remaining = block_len;
        }
        self.output.push(0u8);
        self.block_remaining -= 1;
        self.filtered_remaining -= 1;

        // Write row data, splitting across stored blocks as needed.
        let mut data = row;
        while !data.is_empty() {
            if self.block_remaining == 0 {
                let block_len = self.filtered_remaining.min(65535);
                let is_final = block_len >= self.filtered_remaining;
                write_stored_block_header(&mut self.output, block_len, is_final);
                self.block_remaining = block_len;
            }
            let n = data.len().min(self.block_remaining);
            self.output.extend_from_slice(&data[..n]);
            data = &data[n..];
            self.block_remaining -= n;
            self.filtered_remaining -= n;
        }

        // Update Adler-32: filter byte (0x00) then row data.
        // Manual update for the 0x00 filter byte: s2 += s1 (since byte is 0).
        let s1 = self.adler & 0xFFFF;
        let s2 = ((self.adler >> 16) + s1) % 65521;
        self.adler = (s2 << 16) | s1;
        self.adler = zenflate::adler32(self.adler, row);

        self.rows_pushed += 1;
    }

    /// Finalize the PNG: write Adler-32, backpatch IDAT length, CRC, IEND.
    fn finish(mut self) -> Vec<u8> {
        // Write Adler-32 checksum
        self.output.extend_from_slice(&self.adler.to_be_bytes());

        // CRC-32 over "IDAT" + data (starts 4 bytes after idat_len_pos)
        let crc_start = self.idat_len_pos + 4;
        let crc = zenflate::crc32(0, &self.output[crc_start..]);
        self.output.extend_from_slice(&crc.to_be_bytes());

        // IEND
        crate::chunk::write::write_chunk(&mut self.output, b"IEND", &[]);

        self.output
    }
}

impl PreFilteredState {
    /// Initialize pre-filtered streaming: build PNG preamble, allocate filter buffers.
    #[allow(clippy::too_many_arguments)]
    fn new(
        width: u32,
        height: u32,
        color_type: crate::encode::ColorType,
        bit_depth: crate::encode::BitDepth,
        row_bytes: usize,
        bpp: usize,
        metadata: Option<&Metadata>,
        policy: Option<&zencodec::encode::EncodePolicy>,
        config: &EncodeConfig,
    ) -> Result<Self, At<PngError>> {
        use crate::chunk::{PNG_SIGNATURE, write::write_chunk};
        use crate::encoder::{PngWriteMetadata, metadata_size_estimate, write_all_metadata};

        let effective_meta = apply_encode_policy(metadata, policy);
        let mut write_meta = PngWriteMetadata::from_metadata(effective_meta.as_ref());
        write_meta.source_gamma = config.source_gamma;
        write_meta.srgb_intent = config.srgb_intent;
        write_meta.chromaticities = config.chromaticities;
        write_meta.pixels_per_unit_x = config.pixels_per_unit_x;
        write_meta.pixels_per_unit_y = config.pixels_per_unit_y;
        write_meta.phys_unit = config.phys_unit;
        write_meta.text_chunks.clone_from(&config.text_chunks);
        write_meta.last_modified = config.last_modified;

        // Build preamble: PNG signature + IHDR + metadata
        let est = 8 + 25 + metadata_size_estimate(&write_meta);
        let mut preamble = Vec::with_capacity(est);
        preamble.extend_from_slice(&PNG_SIGNATURE);

        let mut ihdr = [0u8; 13];
        ihdr[0..4].copy_from_slice(&width.to_be_bytes());
        ihdr[4..8].copy_from_slice(&height.to_be_bytes());
        ihdr[8] = match bit_depth {
            crate::encode::BitDepth::Eight => 8,
            crate::encode::BitDepth::Sixteen => 16,
        };
        ihdr[9] = match color_type {
            crate::encode::ColorType::Grayscale => 0,
            crate::encode::ColorType::Rgb => 2,
            crate::encode::ColorType::GrayscaleAlpha => 4,
            crate::encode::ColorType::Rgba => 6,
        };
        write_chunk(&mut preamble, b"IHDR", &ihdr);
        write_all_metadata(&mut preamble, &write_meta)?;

        let filtered_row = row_bytes + 1;
        let total_filtered = filtered_row * height as usize;

        Ok(Self {
            preamble,
            filtered_data: Vec::with_capacity(total_filtered),
            prev_row: vec![0u8; row_bytes],
            convert_buf: vec![0u8; row_bytes],
            filter_type: 4, // Paeth
            bpp,
            row_bytes,
            rows_pushed: 0,
            color_type,
            bit_depth,
            zenflate_effort: 1, // Turbo
        })
    }

    /// Push one row of pixel data (already in PNG byte order). Applies Paeth filter.
    fn push_raw_row(&mut self, row: &[u8]) {
        debug_assert_eq!(row.len(), self.row_bytes);

        // Filter byte
        self.filtered_data.push(self.filter_type);

        // Apply Paeth filter
        let start = self.filtered_data.len();
        self.filtered_data.resize(start + self.row_bytes, 0);
        crate::encoder::filter::apply_filter(
            self.filter_type,
            row,
            &self.prev_row,
            self.bpp,
            &mut self.filtered_data[start..],
        );

        // Save current row as prev
        self.prev_row.copy_from_slice(row);
        self.rows_pushed += 1;
    }

    /// Push one row from `self.convert_buf`. Avoids borrow issues.
    fn push_converted_row(&mut self) {
        // Filter byte
        self.filtered_data.push(self.filter_type);

        // Apply Paeth filter from convert_buf
        let start = self.filtered_data.len();
        let row_bytes = self.row_bytes;
        self.filtered_data.resize(start + row_bytes, 0);
        crate::encoder::filter::apply_filter(
            self.filter_type,
            &self.convert_buf[..row_bytes],
            &self.prev_row,
            self.bpp,
            &mut self.filtered_data[start..],
        );

        // Save current row as prev
        self.prev_row
            .copy_from_slice(&self.convert_buf[..row_bytes]);
        self.rows_pushed += 1;
    }

    /// Compress pre-filtered data and assemble the final PNG.
    ///
    /// Peak memory during this call: ~2× image (filtered_data + compress_bound).
    /// After compression, filtered_data is dropped before assembling output.
    fn finish(self, cancel: &dyn enough::Stop) -> Result<Vec<u8>, At<PngError>> {
        use crate::chunk::write::write_chunk;

        // Destructure to allow dropping filtered_data independently.
        let Self {
            preamble,
            filtered_data,
            zenflate_effort,
            ..
        } = self;

        // Compress filtered data with zenflate.
        // Peak: filtered_data (~1×) + compressed_bound (~1×) = ~2× image.
        let level = zenflate::CompressionLevel::new(zenflate_effort);
        let mut compressor = zenflate::Compressor::new(level);
        let bound = zenflate::Compressor::zlib_compress_bound(filtered_data.len());
        let mut compressed = vec![0u8; bound];
        let len = compressor
            .zlib_compress(&filtered_data, &mut compressed, cancel)
            .map_err(|e| match e {
                zenflate::CompressionError::Stopped(reason) => PngError::Stopped(reason),
                other => PngError::InvalidInput(alloc::format!("compression failed: {other}")),
            })?;
        compressed.truncate(len);

        // Free the filtered data before building output.
        drop(filtered_data);

        // Assemble: preamble + IDAT + IEND
        let mut out = preamble;
        out.reserve(12 + compressed.len() + 12);
        write_chunk(&mut out, b"IDAT", &compressed);
        write_chunk(&mut out, b"IEND", &[]);

        Ok(out)
    }
}

/// Write a stored DEFLATE block header (5 bytes).
fn write_stored_block_header(out: &mut Vec<u8>, len: usize, is_final: bool) {
    out.push(if is_final { 1 } else { 0 });
    out.push((len & 0xFF) as u8);
    out.push(((len >> 8) & 0xFF) as u8);
    let nlen = !len & 0xFFFF;
    out.push((nlen & 0xFF) as u8);
    out.push(((nlen >> 8) & 0xFF) as u8);
}

/// Copy rows from a typed ImgVec into a PixelSliceMut via byte reinterpretation.
fn copy_rows_u8<P: Copy>(src: &imgref::ImgVec<P>, dst: &mut PixelSliceMut<'_>)
where
    [P]: rgb::ComponentBytes<u8>,
{
    use rgb::ComponentBytes;
    for y in 0..src.height().min(dst.rows() as usize) {
        let src_row = &src.buf()[y * src.stride()..][..src.width()];
        let src_bytes = src_row.as_bytes();
        let dst_row = dst.row_mut(y as u32);
        let n = src_bytes.len().min(dst_row.len());
        dst_row[..n].copy_from_slice(&src_bytes[..n]);
    }
}

/// Decode into linear RGB f32.
fn decode_into_rgb_f32(pixels: PixelBuffer, dst: &mut PixelSliceMut<'_>) {
    use linear_srgb::default::srgb_u8_to_linear;

    let src = to_rgb8(pixels);
    for y in 0..src.height().min(dst.rows() as usize) {
        let src_row = &src.buf()[y * src.stride()..][..src.width()];
        let dst_row = dst.row_mut(y as u32);
        for (i, s) in src_row.iter().enumerate() {
            let offset = i * 12;
            if offset + 12 > dst_row.len() {
                break;
            }
            let r = srgb_u8_to_linear(s.r);
            let g = srgb_u8_to_linear(s.g);
            let b = srgb_u8_to_linear(s.b);
            dst_row[offset..offset + 4].copy_from_slice(&r.to_ne_bytes());
            dst_row[offset + 4..offset + 8].copy_from_slice(&g.to_ne_bytes());
            dst_row[offset + 8..offset + 12].copy_from_slice(&b.to_ne_bytes());
        }
    }
}

/// Decode into linear RGBA f32.
fn decode_into_rgba_f32(pixels: PixelBuffer, dst: &mut PixelSliceMut<'_>) {
    use linear_srgb::default::srgb_u8_to_linear;

    let src = to_rgba8(pixels);
    for y in 0..src.height().min(dst.rows() as usize) {
        let src_row = &src.buf()[y * src.stride()..][..src.width()];
        let dst_row = dst.row_mut(y as u32);
        for (i, s) in src_row.iter().enumerate() {
            let offset = i * 16;
            if offset + 16 > dst_row.len() {
                break;
            }
            let r = srgb_u8_to_linear(s.r);
            let g = srgb_u8_to_linear(s.g);
            let b = srgb_u8_to_linear(s.b);
            dst_row[offset..offset + 4].copy_from_slice(&r.to_ne_bytes());
            dst_row[offset + 4..offset + 8].copy_from_slice(&g.to_ne_bytes());
            dst_row[offset + 8..offset + 12].copy_from_slice(&b.to_ne_bytes());
            dst_row[offset + 12..offset + 16].copy_from_slice(&(s.a as f32 / 255.0).to_ne_bytes());
        }
    }
}

/// Decode into linear Gray f32.
fn decode_into_gray_f32(pixels: PixelBuffer, dst: &mut PixelSliceMut<'_>) {
    use linear_srgb::default::srgb_u8_to_linear;

    let src = to_gray8(pixels);
    for y in 0..src.height().min(dst.rows() as usize) {
        let src_row = &src.buf()[y * src.stride()..][..src.width()];
        let dst_row = dst.row_mut(y as u32);
        for (i, s) in src_row.iter().enumerate() {
            let offset = i * 4;
            if offset + 4 > dst_row.len() {
                break;
            }
            let v = srgb_u8_to_linear(s.value());
            dst_row[offset..offset + 4].copy_from_slice(&v.to_ne_bytes());
        }
    }
}

// ── U16 conversion helpers ───────────────────────────────────────────

/// Byte-swap native-endian u16 samples to big-endian for PNG.
fn native_to_be_16(native: &[u8]) -> Vec<u8> {
    if cfg!(target_endian = "big") {
        return native.to_vec();
    }
    let mut out = native.to_vec();
    for chunk in out.chunks_exact_mut(2) {
        chunk.swap(0, 1);
    }
    out
}

/// Convert any PixelBuffer to Rgb<u16>. Upscales 8-bit by v*257.
fn to_rgb16(pixels: PixelBuffer) -> imgref::ImgVec<Rgb<u16>> {
    let desc = pixels.descriptor();
    let w = pixels.width() as usize;
    let h = pixels.height() as usize;
    match (desc.channel_type(), desc.layout()) {
        (ChannelType::U16, ChannelLayout::Rgb) => {
            let img = pixels.try_as_imgref::<Rgb<u16>>().unwrap();
            let buf: Vec<Rgb<u16>> = img.pixels().collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::Rgba) => {
            let img = pixels.try_as_imgref::<Rgba<u16>>().unwrap();
            let buf: Vec<Rgb<u16>> = img
                .pixels()
                .map(|p| Rgb {
                    r: p.r,
                    g: p.g,
                    b: p.b,
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::Gray) => {
            let img = pixels.try_as_imgref::<Gray<u16>>().unwrap();
            let buf: Vec<Rgb<u16>> = img
                .pixels()
                .map(|p| {
                    let v = p.value();
                    Rgb { r: v, g: v, b: v }
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::GrayAlpha) => {
            let img = pixels.try_as_imgref::<GrayAlpha16>().unwrap();
            let buf: Vec<Rgb<u16>> = img
                .pixels()
                .map(|p| {
                    let v = p.v;
                    Rgb { r: v, g: v, b: v }
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
        _ => {
            // Upscale 8-bit via to_rgb8
            let rgb8 = to_rgb8(pixels);
            let buf: Vec<Rgb<u16>> = rgb8
                .into_buf()
                .into_iter()
                .map(|p| Rgb {
                    r: p.r as u16 * 257,
                    g: p.g as u16 * 257,
                    b: p.b as u16 * 257,
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
    }
}

/// Convert any PixelBuffer to Rgba<u16>. Upscales 8-bit by v*257.
fn to_rgba16(pixels: PixelBuffer) -> imgref::ImgVec<Rgba<u16>> {
    let desc = pixels.descriptor();
    let w = pixels.width() as usize;
    let h = pixels.height() as usize;
    match (desc.channel_type(), desc.layout()) {
        (ChannelType::U16, ChannelLayout::Rgba) => {
            let img = pixels.try_as_imgref::<Rgba<u16>>().unwrap();
            let buf: Vec<Rgba<u16>> = img.pixels().collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::Rgb) => {
            let img = pixels.try_as_imgref::<Rgb<u16>>().unwrap();
            let buf: Vec<Rgba<u16>> = img
                .pixels()
                .map(|p| Rgba {
                    r: p.r,
                    g: p.g,
                    b: p.b,
                    a: 65535,
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::Gray) => {
            let img = pixels.try_as_imgref::<Gray<u16>>().unwrap();
            let buf: Vec<Rgba<u16>> = img
                .pixels()
                .map(|p| {
                    let v = p.value();
                    Rgba {
                        r: v,
                        g: v,
                        b: v,
                        a: 65535,
                    }
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::GrayAlpha) => {
            let img = pixels.try_as_imgref::<GrayAlpha16>().unwrap();
            let buf: Vec<Rgba<u16>> = img
                .pixels()
                .map(|p| Rgba {
                    r: p.v,
                    g: p.v,
                    b: p.v,
                    a: p.a,
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
        _ => {
            // Upscale 8-bit via to_rgba8
            let rgba8 = to_rgba8(pixels);
            let buf: Vec<Rgba<u16>> = rgba8
                .into_buf()
                .into_iter()
                .map(|p| Rgba {
                    r: p.r as u16 * 257,
                    g: p.g as u16 * 257,
                    b: p.b as u16 * 257,
                    a: p.a as u16 * 257,
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
    }
}

/// Convert any PixelBuffer to Gray<u16>. Upscales 8-bit by v*257.
fn to_gray16(pixels: PixelBuffer) -> imgref::ImgVec<Gray<u16>> {
    let desc = pixels.descriptor();
    let w = pixels.width() as usize;
    let h = pixels.height() as usize;
    match (desc.channel_type(), desc.layout()) {
        (ChannelType::U16, ChannelLayout::Gray) => {
            let img = pixels.try_as_imgref::<Gray<u16>>().unwrap();
            let buf: Vec<Gray<u16>> = img.pixels().collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::GrayAlpha) => {
            let img = pixels.try_as_imgref::<GrayAlpha16>().unwrap();
            let buf: Vec<Gray<u16>> = img.pixels().map(|p| Gray(p.v)).collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::Rgb) => {
            let img = pixels.try_as_imgref::<Rgb<u16>>().unwrap();
            let buf: Vec<Gray<u16>> = img
                .pixels()
                .map(|p| {
                    let luma =
                        ((p.r as u32 * 77 + p.g as u32 * 150 + p.b as u32 * 29 + 128) >> 8) as u16;
                    Gray(luma)
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
        (ChannelType::U16, ChannelLayout::Rgba) => {
            let img = pixels.try_as_imgref::<Rgba<u16>>().unwrap();
            let buf: Vec<Gray<u16>> = img
                .pixels()
                .map(|p| {
                    let luma =
                        ((p.r as u32 * 77 + p.g as u32 * 150 + p.b as u32 * 29 + 128) >> 8) as u16;
                    Gray(luma)
                })
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
        _ => {
            // Upscale 8-bit via to_gray8
            let gray8 = to_gray8(pixels);
            let buf: Vec<Gray<u16>> = gray8
                .into_buf()
                .into_iter()
                .map(|p| Gray(p.value() as u16 * 257))
                .collect();
            imgref::ImgVec::new(buf, w, h)
        }
    }
}

/// Decode into Rgb<u16> target buffer.
fn decode_into_rgb16(pixels: PixelBuffer, dst: &mut PixelSliceMut<'_>) {
    let src = to_rgb16(pixels);
    for y in 0..src.height().min(dst.rows() as usize) {
        let src_row = &src.buf()[y * src.stride()..][..src.width()];
        let dst_row = dst.row_mut(y as u32);
        for (i, s) in src_row.iter().enumerate() {
            let offset = i * 6;
            if offset + 6 > dst_row.len() {
                break;
            }
            dst_row[offset..offset + 2].copy_from_slice(&s.r.to_ne_bytes());
            dst_row[offset + 2..offset + 4].copy_from_slice(&s.g.to_ne_bytes());
            dst_row[offset + 4..offset + 6].copy_from_slice(&s.b.to_ne_bytes());
        }
    }
}

/// Decode into Rgba<u16> target buffer.
fn decode_into_rgba16(pixels: PixelBuffer, dst: &mut PixelSliceMut<'_>) {
    let src = to_rgba16(pixels);
    for y in 0..src.height().min(dst.rows() as usize) {
        let src_row = &src.buf()[y * src.stride()..][..src.width()];
        let dst_row = dst.row_mut(y as u32);
        for (i, s) in src_row.iter().enumerate() {
            let offset = i * 8;
            if offset + 8 > dst_row.len() {
                break;
            }
            dst_row[offset..offset + 2].copy_from_slice(&s.r.to_ne_bytes());
            dst_row[offset + 2..offset + 4].copy_from_slice(&s.g.to_ne_bytes());
            dst_row[offset + 4..offset + 6].copy_from_slice(&s.b.to_ne_bytes());
            dst_row[offset + 6..offset + 8].copy_from_slice(&s.a.to_ne_bytes());
        }
    }
}

/// Decode into Gray<u16> target buffer.
fn decode_into_gray16(pixels: PixelBuffer, dst: &mut PixelSliceMut<'_>) {
    let src = to_gray16(pixels);
    for y in 0..src.height().min(dst.rows() as usize) {
        let src_row = &src.buf()[y * src.stride()..][..src.width()];
        let dst_row = dst.row_mut(y as u32);
        for (i, s) in src_row.iter().enumerate() {
            let offset = i * 2;
            if offset + 2 > dst_row.len() {
                break;
            }
            dst_row[offset..offset + 2].copy_from_slice(&s.value().to_ne_bytes());
        }
    }
}

// ── decode_rows helpers ──────────────────────────────────────────────

/// Get the PixelDescriptor for decoded PixelBuffer.
fn pixel_descriptor_for_data(pixels: &PixelBuffer) -> PixelDescriptor {
    pixels.descriptor()
}

/// Get raw pixel bytes from PixelBuffer (copies to contiguous bytes).
fn pixel_data_bytes(pixels: &PixelBuffer) -> Vec<u8> {
    pixels.copy_to_contiguous_bytes()
}

// ── Tests ────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use imgref::Img;
    use rgb::{Gray, Rgb, Rgba};
    use zencodec::decode::{Decode, DecodeJob, DecoderConfig};
    use zencodec::encode::{EncodeJob, EncoderConfig};

    #[test]
    fn encoding_rgb8() {
        let enc = PngEncoderConfig::new();
        let pixels: Vec<Rgb<u8>> = vec![
            Rgb {
                r: 128,
                g: 64,
                b: 32
            };
            64
        ];
        let img = Img::new(pixels, 8, 8);
        let output = enc.encode_rgb8(img.as_ref()).unwrap();
        assert!(!output.data().is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
        assert_eq!(
            &output.data()[0..8],
            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
        );
    }

    #[test]
    fn encoding_rgba8() {
        let enc = PngEncoderConfig::new();
        let pixels: Vec<Rgba<u8>> = vec![
            Rgba {
                r: 100,
                g: 150,
                b: 200,
                a: 128,
            };
            64
        ];
        let img = Img::new(pixels, 8, 8);
        let output = enc.encode_rgba8(img.as_ref()).unwrap();
        assert!(!output.data().is_empty());
    }

    #[test]
    fn encoding_gray8() {
        let enc = PngEncoderConfig::new();
        let pixels = vec![Gray::new(128u8); 64];
        let img = Img::new(pixels, 8, 8);
        let output = enc.encode_gray8(img.as_ref()).unwrap();
        assert!(!output.data().is_empty());
    }

    #[test]
    fn decode_roundtrip() {
        let enc = PngEncoderConfig::new();
        let pixels: Vec<Rgb<u8>> = vec![
            Rgb {
                r: 200,
                g: 100,
                b: 50
            };
            64
        ];
        let img = Img::new(pixels, 8, 8);
        let encoded = enc.encode_rgb8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let output = dec.decode(encoded.data()).unwrap();
        assert_eq!(output.info().width, 8);
        assert_eq!(output.info().height, 8);
        assert_eq!(output.info().format, ImageFormat::Png);
    }

    #[test]
    fn probe_header_info() {
        let enc = PngEncoderConfig::new();
        let pixels = vec![Rgb { r: 0u8, g: 0, b: 0 }; 100];
        let img = Img::new(pixels, 10, 10);
        let encoded = enc.encode_rgb8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let info = dec.probe_header(encoded.data()).unwrap();
        assert_eq!(info.width, 10);
        assert_eq!(info.height, 10);
        assert_eq!(info.format, ImageFormat::Png);
    }

    #[test]
    fn decode_into_rgb8_roundtrip() {
        let enc = PngEncoderConfig::new();
        let pixels = vec![
            Rgb {
                r: 128u8,
                g: 64,
                b: 32
            };
            64
        ];
        let img = Img::new(pixels.clone(), 8, 8);
        let encoded = enc.encode_rgb8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let mut buf = vec![Rgb { r: 0u8, g: 0, b: 0 }; 64];
        let mut dst = imgref::ImgVec::new(buf.clone(), 8, 8);
        let info = dec.decode_into_rgb8(encoded.data(), dst.as_mut()).unwrap();
        assert_eq!(info.width, 8);
        assert_eq!(info.height, 8);
        buf = dst.into_buf();
        assert_eq!(buf[0], pixels[0]);
    }

    #[test]
    fn encode_bgra8_roundtrip() {
        let enc = PngEncoderConfig::new();
        let pixels = vec![
            rgb::alt::BGRA {
                b: 0,
                g: 0,
                r: 255,
                a: 255,
            },
            rgb::alt::BGRA {
                b: 0,
                g: 255,
                r: 0,
                a: 200,
            },
            rgb::alt::BGRA {
                b: 255,
                g: 0,
                r: 0,
                a: 128,
            },
            rgb::alt::BGRA {
                b: 128,
                g: 128,
                r: 128,
                a: 255,
            },
        ];
        let img = Img::new(pixels, 2, 2);
        let output = enc.encode_bgra8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let decoded = dec.decode(output.data()).unwrap();
        let rgba = to_rgba8(decoded.into_buffer());
        let buf = rgba.buf();
        assert_eq!(
            buf[0],
            Rgba {
                r: 255,
                g: 0,
                b: 0,
                a: 255
            }
        );
        assert_eq!(
            buf[1],
            Rgba {
                r: 0,
                g: 255,
                b: 0,
                a: 200
            }
        );
    }

    #[test]
    fn supported_descriptors_includes_rgbx_and_bgrx() {
        use zencodec::encode::EncoderConfig;
        let desc = PngEncoderConfig::supported_descriptors();
        assert!(
            desc.contains(&PixelDescriptor::RGBX8_SRGB),
            "RGBX8_SRGB must be in supported_descriptors"
        );
        assert!(
            desc.contains(&PixelDescriptor::BGRX8_SRGB),
            "BGRX8_SRGB must be in supported_descriptors"
        );
    }

    #[test]
    fn encode_rgbx8_roundtrip() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        // 16×16 image, RGBX8 layout: 4 bytes per pixel, byte 3 is padding.
        let w: u32 = 16;
        let h: u32 = 16;
        let mut buf = Vec::with_capacity((w * h * 4) as usize);
        for _ in 0..(w * h) {
            // padding byte 3 deliberately non-0xFF to confirm it's ignored
            buf.extend_from_slice(&[255, 128, 0, 0x13]);
        }
        let stride = (w * 4) as usize;
        let slice = PixelSlice::new(&buf, w, h, stride, PixelDescriptor::RGBX8_SRGB).unwrap();

        let output = PngEncoderConfig::new()
            .job()
            .encoder()
            .unwrap()
            .encode(slice.erase())
            .unwrap();
        assert_eq!(output.format(), ImageFormat::Png);
        assert!(!output.data().is_empty());

        let decoded = PngDecoderConfig::new().decode(output.data()).unwrap();
        let rgba = to_rgba8(decoded.into_buffer());
        let px = rgba.buf();
        assert_eq!(
            px[0],
            Rgba {
                r: 255,
                g: 128,
                b: 0,
                a: 255,
            },
            "RGBX8 padding byte must not leak into decoded alpha"
        );
    }

    #[test]
    fn encode_bgrx8_roundtrip() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w: u32 = 16;
        let h: u32 = 16;
        let mut buf = Vec::with_capacity((w * h * 4) as usize);
        for _ in 0..(w * h) {
            // BGR order: B=0, G=128, R=255; padding byte deliberately non-0xFF
            buf.extend_from_slice(&[0, 128, 255, 0x42]);
        }
        let stride = (w * 4) as usize;
        let slice = PixelSlice::new(&buf, w, h, stride, PixelDescriptor::BGRX8_SRGB).unwrap();

        let output = PngEncoderConfig::new()
            .job()
            .encoder()
            .unwrap()
            .encode(slice.erase())
            .unwrap();
        assert!(!output.data().is_empty());

        let decoded = PngDecoderConfig::new().decode(output.data()).unwrap();
        let rgba = to_rgba8(decoded.into_buffer());
        let px = rgba.buf();
        assert_eq!(
            px[0],
            Rgba {
                r: 255,
                g: 128,
                b: 0,
                a: 255,
            },
            "BGRX8 padding byte must not leak into decoded alpha"
        );
    }

    #[test]
    fn encode_rgbx8_matches_rgb8_size() {
        // RGBX8 should produce an RGB PNG, not an RGBA PNG — size should match
        // (or be very close to) the equivalent RGB8 encode, not the RGBA8 encode.
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w: u32 = 16;
        let h: u32 = 16;

        let mut rgbx = Vec::with_capacity((w * h * 4) as usize);
        let mut rgb = Vec::with_capacity((w * h * 3) as usize);
        for i in 0..(w * h) {
            let r = (i & 0xff) as u8;
            let g = ((i >> 1) & 0xff) as u8;
            let b = ((i >> 2) & 0xff) as u8;
            rgbx.extend_from_slice(&[r, g, b, 0x55]);
            rgb.extend_from_slice(&[r, g, b]);
        }

        let rgbx_slice =
            PixelSlice::new(&rgbx, w, h, (w * 4) as usize, PixelDescriptor::RGBX8_SRGB).unwrap();
        let rgb_slice =
            PixelSlice::new(&rgb, w, h, (w * 3) as usize, PixelDescriptor::RGB8_SRGB).unwrap();

        let rgbx_out = PngEncoderConfig::new()
            .job()
            .encoder()
            .unwrap()
            .encode(rgbx_slice.erase())
            .unwrap();
        let rgb_out = PngEncoderConfig::new()
            .job()
            .encoder()
            .unwrap()
            .encode(rgb_slice.erase())
            .unwrap();

        // Same channel count → same output size (deterministic encoder settings).
        assert_eq!(
            rgbx_out.data().len(),
            rgb_out.data().len(),
            "RGBX8 should encode as 3-channel RGB, matching RGB8 output size"
        );
    }

    #[test]
    fn f32_conversion_all_simd_tiers() {
        use archmage::testing::{CompileTimePolicy, for_each_token_permutation};
        use linear_srgb::default::{linear_to_srgb_u8, srgb_u8_to_linear};

        let report = for_each_token_permutation(CompileTimePolicy::Warn, |_perm| {
            // Encode linear f32 → PNG (sRGB u8) → decode to linear f32
            let pixels = vec![
                Rgb {
                    r: 0.0f32,
                    g: 0.5,
                    b: 1.0,
                },
                Rgb {
                    r: 0.25,
                    g: 0.75,
                    b: 0.1,
                },
                Rgb {
                    r: 0.0,
                    g: 0.0,
                    b: 0.0,
                },
                Rgb {
                    r: 1.0,
                    g: 1.0,
                    b: 1.0,
                },
            ];
            let img = Img::new(pixels.clone(), 2, 2);
            let enc = PngEncoderConfig::new();
            let output = enc.encode_rgb_f32(img.as_ref()).unwrap();

            let dec = PngDecoderConfig::new();
            let mut buf = vec![
                Rgb {
                    r: 0.0f32,
                    g: 0.0,
                    b: 0.0
                };
                4
            ];
            let mut dst = imgref::ImgVec::new(buf.clone(), 2, 2);
            dec.decode_into_rgb_f32(output.data(), dst.as_mut())
                .unwrap();
            buf = dst.into_buf();

            // Roundtrip tolerance: linear→sRGB u8→linear introduces quantization
            for (orig, decoded) in pixels.iter().zip(buf.iter()) {
                let expected_r = srgb_u8_to_linear(linear_to_srgb_u8(orig.r.clamp(0.0, 1.0)));
                let expected_g = srgb_u8_to_linear(linear_to_srgb_u8(orig.g.clamp(0.0, 1.0)));
                let expected_b = srgb_u8_to_linear(linear_to_srgb_u8(orig.b.clamp(0.0, 1.0)));
                assert!(
                    (decoded.r - expected_r).abs() < 1e-5,
                    "r mismatch: {} vs {}",
                    decoded.r,
                    expected_r
                );
                assert!(
                    (decoded.g - expected_g).abs() < 1e-5,
                    "g mismatch: {} vs {}",
                    decoded.g,
                    expected_g
                );
                assert!(
                    (decoded.b - expected_b).abs() < 1e-5,
                    "b mismatch: {} vs {}",
                    decoded.b,
                    expected_b
                );
            }
        });
        assert!(report.permutations_run >= 1);
    }

    #[test]
    fn f32_rgba_roundtrip() {
        use linear_srgb::default::{linear_to_srgb_u8, srgb_u8_to_linear};

        let pixels = vec![
            Rgba {
                r: 0.0f32,
                g: 0.5,
                b: 1.0,
                a: 1.0,
            },
            Rgba {
                r: 0.25,
                g: 0.75,
                b: 0.1,
                a: 0.5,
            },
            Rgba {
                r: 0.0,
                g: 0.0,
                b: 0.0,
                a: 0.0,
            },
            Rgba {
                r: 1.0,
                g: 1.0,
                b: 1.0,
                a: 1.0,
            },
        ];
        let img = Img::new(pixels.clone(), 2, 2);
        let enc = PngEncoderConfig::new();
        let output = enc.encode_rgba_f32(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let mut dst = imgref::ImgVec::new(
            vec![
                Rgba {
                    r: 0.0f32,
                    g: 0.0,
                    b: 0.0,
                    a: 0.0
                };
                4
            ],
            2,
            2,
        );
        dec.decode_into_rgba_f32(output.data(), dst.as_mut())
            .unwrap();

        for (orig, decoded) in pixels.iter().zip(dst.buf().iter()) {
            let expected_r = srgb_u8_to_linear(linear_to_srgb_u8(orig.r.clamp(0.0, 1.0)));
            let expected_g = srgb_u8_to_linear(linear_to_srgb_u8(orig.g.clamp(0.0, 1.0)));
            let expected_b = srgb_u8_to_linear(linear_to_srgb_u8(orig.b.clamp(0.0, 1.0)));
            let expected_a = (orig.a * 255.0).round() / 255.0;
            assert!((decoded.r - expected_r).abs() < 1e-5, "r mismatch");
            assert!((decoded.g - expected_g).abs() < 1e-5, "g mismatch");
            assert!((decoded.b - expected_b).abs() < 1e-5, "b mismatch");
            assert!(
                (decoded.a - expected_a).abs() < 1e-2,
                "a mismatch: {} vs {}",
                decoded.a,
                expected_a
            );
        }
    }

    #[test]
    fn f32_gray_roundtrip() {
        use linear_srgb::default::{linear_to_srgb_u8, srgb_u8_to_linear};
        use rgb::Gray;

        let pixels = vec![Gray(0.0f32), Gray(0.18), Gray(0.5), Gray(1.0)];
        let img = Img::new(pixels.clone(), 2, 2);
        let enc = PngEncoderConfig::new();
        let output = enc.encode_gray_f32(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let mut dst = imgref::ImgVec::new(vec![Gray(0.0f32); 4], 2, 2);
        dec.decode_into_gray_f32(output.data(), dst.as_mut())
            .unwrap();

        for (orig, decoded) in pixels.iter().zip(dst.buf().iter()) {
            let expected = srgb_u8_to_linear(linear_to_srgb_u8(orig.value().clamp(0.0, 1.0)));
            assert!(
                (decoded.value() - expected).abs() < 1e-5,
                "gray mismatch: {} vs {}",
                decoded.value(),
                expected
            );
        }
    }

    #[test]
    fn f32_known_srgb_values() {
        use linear_srgb::default::srgb_u8_to_linear;

        // Encode known sRGB u8 values, decode to linear f32, verify conversion
        let pixels = vec![
            Rgb { r: 0u8, g: 0, b: 0 },
            Rgb {
                r: 128,
                g: 128,
                b: 128,
            },
            Rgb {
                r: 255,
                g: 255,
                b: 255,
            },
            Rgb { r: 255, g: 0, b: 0 },
        ];
        let img = Img::new(pixels, 2, 2);
        let enc = PngEncoderConfig::new();
        let output = enc.encode_rgb8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let mut dst = imgref::ImgVec::new(
            vec![
                Rgb {
                    r: 0.0f32,
                    g: 0.0,
                    b: 0.0
                };
                4
            ],
            2,
            2,
        );
        dec.decode_into_rgb_f32(output.data(), dst.as_mut())
            .unwrap();

        let buf = dst.buf();
        // Black → 0.0 linear
        assert!(buf[0].r.abs() < 1e-6);
        assert!(buf[0].g.abs() < 1e-6);
        assert!(buf[0].b.abs() < 1e-6);
        // sRGB 128 → known linear value
        let expected_128 = srgb_u8_to_linear(128);
        assert!((buf[1].r - expected_128).abs() < 1e-5);
        // White → 1.0 linear
        assert!((buf[2].r - 1.0).abs() < 1e-6);
        assert!((buf[2].g - 1.0).abs() < 1e-6);
        assert!((buf[2].b - 1.0).abs() < 1e-6);
        // Pure red
        assert!((buf[3].r - 1.0).abs() < 1e-6);
        assert!(buf[3].g.abs() < 1e-6);
        assert!(buf[3].b.abs() < 1e-6);
    }

    #[test]
    fn format_is_correct() {
        assert_eq!(
            <PngEncoderConfig as EncoderConfig>::format(),
            ImageFormat::Png
        );
        assert_eq!(
            <PngDecoderConfig as DecoderConfig>::formats(),
            &[ImageFormat::Png]
        );
    }

    #[test]
    fn effort_getter_setter() {
        // Default (no effort set) → lossless
        let enc = PngEncoderConfig::new();
        assert_eq!(enc.generic_effort(), None);
        assert_eq!(enc.is_lossless(), Some(true));

        // effort 0 → None (store, no compression)
        let enc = PngEncoderConfig::new().with_generic_effort(0);
        assert_eq!(enc.generic_effort(), Some(0));

        // effort 1 → Fastest
        let enc = PngEncoderConfig::new().with_generic_effort(1);
        assert_eq!(enc.generic_effort(), Some(1));

        // effort 5 → Thorough
        let enc = PngEncoderConfig::new().with_generic_effort(5);
        assert_eq!(enc.generic_effort(), Some(5));
        assert_eq!(enc.is_lossless(), Some(true));

        // effort 9 → Crush
        let enc = PngEncoderConfig::new().with_generic_effort(9);
        assert_eq!(enc.generic_effort(), Some(9));

        // effort 10 → Maniac
        let enc = PngEncoderConfig::new().with_generic_effort(10);
        assert_eq!(enc.generic_effort(), Some(10));

        // effort 11 → Brag
        let enc = PngEncoderConfig::new().with_generic_effort(11);
        assert_eq!(enc.generic_effort(), Some(11));

        // effort 12+ → Minutes
        let enc = PngEncoderConfig::new().with_generic_effort(12);
        assert_eq!(enc.generic_effort(), Some(12));
    }

    #[test]
    fn output_info_matches_decode() {
        let pixels = vec![Rgb { r: 1u8, g: 2, b: 3 }; 6];
        let img = Img::new(pixels, 3, 2);
        let enc = PngEncoderConfig::new();
        let output = enc.encode_rgb8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let info = dec.clone().job().output_info(output.data()).unwrap();
        assert_eq!(info.width, 3);
        assert_eq!(info.height, 2);

        let decoded = dec.decode(output.data()).unwrap();
        assert_eq!(decoded.width(), info.width);
        assert_eq!(decoded.height(), info.height);
    }

    #[test]
    fn four_layer_encode_flow() {
        let pixels = vec![
            Rgb::<u8> { r: 255, g: 0, b: 0 },
            Rgb { r: 0, g: 255, b: 0 },
            Rgb { r: 0, g: 0, b: 255 },
            Rgb {
                r: 128,
                g: 128,
                b: 128,
            },
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);
        let config = PngEncoderConfig::new();

        use zencodec::encode::Encoder;
        let slice = PixelSlice::from(img.as_ref());
        let output = config
            .job()
            .encoder()
            .unwrap()
            .encode(slice.erase())
            .unwrap();
        assert_eq!(output.format(), ImageFormat::Png);
        assert!(!output.data().is_empty());
    }

    #[test]
    fn four_layer_decode_flow() {
        let pixels = vec![
            Rgb {
                r: 100u8,
                g: 200,
                b: 50
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);
        let enc = PngEncoderConfig::new();
        let encoded = enc.encode_rgb8(img.as_ref()).unwrap();

        let config = PngDecoderConfig::new();
        let decoded = config
            .job()
            .decoder(Cow::Borrowed(encoded.data()), &[])
            .unwrap()
            .decode()
            .unwrap();
        assert_eq!(decoded.width(), 2);
        assert_eq!(decoded.height(), 2);
    }

    #[test]
    fn encoding_clone_send_sync() {
        fn assert_traits<T: Clone + Send + Sync>() {}
        assert_traits::<PngEncoderConfig>();
    }

    #[test]
    fn decoding_clone_send_sync() {
        fn assert_traits<T: Clone + Send + Sync>() {}
        assert_traits::<PngDecoderConfig>();
    }

    #[test]
    fn rgb16_roundtrip() {
        let pixels = vec![
            Rgb::<u16> {
                r: 0,
                g: 32768,
                b: 65535,
            },
            Rgb {
                r: 1000,
                g: 50000,
                b: 12345,
            },
            Rgb {
                r: 65535,
                g: 0,
                b: 0,
            },
            Rgb {
                r: 0,
                g: 65535,
                b: 0,
            },
        ];
        let img = imgref::ImgVec::new(pixels.clone(), 2, 2);

        let encoded = crate::encode::encode_rgb16(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        // Verify PNG signature
        assert_eq!(
            &encoded[..8],
            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
        );

        // Decode and verify exact values
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        assert_eq!(decoded.info.width, 2);
        assert_eq!(decoded.info.height, 2);
        assert_eq!(decoded.info.bit_depth, 16);

        let img = decoded
            .pixels
            .try_as_imgref::<Rgb<u16>>()
            .expect("expected Rgb16");
        for (i, (orig, dec)) in pixels.iter().zip(img.pixels()).enumerate() {
            assert_eq!(
                *orig, dec,
                "pixel {i} mismatch: expected {orig:?}, got {dec:?}"
            );
        }
    }

    #[test]
    fn rgba16_roundtrip() {
        let pixels = vec![
            Rgba::<u16> {
                r: 0x0102,
                g: 0x0304,
                b: 0x0506,
                a: 0xFFFF,
            },
            Rgba {
                r: 65535,
                g: 0,
                b: 0,
                a: 32768,
            },
            Rgba {
                r: 0,
                g: 0,
                b: 0,
                a: 0,
            },
            Rgba {
                r: 65535,
                g: 65535,
                b: 65535,
                a: 65535,
            },
        ];
        let img = imgref::ImgVec::new(pixels.clone(), 2, 2);

        let encoded = crate::encode::encode_rgba16(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        assert_eq!(decoded.info.bit_depth, 16);

        let img = decoded
            .pixels
            .try_as_imgref::<Rgba<u16>>()
            .expect("expected Rgba16");
        for (i, (orig, dec)) in pixels.iter().zip(img.pixels()).enumerate() {
            assert_eq!(
                *orig, dec,
                "pixel {i} mismatch: expected {orig:?}, got {dec:?}"
            );
        }
    }

    #[test]
    fn gray16_roundtrip() {
        let pixels = vec![Gray::<u16>(0), Gray(1000), Gray(32768), Gray(65535)];
        let img = imgref::ImgVec::new(pixels.clone(), 2, 2);

        let encoded = crate::encode::encode_gray16(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        assert_eq!(decoded.info.bit_depth, 16);

        let img = decoded
            .pixels
            .try_as_imgref::<Gray<u16>>()
            .expect("expected Gray16");
        for (i, (orig, dec)) in pixels.iter().zip(img.pixels()).enumerate() {
            assert_eq!(
                *orig, dec,
                "pixel {i} mismatch: expected {orig:?}, got {dec:?}"
            );
        }
    }

    #[test]
    fn rgb16_metadata_roundtrip() {
        let pixels = vec![
            Rgb::<u16> {
                r: 100,
                g: 200,
                b: 300
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        let fake_icc = vec![0x42u8; 200];
        let exif_data = b"Exif\0\0test_exif";
        let xmp_data = b"<x:xmpmeta>test</x:xmpmeta>";
        let meta = Metadata::none()
            .with_icc(fake_icc.as_slice())
            .with_exif(exif_data.as_slice())
            .with_xmp(xmp_data.as_slice());

        let encoded = crate::encode::encode_rgb16(
            img.as_ref(),
            Some(&meta),
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        assert_eq!(
            decoded.info.icc_profile.as_deref(),
            Some(fake_icc.as_slice())
        );
        assert_eq!(decoded.info.exif.as_deref(), Some(exif_data.as_slice()));
        assert_eq!(decoded.info.xmp.as_deref(), Some(xmp_data.as_slice()));
    }

    #[test]
    fn truecolor_zenflate_rgb8_roundtrip() {
        // Verify that 8-bit truecolor now goes through zenflate (not flate2)
        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32,
            },
            Rgb { r: 0, g: 255, b: 0 },
            Rgb {
                r: 255,
                g: 255,
                b: 255,
            },
            Rgb { r: 0, g: 0, b: 0 },
        ];
        let img = imgref::ImgVec::new(pixels.clone(), 2, 2);

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        assert_eq!(decoded.info.width, 2);
        assert_eq!(decoded.info.height, 2);

        let img = decoded
            .pixels
            .try_as_imgref::<Rgb<u8>>()
            .expect("expected Rgb8");
        for (orig, dec) in pixels.iter().zip(img.pixels()) {
            assert_eq!(*orig, dec);
        }
    }

    #[test]
    fn truecolor_zenflate_rgba8_roundtrip() {
        let pixels = vec![
            Rgba::<u8> {
                r: 100,
                g: 150,
                b: 200,
                a: 128,
            },
            Rgba {
                r: 0,
                g: 0,
                b: 0,
                a: 0,
            },
            Rgba {
                r: 255,
                g: 255,
                b: 255,
                a: 255,
            },
            Rgba {
                r: 1,
                g: 2,
                b: 3,
                a: 4,
            },
        ];
        let img = imgref::ImgVec::new(pixels.clone(), 2, 2);

        let encoded = crate::encode::encode_rgba8(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        let img = decoded
            .pixels
            .try_as_imgref::<Rgba<u8>>()
            .expect("expected Rgba8");
        for (orig, dec) in pixels.iter().zip(img.pixels()) {
            assert_eq!(*orig, dec);
        }
    }

    #[test]
    fn truecolor_zenflate_gray8_roundtrip() {
        let pixels = vec![Gray(0u8), Gray(128), Gray(255), Gray(1)];
        let img = imgref::ImgVec::new(pixels.clone(), 2, 2);

        let encoded = crate::encode::encode_gray8(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        let img = decoded
            .pixels
            .try_as_imgref::<Gray<u8>>()
            .expect("expected Gray8");
        for (orig, dec) in pixels.iter().zip(img.pixels()) {
            assert_eq!(*orig, dec);
        }
    }

    #[test]
    fn subbyte_gray_1bit_roundtrip() {
        // 4x2 RGBA image: black and white only → should encode as 1-bit gray
        let mut pixels = Vec::new();
        for i in 0..8 {
            let v = if i % 2 == 0 { 0u8 } else { 255u8 };
            pixels.push(Rgba {
                r: v,
                g: v,
                b: v,
                a: 255,
            });
        }
        let img = imgref::ImgVec::new(pixels.clone(), 4, 2);

        let encoded = crate::encode::encode_rgba8(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        // Verify pixel-exact roundtrip (decoded may be Gray or RGBA)
        let decoded_rgba = decoded.pixels.to_rgba8();
        let decoded_img = decoded_rgba.as_imgref();
        for (i, (orig, dec)) in pixels.iter().zip(decoded_img.pixels()).enumerate() {
            assert_eq!(
                (orig.r, orig.g, orig.b, orig.a),
                (dec.r, dec.g, dec.b, dec.a),
                "pixel {i} mismatch"
            );
        }
    }

    #[test]
    fn subbyte_gray_4bit_roundtrip() {
        // Gray values: 0, 17, 34, ..., 255 (all divisible by 17) → 4-bit gray
        let mut pixels = Vec::new();
        for i in 0..16 {
            let v = (i * 17) as u8;
            pixels.push(Rgba {
                r: v,
                g: v,
                b: v,
                a: 255,
            });
        }
        let img = imgref::ImgVec::new(pixels.clone(), 4, 4);

        let encoded = crate::encode::encode_rgba8(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        let decoded_rgba = decoded.pixels.to_rgba8();
        let decoded_img = decoded_rgba.as_imgref();
        for (i, (orig, dec)) in pixels.iter().zip(decoded_img.pixels()).enumerate() {
            assert_eq!(
                (orig.r, orig.g, orig.b, orig.a),
                (dec.r, dec.g, dec.b, dec.a),
                "pixel {i} mismatch"
            );
        }
    }

    #[test]
    fn rgba_trns_gray_roundtrip() {
        // 10x10 grayscale RGBA with one transparent color
        // Transparent gray=0 (unique — doesn't appear opaque)
        let mut pixels = Vec::new();
        for i in 0..100 {
            if i == 0 {
                pixels.push(Rgba {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 0,
                }); // transparent
            } else {
                let v = ((i % 15) * 17 + 17) as u8; // 17..255, avoids 0
                pixels.push(Rgba {
                    r: v,
                    g: v,
                    b: v,
                    a: 255,
                });
            }
        }
        let img = imgref::ImgVec::new(pixels.clone(), 10, 10);

        let encoded = crate::encode::encode_rgba8(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        let decoded_rgba = decoded.pixels.to_rgba8();
        let decoded_img = decoded_rgba.as_imgref();
        for (i, (orig, dec)) in pixels.iter().zip(decoded_img.pixels()).enumerate() {
            if orig.a == 0 && dec.a == 0 {
                continue; // both transparent, RGB may differ
            }
            assert_eq!(
                (orig.r, orig.g, orig.b, orig.a),
                (dec.r, dec.g, dec.b, dec.a),
                "pixel {i} mismatch"
            );
        }
    }

    #[test]
    fn rgba_trns_rgb_roundtrip() {
        // >256 unique colors with one transparent color → should use RGB+tRNS
        let mut pixels = Vec::new();
        for r in 0..20u8 {
            for g in 0..21u8 {
                let b = 128u8;
                pixels.push(Rgba {
                    r: r.wrapping_mul(13),
                    g: g.wrapping_mul(12),
                    b,
                    a: 255,
                });
            }
        }
        // Make first pixel transparent with unique RGB
        pixels[0] = Rgba {
            r: 3,
            g: 7,
            b: 11,
            a: 0,
        };
        let w = 20;
        let h = pixels.len() / w;
        let img = imgref::ImgVec::new(pixels.clone(), w, h);

        let encoded = crate::encode::encode_rgba8(
            img.as_ref(),
            None,
            &EncodeConfig::default(),
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        let decoded_rgba = decoded.pixels.to_rgba8();
        let decoded_img = decoded_rgba.as_imgref();
        for (i, (orig, dec)) in pixels.iter().zip(decoded_img.pixels()).enumerate() {
            if orig.a == 0 && dec.a == 0 {
                continue;
            }
            assert_eq!(
                (orig.r, orig.g, orig.b, orig.a),
                (dec.r, dec.g, dec.b, dec.a),
                "pixel {i} mismatch"
            );
        }
    }

    #[test]
    fn zencodec_u16_encode_decode() {
        // Test the zencodec trait path for U16
        let pixels = vec![
            Rgb::<u16> {
                r: 100,
                g: 200,
                b: 300,
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels.clone(), 2, 2);

        let enc = PngEncoderConfig::new();
        let slice = PixelSlice::from(img.as_ref());
        use zencodec::encode::Encoder;
        let output = enc.job().encoder().unwrap().encode(slice.erase()).unwrap();
        assert_eq!(output.format(), ImageFormat::Png);

        // Decode back into U16
        let dec = PngDecoderConfig::new();
        let mut dst = imgref::ImgVec::new(vec![Rgb::<u16> { r: 0, g: 0, b: 0 }; 4], 2, 2);
        dec.decode_into_rgb16(output.data(), dst.as_mut()).unwrap();
        for (orig, dec) in pixels.iter().zip(dst.buf().iter()) {
            assert_eq!(orig, dec);
        }
    }

    #[test]
    fn srgb_suppresses_gama_chrm() {
        // PNGv3 precedence: sRGB suppresses gAMA and cHRM in output
        use crate::decode::PngChromaticities;

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        let chrm = PngChromaticities {
            white_x: 31270,
            white_y: 32900,
            red_x: 64000,
            red_y: 33000,
            green_x: 30000,
            green_y: 60000,
            blue_x: 15000,
            blue_y: 6000,
        };

        let config = crate::encode::EncodeConfig {
            source_gamma: Some(45455),
            srgb_intent: Some(0), // Perceptual
            chromaticities: Some(chrm),
            ..Default::default()
        };

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            None,
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        // sRGB is written, gAMA and cHRM are suppressed
        assert_eq!(decoded.info.srgb_intent, Some(0));
        assert_eq!(decoded.info.source_gamma, None);
        assert!(decoded.info.chromaticities.is_none());
    }

    #[test]
    fn gama_chrm_roundtrip_without_srgb() {
        // gAMA + cHRM round-trip when no higher-priority chunk is present
        use crate::decode::PngChromaticities;

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        let chrm = PngChromaticities {
            white_x: 31270,
            white_y: 32900,
            red_x: 64000,
            red_y: 33000,
            green_x: 30000,
            green_y: 60000,
            blue_x: 15000,
            blue_y: 6000,
        };

        let config = crate::encode::EncodeConfig {
            source_gamma: Some(45455),
            chromaticities: Some(chrm),
            ..Default::default()
        };

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            None,
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        assert_eq!(decoded.info.source_gamma, Some(45455));
        assert!(decoded.info.srgb_intent.is_none());
        let dc = decoded.info.chromaticities.expect("cHRM missing");
        assert_eq!(dc.white_x, 31270);
        assert_eq!(dc.white_y, 32900);
        assert_eq!(dc.red_x, 64000);
        assert_eq!(dc.red_y, 33000);
        assert_eq!(dc.green_x, 30000);
        assert_eq!(dc.green_y, 60000);
        assert_eq!(dc.blue_x, 15000);
        assert_eq!(dc.blue_y, 6000);
    }

    #[test]
    fn cicp_suppresses_srgb_gama_chrm() {
        // PNGv3 precedence: cICP suppresses sRGB, gAMA, cHRM
        use crate::decode::PngChromaticities;
        use zencodec::{Cicp, Metadata};

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        let cicp = Cicp::new(9, 16, 0, true);
        let meta = Metadata::none().with_cicp(cicp);

        let chrm = PngChromaticities {
            white_x: 31270,
            white_y: 32900,
            red_x: 64000,
            red_y: 33000,
            green_x: 30000,
            green_y: 60000,
            blue_x: 15000,
            blue_y: 6000,
        };

        let config = crate::encode::EncodeConfig {
            source_gamma: Some(45455),
            srgb_intent: Some(0),
            chromaticities: Some(chrm),
            ..Default::default()
        };

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            Some(&meta),
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        // cICP present, everything else suppressed
        assert!(decoded.info.cicp.is_some());
        assert_eq!(decoded.info.srgb_intent, None);
        assert_eq!(decoded.info.source_gamma, None);
        assert!(decoded.info.chromaticities.is_none());
    }

    #[test]
    fn iccp_suppresses_srgb_gama_chrm() {
        // PNGv3 precedence: iCCP suppresses sRGB, gAMA, cHRM
        use crate::decode::PngChromaticities;
        use zencodec::Metadata;

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        // Minimal valid ICC profile (just needs to be non-empty for the test)
        // Use a real sRGB profile header so iCCP decompression works
        // Minimal byte sequence — just needs to survive zlib round-trip
        let srgb_icc: &[u8] = &[0u8; 128];
        let meta = Metadata::none().with_icc(srgb_icc);

        let chrm = PngChromaticities {
            white_x: 31270,
            white_y: 32900,
            red_x: 64000,
            red_y: 33000,
            green_x: 30000,
            green_y: 60000,
            blue_x: 15000,
            blue_y: 6000,
        };

        let config = crate::encode::EncodeConfig {
            source_gamma: Some(45455),
            srgb_intent: Some(0),
            chromaticities: Some(chrm),
            ..Default::default()
        };

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            Some(&meta),
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        // iCCP present, sRGB/gAMA/cHRM suppressed
        assert!(decoded.info.icc_profile.is_some());
        assert_eq!(decoded.info.srgb_intent, None);
        assert_eq!(decoded.info.source_gamma, None);
        assert!(decoded.info.chromaticities.is_none());
    }

    #[test]
    fn cicp_with_iccp_fallback() {
        // PNGv3: cICP + iCCP both written (iCCP as fallback for limited cICP support)
        use zencodec::{Cicp, Metadata};

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        let cicp = Cicp::new(1, 13, 0, true);
        // Minimal byte sequence — just needs to survive zlib round-trip
        let srgb_icc: &[u8] = &[0u8; 128];
        let meta = Metadata::none().with_cicp(cicp).with_icc(srgb_icc);

        let config = crate::encode::EncodeConfig::default();

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            Some(&meta),
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        // Both cICP and iCCP present
        assert!(decoded.info.cicp.is_some());
        assert!(decoded.info.icc_profile.is_some());
        // sRGB/gAMA/cHRM suppressed
        assert_eq!(decoded.info.srgb_intent, None);
        assert_eq!(decoded.info.source_gamma, None);
        assert!(decoded.info.chromaticities.is_none());
    }

    #[test]
    fn hdr_metadata_always_written_with_cicp() {
        // mDCV and cLLi always written alongside cICP
        use zencodec::{Cicp, ContentLightLevel, MasteringDisplay, Metadata};

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        let cicp = Cicp::new(9, 16, 0, true);
        let clli = ContentLightLevel::new(1000, 400);
        let mdcv = MasteringDisplay::new(
            [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]],
            [0.3127, 0.3290],
            1000.0,
            0.005,
        );
        let meta = Metadata::none()
            .with_cicp(cicp)
            .with_content_light_level(clli)
            .with_mastering_display(mdcv);

        let config = crate::encode::EncodeConfig {
            source_gamma: Some(45455),
            srgb_intent: Some(0),
            ..Default::default()
        };

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            Some(&meta),
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        // cICP + HDR metadata present
        assert!(decoded.info.cicp.is_some());
        assert!(decoded.info.content_light_level.is_some());
        assert!(decoded.info.mastering_display.is_some());
        // sRGB/gAMA suppressed by cICP
        assert_eq!(decoded.info.srgb_intent, None);
        assert_eq!(decoded.info.source_gamma, None);
    }

    #[test]
    fn chrm_negative_values_roundtrip() {
        // Wide-gamut spaces can have negative chromaticity values
        use crate::decode::PngChromaticities;

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        // ACES AP1 has a negative blue_x primary
        let chrm = PngChromaticities {
            white_x: 32168,
            white_y: 33767,
            red_x: 71300,
            red_y: 29300,
            green_x: 16500,
            green_y: 83000,
            blue_x: -12800, // negative — imaginary primary
            blue_y: 4400,
        };

        let config = crate::encode::EncodeConfig {
            source_gamma: Some(100000), // linear
            chromaticities: Some(chrm),
            ..Default::default()
        };

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            None,
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        let dc = decoded.info.chromaticities.expect("cHRM missing");
        assert_eq!(dc.blue_x, -12800);
        assert_eq!(dc.blue_y, 4400);
        assert_eq!(dc.white_x, 32168);
    }

    #[test]
    fn cicp_roundtrip() {
        use zencodec::{Cicp, Metadata};

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        let cicp = Cicp::new(9, 16, 0, true); // BT.2020 primaries, PQ transfer, Identity matrix (PNG requirement)
        let meta = Metadata::none().with_cicp(cicp);
        let config = crate::encode::EncodeConfig::default();

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            Some(&meta),
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        let dc = decoded.info.cicp.expect("cICP missing");
        assert_eq!(dc.color_primaries, 9);
        assert_eq!(dc.transfer_characteristics, 16);
        assert_eq!(dc.matrix_coefficients, 0);
        assert!(dc.full_range);
    }

    #[test]
    fn clli_mdcv_roundtrip() {
        use zencodec::{ContentLightLevel, MasteringDisplay, Metadata};

        let pixels = vec![
            Rgb::<u8> {
                r: 128,
                g: 64,
                b: 32
            };
            4
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        let clli = ContentLightLevel::new(1000, 400);
        let mdcv = MasteringDisplay::new(
            [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]], // R, G, B primaries (CIE xy)
            [0.3127, 0.3290],                                 // white point (CIE xy)
            1000.0,                                           // max luminance (cd/m²)
            0.005,                                            // min luminance (cd/m²)
        );
        let meta = Metadata::none()
            .with_content_light_level(clli)
            .with_mastering_display(mdcv);
        let config = crate::encode::EncodeConfig::default();

        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            Some(&meta),
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();

        let dc = decoded.info.content_light_level.expect("cLLi missing");
        assert_eq!(dc.max_content_light_level, 1000);
        assert_eq!(dc.max_frame_average_light_level, 400);

        let dm = decoded.info.mastering_display.expect("mDCV missing");
        // Values roundtrip through PNG u16 (0.00002 units) and u32 (0.0001 cd/m² units)
        assert_eq!(
            dm.primaries_xy,
            [[0.708, 0.292], [0.170, 0.797], [0.131, 0.046]]
        );
        assert_eq!(dm.white_point_xy, [0.3127, 0.3290]);
        assert_eq!(dm.max_luminance, 1000.0);
        assert_eq!(dm.min_luminance, 0.005);
    }

    // ── Real-file roundtrip tests ────────────────────────────────────

    /// Decode a real PNG with gAMA+cHRM (no sRGB), re-encode preserving
    /// the color metadata, decode again, and verify exact roundtrip.
    #[test]
    #[ignore]
    fn real_file_gama_chrm_roundtrip() {
        let corpus = std::env::var("CODEC_CORPUS_DIR")
            .unwrap_or_else(|_| "/home/lilith/work/codec-corpus".to_string());
        let path = format!("{corpus}/imageflow/test_inputs/frymire.png");
        let data = std::fs::read(&path).expect("frymire.png not found");

        // Decode original
        let orig =
            crate::decode::decode(&data, &PngDecodeConfig::none(), &enough::Unstoppable).unwrap();
        let gamma = orig
            .info
            .source_gamma
            .expect("frymire.png should have gAMA");
        let chrm = orig
            .info
            .chromaticities
            .expect("frymire.png should have cHRM");
        assert!(
            orig.info.srgb_intent.is_none(),
            "frymire.png should NOT have sRGB"
        );

        // gamma=0.45454 (raw u32=45454)
        assert_eq!(gamma, 45454);

        // Re-encode with same metadata
        let config = crate::encode::EncodeConfig {
            source_gamma: Some(gamma),
            chromaticities: Some(chrm),
            ..Default::default()
        };
        let pixels = orig
            .pixels
            .try_as_imgref::<Rgb<u8>>()
            .expect("frymire.png should decode as RGB8");
        let encoded = crate::encode::encode_rgb8(
            pixels,
            None,
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        // Decode re-encoded
        let rt = crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
            .unwrap();
        assert_eq!(rt.info.source_gamma, Some(gamma));
        let rt_chrm = rt.info.chromaticities.expect("re-encoded should have cHRM");
        assert_eq!(rt_chrm, chrm);
        assert!(rt.info.srgb_intent.is_none());
    }

    /// Decode a real PNG with sRGB+gAMA+cHRM, re-encode, verify roundtrip.
    /// PNGv3 precedence: sRGB suppresses gAMA/cHRM in output.
    #[test]
    #[ignore]
    fn real_file_srgb_roundtrip() {
        let corpus = std::env::var("CODEC_CORPUS_DIR")
            .unwrap_or_else(|_| "/home/lilith/work/codec-corpus".to_string());
        let path = format!("{corpus}/imageflow/test_inputs/red-night.png");
        let data = std::fs::read(&path).expect("red-night.png not found");

        let orig =
            crate::decode::decode(&data, &PngDecodeConfig::none(), &enough::Unstoppable).unwrap();
        let intent = orig
            .info
            .srgb_intent
            .expect("red-night.png should have sRGB");
        // Original file has gAMA+cHRM alongside sRGB (pre-PNGv3 practice)
        assert!(orig.info.source_gamma.is_some());
        assert!(orig.info.chromaticities.is_some());

        assert_eq!(intent, 0); // Perceptual

        // Re-encode with all color metadata
        let config = crate::encode::EncodeConfig {
            source_gamma: orig.info.source_gamma,
            srgb_intent: Some(intent),
            chromaticities: orig.info.chromaticities,
            ..Default::default()
        };
        let pixels = orig
            .pixels
            .try_as_imgref::<Rgba<u8>>()
            .expect("red-night.png should decode as RGBA8");
        let encoded = crate::encode::encode_rgba8(
            pixels,
            None,
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let rt = crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
            .unwrap();
        // PNGv3: sRGB present → gAMA/cHRM suppressed in output
        assert_eq!(rt.info.srgb_intent, Some(0));
        assert_eq!(rt.info.source_gamma, None);
        assert!(rt.info.chromaticities.is_none());
    }

    /// Decode a real PNG with iCCP (Adobe RGB), re-encode preserving the
    /// ICC profile, verify the profile roundtrips.
    #[test]
    #[ignore]
    fn real_file_icc_roundtrip() {
        let corpus = std::env::var("CODEC_CORPUS_DIR")
            .unwrap_or_else(|_| "/home/lilith/work/codec-corpus".to_string());
        let path = format!("{corpus}/imageflow/test_inputs/shirt_transparent.png");
        let data = std::fs::read(&path).expect("shirt_transparent.png not found");

        let orig =
            crate::decode::decode(&data, &PngDecodeConfig::none(), &enough::Unstoppable).unwrap();
        let icc = orig
            .info
            .icc_profile
            .as_ref()
            .expect("shirt_transparent.png should have iCCP");
        assert!(!icc.is_empty());

        // Re-encode with ICC profile
        let meta = zencodec::Metadata::none().with_icc(icc.as_slice());
        let config = crate::encode::EncodeConfig::default();
        let pixels = orig
            .pixels
            .try_as_imgref::<Rgba<u8>>()
            .expect("shirt_transparent.png should decode as RGBA8");
        let encoded = crate::encode::encode_rgba8(
            pixels,
            Some(&meta),
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        let rt = crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
            .unwrap();
        let rt_icc = rt
            .info
            .icc_profile
            .as_ref()
            .expect("re-encoded should have iCCP");
        assert_eq!(icc, rt_icc);
    }

    #[test]
    fn test_clic_0d154_roundtrip() {
        // This 1024x1024 RGB image triggered a zenflate compression bug
        // at L4 with adaptive MinSum filtering (corrupt deflate stream).
        // The decompression verification in compress_filtered now catches this.
        let corpus = std::env::var("CODEC_CORPUS_DIR")
            .unwrap_or_else(|_| "/home/lilith/work/codec-corpus".to_string());
        let path = format!(
            "{corpus}/clic2025-1024/0d154749c7771f58e89ad343653ec4e20d6f037da829f47f5598e5d0a4ab61f0.png"
        );
        let data = match std::fs::read(&path) {
            Ok(d) => d,
            Err(_) => return, // skip if corpus not available
        };
        let decoded =
            crate::decode::decode(&data, &PngDecodeConfig::none(), &enough::Unstoppable).unwrap();
        let info = &decoded.info;
        let rgb_pixels = decoded
            .pixels
            .try_as_imgref::<Rgb<u8>>()
            .unwrap_or_else(|| panic!("expected Rgb8, got {:?}", decoded.pixels.descriptor()));

        for (name, comp) in [
            ("Fastest", crate::Compression::Fastest),
            ("Fast", crate::Compression::Fast),
            ("Balanced", crate::Compression::Balanced),
            ("Thorough", crate::Compression::Thorough),
            ("High", crate::Compression::High),
            ("Aggressive", crate::Compression::Aggressive),
        ] {
            let config = crate::EncodeConfig {
                source_gamma: info.source_gamma,
                srgb_intent: info.srgb_intent,
                chromaticities: info.chromaticities,
                compression: comp,
                ..Default::default()
            };
            let encoded = crate::encode::encode_rgb8(
                rgb_pixels,
                None,
                &config,
                &enough::Unstoppable,
                &enough::Unstoppable,
            )
            .unwrap();
            match crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable) {
                Ok(_) => {}
                Err(e) => panic!("{name}: full PNG re-decode failed: {e}"),
            }
        }
    }

    #[test]
    fn test_large_rgb8_roundtrip() {
        // Test with a 1024x1024 gradient image to catch compression bugs at ~3MiB
        let width = 1024usize;
        let height = 1024usize;
        let pixels: Vec<rgb::Rgb<u8>> = (0..width * height)
            .map(|i| {
                let x = i % width;
                let y = i / width;
                rgb::Rgb {
                    r: (x & 0xFF) as u8,
                    g: (y & 0xFF) as u8,
                    b: ((x + y) & 0xFF) as u8,
                }
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, width, height);
        let config = crate::EncodeConfig::default();
        let encoded = crate::encode::encode_rgb8(
            img.as_ref(),
            None,
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        let dec_img = decoded
            .pixels
            .try_as_imgref::<Rgb<u8>>()
            .unwrap_or_else(|| panic!("expected Rgb8, got {:?}", decoded.pixels.descriptor()));
        assert_eq!(dec_img.width(), width);
        assert_eq!(dec_img.height(), height);
    }

    #[test]
    fn immediate_cancel_encode_returns_stopped() {
        use enough::{Stop, StopReason};

        /// A Stop that always says "stop now".
        struct AlreadyCancelled;
        impl Stop for AlreadyCancelled {
            fn check(&self) -> Result<(), StopReason> {
                Err(StopReason::Cancelled)
            }
        }

        let config = PngEncoderConfig::new();
        let stop = zencodec::StopToken::new(AlreadyCancelled);
        let job = config.clone().job().with_stop(stop);
        let encoder = job.encoder().unwrap();

        // Create a small 2x2 RGB8 image
        let pixels = vec![Rgb { r: 0u8, g: 0, b: 0 }; 4];
        let img = Img::new(pixels, 2, 2);
        let slice = PixelSlice::from(img.as_ref());

        use zencodec::encode::Encoder;
        let result = encoder.encode(slice.erase());
        assert!(result.is_err());
        match result.unwrap_err().decompose().0 {
            PngError::Stopped(reason) => {
                assert_eq!(reason, StopReason::Cancelled);
            }
            other => panic!("expected PngError::Stopped, got: {other}"),
        }
    }

    #[test]
    fn zero_deadline_encode_still_succeeds() {
        // An immediately-expired deadline should still succeed by returning a fast result
        // (at least one strategy is always tried before checking the deadline)
        let config = crate::EncodeConfig::default();
        let deadline =
            almost_enough::time::WithTimeout::new(enough::Unstoppable, std::time::Duration::ZERO);

        let pixels = vec![
            rgb::Rgba {
                r: 255u8,
                g: 0,
                b: 0,
                a: 255,
            };
            16
        ];
        let img = imgref::ImgVec::new(pixels, 4, 4);
        let result = crate::encode::encode_rgba8(
            img.as_ref(),
            None,
            &config,
            &enough::Unstoppable,
            &deadline,
        );
        assert!(result.is_ok(), "zero-deadline encode should still succeed");

        // Verify it decodes
        let encoded = result.unwrap();
        let decoded =
            crate::decode::decode(&encoded, &PngDecodeConfig::none(), &enough::Unstoppable)
                .unwrap();
        assert_eq!(decoded.info.width, 4);
        assert_eq!(decoded.info.height, 4);
    }

    #[test]
    fn immediate_cancel_decode_returns_stopped() {
        use enough::{Stop, StopReason};

        struct AlreadyCancelled;
        impl Stop for AlreadyCancelled {
            fn check(&self) -> Result<(), StopReason> {
                Err(StopReason::Cancelled)
            }
        }

        // First encode a valid PNG
        let pixels = vec![
            rgb::Rgba {
                r: 128u8,
                g: 64,
                b: 32,
                a: 255,
            };
            16
        ];
        let img = imgref::ImgVec::new(pixels, 4, 4);
        let config = crate::EncodeConfig::default();
        let encoded = crate::encode::encode_rgba8(
            img.as_ref(),
            None,
            &config,
            &enough::Unstoppable,
            &enough::Unstoppable,
        )
        .unwrap();

        // Now try to decode with immediate cancel
        let result = crate::decode::decode(&encoded, &PngDecodeConfig::none(), &AlreadyCancelled);
        assert!(result.is_err());
        match result.unwrap_err().decompose().0 {
            PngError::Stopped(reason) => {
                assert_eq!(reason, StopReason::Cancelled);
            }
            other => panic!("expected PngError::Stopped, got: {other}"),
        }
    }

    #[test]
    fn quality_getter_setter() {
        // Default → no quality set, lossless
        let enc = PngEncoderConfig::new();
        assert_eq!(enc.generic_quality(), None);
        assert_eq!(enc.is_lossless(), Some(true));

        // quality 100.0 → still lossless
        let enc = PngEncoderConfig::new().with_generic_quality(100.0);
        assert_eq!(enc.generic_quality(), Some(100.0));
        assert_eq!(enc.is_lossless(), Some(true));

        // quality < 100.0 → lossy
        let enc = PngEncoderConfig::new().with_generic_quality(90.0);
        assert_eq!(enc.generic_quality(), Some(90.0));
        assert_eq!(enc.is_lossless(), Some(false));

        // quality 0.0 → lossy
        let enc = PngEncoderConfig::new().with_generic_quality(0.0);
        assert_eq!(enc.generic_quality(), Some(0.0));
        assert_eq!(enc.is_lossless(), Some(false));

        // effort + quality compose independently
        let enc = PngEncoderConfig::new()
            .with_generic_effort(5)
            .with_generic_quality(75.0);
        assert_eq!(enc.generic_effort(), Some(5));
        assert_eq!(enc.generic_quality(), Some(75.0));
        assert_eq!(enc.is_lossless(), Some(false));
    }

    #[test]
    fn quality_to_mpe_curve() {
        // Exact table points
        assert_eq!(quality_to_mpe(100.0), 0.0);
        assert_eq!(quality_to_mpe(99.0), 0.003);
        assert_eq!(quality_to_mpe(0.0), 0.100);

        // libjpeg-turbo SSIM2-calibrated points
        let mpe_95 = quality_to_mpe(95.0);
        assert!((mpe_95 - 0.007).abs() < 0.001, "q95 mpe={mpe_95}");

        let mpe_90 = quality_to_mpe(90.0);
        assert!((mpe_90 - 0.011).abs() < 0.001, "q90 mpe={mpe_90}");

        let mpe_75 = quality_to_mpe(75.0);
        assert!((mpe_75 - 0.026).abs() < 0.001, "q75 mpe={mpe_75}");

        let mpe_50 = quality_to_mpe(50.0);
        assert!((mpe_50 - 0.044).abs() < 0.001, "q50 mpe={mpe_50}");

        // Interpolated mid-point: q97 between q99 (0.003) and q95 (0.007)
        let mpe_97 = quality_to_mpe(97.0);
        assert!(mpe_97 > 0.003 && mpe_97 < 0.007, "q97 mpe={mpe_97}");

        // Monotonicity: lower quality → higher MPE (more tolerant)
        assert!(quality_to_mpe(90.0) > quality_to_mpe(99.0));
        assert!(quality_to_mpe(75.0) > quality_to_mpe(90.0));
        assert!(quality_to_mpe(50.0) > quality_to_mpe(75.0));
        assert!(quality_to_mpe(0.0) > quality_to_mpe(50.0));

        // Clamping: values outside 0-100 are clamped
        assert_eq!(quality_to_mpe(-10.0), quality_to_mpe(0.0));
        assert_eq!(quality_to_mpe(200.0), quality_to_mpe(100.0));
    }

    #[cfg(feature = "quantize")]
    #[test]
    fn quality_auto_indexed_rgba8() {
        // Create a simple image with few unique colors — should always quantize
        let pixels: Vec<Rgba<u8>> = vec![
            Rgba {
                r: 255,
                g: 0,
                b: 0,
                a: 255,
            },
            Rgba {
                r: 0,
                g: 255,
                b: 0,
                a: 255,
            },
            Rgba {
                r: 0,
                g: 0,
                b: 255,
                a: 255,
            },
            Rgba {
                r: 255,
                g: 255,
                b: 0,
                a: 255,
            },
        ];
        let img = imgref::ImgVec::new(pixels, 2, 2);

        // Lossless encode (no quality set)
        let enc_lossless = PngEncoderConfig::new();
        let out_lossless = enc_lossless.encode_rgba8(img.as_ref()).unwrap();

        // Lossy encode (quality 90 → auto-indexed)
        let enc_lossy = PngEncoderConfig::new().with_generic_quality(90.0);
        let out_lossy = enc_lossy.encode_rgba8(img.as_ref()).unwrap();

        // Both should produce valid PNG
        assert_eq!(
            &out_lossless.data()[..8],
            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
        );
        assert_eq!(
            &out_lossy.data()[..8],
            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
        );

        // With only 4 colors, auto-indexed should produce a PLTE chunk
        // (indexed PNG is smaller than truecolor for few-color images)
        let has_plte = out_lossy.data().windows(4).any(|w| w == b"PLTE");
        assert!(
            has_plte,
            "expected indexed PNG with PLTE chunk for 4-color image"
        );

        // Both should decode correctly
        let dec = PngDecoderConfig::new();
        let d_lossless = dec.decode(out_lossless.data()).unwrap();
        let d_lossy = dec.decode(out_lossy.data()).unwrap();
        assert_eq!(d_lossless.width(), 2);
        assert_eq!(d_lossy.width(), 2);
    }

    // ── Builder methods ──

    #[test]
    fn with_compression_sets_config() {
        let enc = PngEncoderConfig::new().with_compression(crate::Compression::Turbo);
        let pixels = vec![Rgb { r: 0, g: 0, b: 0 }; 4];
        let img = Img::new(pixels, 2, 2);
        let out = enc.encode_rgb8(img.as_ref()).unwrap();
        assert!(!out.data().is_empty());
    }

    #[test]
    fn with_filter_sets_config() {
        let enc = PngEncoderConfig::new().with_filter(crate::Filter::Auto);
        let pixels = vec![Rgb { r: 0, g: 0, b: 0 }; 4];
        let img = Img::new(pixels, 2, 2);
        let out = enc.encode_rgb8(img.as_ref()).unwrap();
        assert!(!out.data().is_empty());
    }

    #[test]
    fn default_encoder_config() {
        let enc: PngEncoderConfig = Default::default();
        assert!(enc.generic_effort().is_none());
        assert!(enc.generic_quality().is_none());
    }

    // ── 16-bit encode convenience methods ──

    #[test]
    fn encode_rgb16_roundtrip() {
        let enc = PngEncoderConfig::new();
        let pixels = vec![
            Rgb {
                r: 1000u16,
                g: 2000,
                b: 3000
            };
            4
        ];
        let img = Img::new(pixels, 2, 2);
        let out = enc.encode_rgb16(img.as_ref()).unwrap();
        assert!(!out.data().is_empty());
        assert_eq!(
            &out.data()[..8],
            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
        );
    }

    #[test]
    fn encode_rgba16_roundtrip() {
        let enc = PngEncoderConfig::new();
        let pixels = vec![
            Rgba {
                r: 1000u16,
                g: 2000,
                b: 3000,
                a: 65535
            };
            4
        ];
        let img = Img::new(pixels, 2, 2);
        let out = enc.encode_rgba16(img.as_ref()).unwrap();
        assert!(!out.data().is_empty());
    }

    #[test]
    fn encode_gray16_roundtrip() {
        let enc = PngEncoderConfig::new();
        let pixels = vec![Gray::new(30000u16); 4];
        let img = Img::new(pixels, 2, 2);
        let out = enc.encode_gray16(img.as_ref()).unwrap();
        assert!(!out.data().is_empty());
    }

    // ── effort_to_compression coverage ──

    #[test]
    fn effort_to_compression_all_levels() {
        use crate::Compression;
        // Cover all branches including the uncovered ones (2-8, 12+)
        assert!(matches!(effort_to_compression(-1), Compression::None));
        assert!(matches!(effort_to_compression(0), Compression::None));
        assert!(matches!(effort_to_compression(1), Compression::Fastest));
        assert!(matches!(effort_to_compression(2), Compression::Turbo));
        assert!(matches!(effort_to_compression(3), Compression::Fast));
        assert!(matches!(effort_to_compression(4), Compression::Balanced));
        assert!(matches!(effort_to_compression(5), Compression::Thorough));
        assert!(matches!(effort_to_compression(6), Compression::High));
        assert!(matches!(effort_to_compression(7), Compression::Aggressive));
        assert!(matches!(effort_to_compression(8), Compression::Intense));
        assert!(matches!(effort_to_compression(9), Compression::Crush));
        assert!(matches!(effort_to_compression(10), Compression::Maniac));
        assert!(matches!(effort_to_compression(11), Compression::Brag));
        assert!(matches!(effort_to_compression(12), Compression::Minutes));
        assert!(matches!(effort_to_compression(100), Compression::Minutes));
    }

    // ── quality_to_mpe coverage ──

    #[test]
    fn quality_to_mpe_endpoints() {
        // q=100 → mpe=0.0
        assert_eq!(quality_to_mpe(100.0), 0.0);
        // q=0 → mpe=0.1
        assert_eq!(quality_to_mpe(0.0), 0.1);
        // q > 100 → clamped to 100 → 0.0
        assert_eq!(quality_to_mpe(150.0), 0.0);
        // q < 0 → clamped to 0 → 0.1
        assert_eq!(quality_to_mpe(-10.0), 0.1);
    }

    #[test]
    fn quality_to_mpe_interpolation() {
        // q=95 should be 0.007
        assert!((quality_to_mpe(95.0) - 0.007).abs() < 0.0001);
        // q=50 should be 0.044
        assert!((quality_to_mpe(50.0) - 0.044).abs() < 0.0001);
        // Interpolated value between 95 and 99
        let mid = quality_to_mpe(97.0);
        assert!(mid > 0.003 && mid < 0.007);
    }

    // ── EncodeJob trait methods ──

    #[test]
    fn encode_job_with_stop() {
        let enc = PngEncoderConfig::new();
        let stop = zencodec::StopToken::new(enough::Unstoppable);
        let job = enc.job().with_stop(stop);
        let encoder = job.encoder().unwrap();
        let pixels = vec![Rgb { r: 0u8, g: 0, b: 0 }; 4];
        let img = Img::new(pixels, 2, 2);
        let out = encoder.do_encode(
            bytemuck::cast_slice(img.buf()),
            2,
            2,
            crate::encode::ColorType::Rgb,
        );
        assert!(out.is_ok());
    }

    #[test]
    fn encode_job_with_limits() {
        let enc = PngEncoderConfig::new();
        let limits = ResourceLimits::default();
        let job = enc.job().with_limits(limits);
        let encoder = job.encoder().unwrap();
        let pixels = vec![Rgb { r: 0u8, g: 0, b: 0 }; 4];
        let img = Img::new(pixels, 2, 2);
        let out = encoder.do_encode(
            bytemuck::cast_slice(img.buf()),
            2,
            2,
            crate::encode::ColorType::Rgb,
        );
        assert!(out.is_ok());
    }

    #[test]
    fn encode_job_with_metadata() {
        let enc = PngEncoderConfig::new();
        let meta = Metadata::default();
        let job = enc.job().with_metadata(meta);
        let encoder = job.encoder().unwrap();
        let pixels = vec![Rgb { r: 0u8, g: 0, b: 0 }; 4];
        let img = Img::new(pixels, 2, 2);
        let out = encoder.do_encode(
            bytemuck::cast_slice(img.buf()),
            2,
            2,
            crate::encode::ColorType::Rgb,
        );
        assert!(out.is_ok());
    }

    #[test]
    fn encode_job_animation_frame_encoder() {
        let enc = PngEncoderConfig::new();
        let job = enc.job().with_canvas_size(8, 8).with_loop_count(Some(0));
        let frame_enc = job.animation_frame_encoder();
        assert!(frame_enc.is_ok());
    }

    // ── EncoderConfig trait ──

    #[test]
    fn encoder_supported_descriptors() {
        let descs = <PngEncoderConfig as EncoderConfig>::supported_descriptors();
        assert!(!descs.is_empty());
        assert!(descs.contains(&PixelDescriptor::RGB8_SRGB));
        assert!(descs.contains(&PixelDescriptor::RGBA8_SRGB));
    }

    #[test]
    fn encoder_is_lossless() {
        let enc = PngEncoderConfig::new();
        assert_eq!(enc.is_lossless(), Some(true));
        let enc_lossy = enc.with_generic_quality(90.0);
        assert_eq!(enc_lossy.is_lossless(), Some(false));
    }

    // ── Encoder trait roundtrip tests ──

    #[test]
    fn encoder_trait_rgb8() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Rgb<u8>> = (0..16 * 16)
            .map(|i| Rgb {
                r: (i % 256) as u8,
                g: ((i * 3) % 256) as u8,
                b: ((i * 7) % 256) as u8,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_rgba8() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Rgba<u8>> = (0..16 * 16)
            .map(|i| Rgba {
                r: (i % 256) as u8,
                g: ((i * 3) % 256) as u8,
                b: ((i * 7) % 256) as u8,
                a: 255,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_gray8() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Gray<u8>> = (0..16 * 16).map(|i| Gray((i % 256) as u8)).collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_rgb16() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Rgb<u16>> = (0..16 * 16)
            .map(|i| Rgb {
                r: (i * 256) as u16,
                g: ((i * 3 * 256) % 65536) as u16,
                b: 0,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_rgba16() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Rgba<u16>> = (0..16 * 16)
            .map(|i| Rgba {
                r: (i * 256) as u16,
                g: ((i * 3 * 256) % 65536) as u16,
                b: 0,
                a: 65535,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_gray16() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Gray<u16>> = (0..16 * 16).map(|i| Gray((i * 256) as u16)).collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_rgb_f32() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Rgb<f32>> = (0..16 * 16)
            .map(|i| Rgb {
                r: (i % 256) as f32 / 255.0,
                g: ((i * 3) % 256) as f32 / 255.0,
                b: ((i * 7) % 256) as f32 / 255.0,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_rgba_f32() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Rgba<f32>> = (0..16 * 16)
            .map(|i| Rgba {
                r: (i % 256) as f32 / 255.0,
                g: ((i * 3) % 256) as f32 / 255.0,
                b: ((i * 7) % 256) as f32 / 255.0,
                a: 1.0,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_gray_f32() {
        use zencodec::encode::Encoder;
        let pixels: Vec<Gray<f32>> = (0..16 * 16)
            .map(|i| Gray((i % 256) as f32 / 255.0))
            .collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    #[test]
    fn encoder_trait_bgra8() {
        use zencodec::encode::Encoder;
        let pixels: Vec<rgb::alt::BGRA<u8>> = (0..16 * 16)
            .map(|i| rgb::alt::BGRA {
                b: (i % 256) as u8,
                g: 128,
                r: 64,
                a: 255,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 16, 16);
        let config = PngEncoderConfig::new();
        let encoder = config.clone().job().encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).into())
            .unwrap();
        assert!(!output.is_empty());
        assert_eq!(output.format(), ImageFormat::Png);
    }

    // ── ResourceLimits enforcement tests ──

    #[test]
    fn encode_max_output_bytes_rejects_large_output() {
        use zencodec::encode::Encoder;
        // Encode a 32x32 RGB image — output will be well over 100 bytes.
        let pixels: Vec<Rgb<u8>> = (0..32 * 32)
            .map(|i| Rgb {
                r: (i % 256) as u8,
                g: ((i * 3) % 256) as u8,
                b: ((i * 7) % 256) as u8,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 32, 32);
        let config = PngEncoderConfig::new();
        let limits = ResourceLimits::none().with_max_output(100);
        let encoder = config.clone().job().with_limits(limits).encoder().unwrap();
        let result = encoder.encode(PixelSlice::from(img.as_ref()).erase());
        let err = result.unwrap_err();
        let msg = alloc::format!("{}", err);
        assert!(
            msg.contains("limit exceeded") || msg.contains("output size"),
            "expected limit exceeded error, got: {msg}"
        );
    }

    #[test]
    fn encode_max_output_bytes_allows_small_output() {
        use zencodec::encode::Encoder;
        // 2x2 tiny image — output will be small but still a valid PNG
        let pixels: Vec<Rgb<u8>> = vec![Rgb { r: 0, g: 0, b: 0 }; 4];
        let img = imgref::ImgVec::new(pixels, 2, 2);
        let config = PngEncoderConfig::new();
        // Allow up to 10 KB — should be plenty for a 2x2 PNG
        let limits = ResourceLimits::none().with_max_output(10_000);
        let encoder = config.clone().job().with_limits(limits).encoder().unwrap();
        let result = encoder.encode(PixelSlice::from(img.as_ref()).erase());
        assert!(result.is_ok(), "expected success, got: {:?}", result.err());
    }

    #[test]
    fn apng_push_frame_rejects_over_max_frames() {
        use zencodec::encode::AnimationFrameEncoder;
        let config = PngEncoderConfig::new();
        let limits = ResourceLimits::none().with_max_frames(2);
        let job = config
            .job()
            .with_canvas_size(4, 4)
            .with_loop_count(Some(0))
            .with_limits(limits);
        let mut enc = job.animation_frame_encoder().unwrap();

        let make_frame = || {
            let pixels: Vec<Rgba<u8>> = vec![
                Rgba {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 255,
                };
                16
            ];
            imgref::ImgVec::new(pixels, 4, 4)
        };

        // First two frames should succeed
        let img1 = make_frame();
        enc.push_frame(PixelSlice::from(img1.as_ref()).erase(), 100, None)
            .unwrap();
        let img2 = make_frame();
        enc.push_frame(PixelSlice::from(img2.as_ref()).erase(), 100, None)
            .unwrap();

        // Third frame should fail with limit exceeded
        let img3 = make_frame();
        let result = enc.push_frame(PixelSlice::from(img3.as_ref()).erase(), 100, None);
        let err = result.unwrap_err();
        let msg = alloc::format!("{}", err);
        assert!(
            msg.contains("limit exceeded") || msg.contains("frame count"),
            "expected frame limit error, got: {msg}"
        );
    }

    #[test]
    fn apng_push_frame_rejects_over_max_memory() {
        use zencodec::encode::AnimationFrameEncoder;
        let config = PngEncoderConfig::new();
        // 4x4 RGBA8 = 64 bytes per frame. Limit to 100 bytes total.
        let limits = ResourceLimits::none().with_max_memory(100);
        let job = config
            .job()
            .with_canvas_size(4, 4)
            .with_loop_count(Some(0))
            .with_limits(limits);
        let mut enc = job.animation_frame_encoder().unwrap();

        let make_frame = || {
            let pixels: Vec<Rgba<u8>> = vec![
                Rgba {
                    r: 0,
                    g: 0,
                    b: 0,
                    a: 255,
                };
                16
            ];
            imgref::ImgVec::new(pixels, 4, 4)
        };

        // First frame is 64 bytes — should succeed (64 <= 100)
        let img1 = make_frame();
        enc.push_frame(PixelSlice::from(img1.as_ref()).erase(), 100, None)
            .unwrap();

        // Second frame would be 128 bytes cumulative — should fail (128 > 100)
        let img2 = make_frame();
        let result = enc.push_frame(PixelSlice::from(img2.as_ref()).erase(), 100, None);
        let err = result.unwrap_err();
        let msg = alloc::format!("{}", err);
        assert!(
            msg.contains("limit exceeded") || msg.contains("memory"),
            "expected memory limit error, got: {msg}"
        );
    }

    #[test]
    fn decode_max_input_bytes_rejects_large_input() {
        use zencodec::decode::{Decode, DecodeJob, DecoderConfig};
        // First, encode a valid PNG
        let pixels: Vec<Rgb<u8>> = vec![
            Rgb {
                r: 128,
                g: 64,
                b: 32
            };
            64
        ];
        let img = imgref::ImgVec::new(pixels, 8, 8);
        let enc = PngEncoderConfig::new();
        let encoded = enc.encode_rgb8(img.as_ref()).unwrap();
        let data = encoded.data();

        // Now try to decode with a very small max_input_bytes limit
        let dec = PngDecoderConfig::new();
        let limits = ResourceLimits::none().with_max_input_bytes(10);
        let result = dec
            .job()
            .with_limits(limits)
            .decoder(Cow::Borrowed(data), &[])
            .unwrap()
            .decode();
        let err = result.unwrap_err();
        let msg = alloc::format!("{}", err);
        assert!(
            msg.contains("limit exceeded") || msg.contains("input size"),
            "expected input size limit error, got: {msg}"
        );
    }

    #[test]
    fn decode_max_input_bytes_allows_small_input() {
        use zencodec::decode::{Decode, DecodeJob, DecoderConfig};
        // Encode a tiny PNG
        let pixels: Vec<Rgb<u8>> = vec![Rgb { r: 0, g: 0, b: 0 }; 4];
        let img = imgref::ImgVec::new(pixels, 2, 2);
        let enc = PngEncoderConfig::new();
        let encoded = enc.encode_rgb8(img.as_ref()).unwrap();
        let data = encoded.data();

        // Generous limit — should succeed
        let dec = PngDecoderConfig::new();
        let limits = ResourceLimits::none().with_max_input_bytes(100_000);
        let result = dec
            .job()
            .with_limits(limits)
            .decoder(Cow::Borrowed(data), &[])
            .unwrap()
            .decode();
        assert!(result.is_ok(), "expected success, got: {:?}", result.err());
    }

    // ── ThreadingPolicy tests ──

    #[test]
    fn encode_single_thread_produces_valid_png() {
        use zencodec::ThreadingPolicy;
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let pixels: Vec<Rgb<u8>> = (0..32 * 32)
            .map(|i| Rgb {
                r: (i % 256) as u8,
                g: ((i * 3) % 256) as u8,
                b: ((i * 7) % 256) as u8,
            })
            .collect();
        let img = imgref::ImgVec::new(pixels, 32, 32);

        let config = PngEncoderConfig::new();
        let limits = ResourceLimits::none().with_threading(ThreadingPolicy::Sequential);
        let encoder = config.clone().job().with_limits(limits).encoder().unwrap();
        let output = encoder
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();

        // Valid PNG header
        assert_eq!(
            &output.data()[0..8],
            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
        );

        // Roundtrip: decode it back
        use zencodec::decode::{Decode, DecodeJob, DecoderConfig};
        let dec = PngDecoderConfig::new();
        let result = dec
            .job()
            .decoder(Cow::Borrowed(output.data()), &[])
            .unwrap()
            .decode();
        assert!(
            result.is_ok(),
            "roundtrip decode failed: {:?}",
            result.err()
        );
    }

    #[test]
    fn encode_single_thread_matches_default_threading() {
        use zencodec::ThreadingPolicy;
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let pixels: Vec<Rgb<u8>> = vec![
            Rgb {
                r: 100,
                g: 150,
                b: 200,
            };
            16 * 16
        ];
        let img = imgref::ImgVec::new(pixels, 16, 16);

        // Encode with SingleThread
        let config_st = PngEncoderConfig::new();
        let limits = ResourceLimits::none().with_threading(ThreadingPolicy::Sequential);
        let st_output = config_st
            .job()
            .with_limits(limits)
            .encoder()
            .unwrap()
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();

        // Encode with default (Unlimited)
        let config_def = PngEncoderConfig::new();
        let def_output = config_def
            .job()
            .encoder()
            .unwrap()
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();

        // Both must be valid PNGs (same content, so should be identical)
        assert_eq!(
            &st_output.data()[0..8],
            &[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
        );
        assert_eq!(st_output.data().len(), def_output.data().len());
    }

    // TODO: fix lifetime issue — `config` must outlive `dyn_enc`
    // #[test]
    // fn encoder_trait_dyn_encoder() {
    //     let pixels: Vec<Rgb<u8>> = vec![
    //         Rgb {
    //             r: 100,
    //             g: 150,
    //             b: 200,
    //         };
    //         32 * 32
    //     ];
    //     let img = imgref::ImgVec::new(pixels, 32, 32);
    //     let config = PngEncoderConfig::new();
    //     let dyn_enc = config.clone().job().dyn_encoder().unwrap();
    //     let output = dyn_enc
    //         .encode(PixelSlice::from(img.as_ref()).into())
    //         .unwrap();
    //     assert!(!output.is_empty());
    //     assert_eq!(output.format(), ImageFormat::Png);
    // }

    // ── push_rows / finish tests ──

    #[test]
    fn push_rows_rgb8_roundtrip() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 4u32;
        let h = 6u32;
        let pixels: Vec<Rgb<u8>> = (0..w * h)
            .map(|i| Rgb {
                r: (i * 7) as u8,
                g: (i * 13) as u8,
                b: (i * 19) as u8,
            })
            .collect();
        let img = Img::new(pixels.clone(), w as usize, h as usize);

        // Encode via push_rows (2 rows at a time)
        let config = PngEncoderConfig::new();
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        for strip_y in (0..h).step_by(2) {
            let strip = img.sub_image(0, strip_y as usize, w as usize, 2);
            let slice = PixelSlice::from(strip).erase();
            encoder.push_rows(slice).unwrap();
        }
        let push_output = encoder.finish().unwrap();

        // Encode via one-shot for comparison
        let oneshot_output = config
            .job()
            .encoder()
            .unwrap()
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();

        // Both should produce valid PNG of the same dimensions
        assert!(!push_output.data().is_empty());
        let decoded_push = crate::decode(
            push_output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        let decoded_one = crate::decode(
            oneshot_output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded_push.info.width, w);
        assert_eq!(decoded_push.info.height, h);
        // Pixel data should be identical
        assert_eq!(
            decoded_push.pixels.copy_to_contiguous_bytes(),
            decoded_one.pixels.copy_to_contiguous_bytes()
        );
    }

    #[test]
    fn push_rows_rgba8_single_row_at_a_time() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 3u32;
        let h = 4u32;
        let pixels: Vec<Rgba<u8>> = (0..w * h)
            .map(|i| Rgba {
                r: (i * 5) as u8,
                g: (i * 11) as u8,
                b: (i * 17) as u8,
                a: 255,
            })
            .collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new();
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        for y in 0..h {
            let strip = img.sub_image(0, y as usize, w as usize, 1);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);
    }

    #[test]
    fn push_rows_all_at_once() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 8u32;
        let h = 8u32;
        let pixels: Vec<Rgb<u8>> = vec![
            Rgb {
                r: 128,
                g: 64,
                b: 32,
            };
            (w * h) as usize
        ];
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new();
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        encoder
            .push_rows(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);
    }

    #[test]
    fn push_rows_gray8() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 5u32;
        let h = 3u32;
        let pixels: Vec<Gray<u8>> = (0..w * h).map(|i| Gray::new((i * 17) as u8)).collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new();
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        encoder
            .push_rows(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);
    }

    #[test]
    fn push_rows_finish_without_push_errors() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let config = PngEncoderConfig::new();
        let encoder = config
            .clone()
            .job()
            .with_canvas_size(4, 4)
            .encoder()
            .unwrap();
        assert!(encoder.finish().is_err());
    }

    #[test]
    fn push_rows_overflow_errors() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 2u32;
        let h = 2u32;
        let pixels: Vec<Rgb<u8>> = vec![Rgb { r: 0, g: 0, b: 0 }; (w * 3) as usize]; // 3 rows worth
        let img = Img::new(pixels, w as usize, 3);

        let config = PngEncoderConfig::new();
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        // Pushing 3 rows when canvas is 2 tall should error
        let result = encoder.push_rows(PixelSlice::from(img.as_ref()).erase());
        assert!(result.is_err());
    }

    #[test]
    fn push_rows_matches_encode_output() {
        // Verify push_rows produces byte-identical output to encode()
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 16u32;
        let h = 16u32;
        let pixels: Vec<Rgba<u8>> = (0..w * h)
            .map(|i| Rgba {
                r: (i % 256) as u8,
                g: ((i * 3) % 256) as u8,
                b: ((i * 7) % 256) as u8,
                a: 255,
            })
            .collect();
        let img = Img::new(pixels, w as usize, h as usize);

        // push_rows path
        let config = PngEncoderConfig::new().with_generic_effort(3);
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        for y in (0..h).step_by(4) {
            let rows = (h - y).min(4);
            let strip = img.sub_image(0, y as usize, w as usize, rows as usize);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let push_out = encoder.finish().unwrap();

        // encode() path
        let one_enc = config.clone().job().encoder().unwrap();
        let one_out = one_enc
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();

        // Should decode to identical pixels
        let dec_push = crate::decode(
            push_out.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        let dec_one = crate::decode(
            one_out.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(
            dec_push.pixels.copy_to_contiguous_bytes(),
            dec_one.pixels.copy_to_contiguous_bytes()
        );
    }

    #[test]
    fn push_rows_caps_advertised() {
        use zencodec::encode::EncoderConfig;

        let caps = PngEncoderConfig::capabilities();
        assert!(caps.supports(zencodec::UnsupportedOperation::RowLevelEncode));
    }

    #[test]
    fn push_rows_infer_canvas_width() {
        // If canvas_size not set, width inferred from first push
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 4u32;
        let h = 2u32;
        let pixels: Vec<Rgb<u8>> = vec![
            Rgb {
                r: 100,
                g: 100,
                b: 100,
            };
            (w * h) as usize
        ];
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new();
        let mut encoder = config.clone().job().encoder().unwrap(); // no with_canvas_size
        encoder
            .push_rows(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);
    }

    // ── True streaming (effort 0) tests ─────────────────────────────

    #[test]
    fn streaming_effort0_rgb8_roundtrip() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 4u32;
        let h = 6u32;
        let pixels: Vec<Rgb<u8>> = (0..w * h)
            .map(|i| Rgb {
                r: (i * 7) as u8,
                g: (i * 13) as u8,
                b: (i * 19) as u8,
            })
            .collect();
        let img = Img::new(pixels.clone(), w as usize, h as usize);

        // Effort 0 → true streaming path
        let config = PngEncoderConfig::new().with_compression(crate::Compression::None);
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        for strip_y in (0..h).step_by(2) {
            let strip = img.sub_image(0, strip_y as usize, w as usize, 2);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let output = encoder.finish().unwrap();

        // Decode and verify pixel-exact
        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);

        // Compare with one-shot encode at effort 0
        let oneshot = config
            .job()
            .encoder()
            .unwrap()
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        let decoded_one = crate::decode(
            oneshot.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(
            decoded.pixels.copy_to_contiguous_bytes(),
            decoded_one.pixels.copy_to_contiguous_bytes()
        );
    }

    #[test]
    fn streaming_effort0_rgba8_single_row() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 3u32;
        let h = 4u32;
        let pixels: Vec<Rgba<u8>> = (0..w * h)
            .map(|i| Rgba {
                r: (i * 5) as u8,
                g: (i * 11) as u8,
                b: (i * 17) as u8,
                a: 200,
            })
            .collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new().with_compression(crate::Compression::None);
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        for y in 0..h {
            let strip = img.sub_image(0, y as usize, w as usize, 1);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);
    }

    #[test]
    fn streaming_effort0_gray8() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 8u32;
        let h = 4u32;
        let pixels: Vec<Gray<u8>> = (0..w * h).map(|i| Gray(i as u8)).collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new().with_compression(crate::Compression::None);
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        encoder
            .push_rows(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);
    }

    #[test]
    fn streaming_effort0_matches_oneshot_effort0() {
        // True streaming at effort 0 should produce byte-identical output
        // to one-shot encode at effort 0 (both use stored DEFLATE + None filter).
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 16u32;
        let h = 12u32;
        let pixels: Vec<Rgb<u8>> = (0..w * h)
            .map(|i| Rgb {
                r: (i * 3 + 7) as u8,
                g: (i * 5 + 11) as u8,
                b: (i * 7 + 13) as u8,
            })
            .collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new().with_compression(crate::Compression::None);

        // One-shot encode
        let oneshot = config
            .clone()
            .job()
            .encoder()
            .unwrap()
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();

        // Streaming encode (3 rows at a time)
        let mut encoder = config.job().with_canvas_size(w, h).encoder().unwrap();
        for strip_y in (0..h).step_by(3) {
            let strip_h = (h - strip_y).min(3);
            let strip = img.sub_image(0, strip_y as usize, w as usize, strip_h as usize);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let streaming = encoder.finish().unwrap();

        // Byte-identical output
        assert_eq!(oneshot.data(), streaming.data());
    }

    #[test]
    fn streaming_effort0_large_row() {
        // Test rows that exceed 65535 bytes (stored block boundary).
        // 16384 × 4 = 65536 bytes per row → must split across blocks.
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 16384u32;
        let h = 2u32;
        // Use non-opaque alpha to prevent auto-optimization (RGBA→RGB strip)
        let pixels: Vec<Rgba<u8>> = (0..w * h)
            .map(|i| Rgba {
                r: (i % 251) as u8,
                g: (i % 241) as u8,
                b: (i % 239) as u8,
                a: 200,
            })
            .collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new().with_compression(crate::Compression::None);
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        for y in 0..h {
            let strip = img.sub_image(0, y as usize, w as usize, 1);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);

        // Verify byte-identical with one-shot (both RGBA, no auto-opt)
        let oneshot = config
            .job()
            .encoder()
            .unwrap()
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        assert_eq!(oneshot.data(), output.data());
    }

    #[test]
    fn streaming_effort0_fallback_without_canvas_height() {
        // Without canvas_height, effort 0 should fall back to buffered mode
        // (can't pre-compute IDAT size), but still produce valid output.
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 4u32;
        let h = 3u32;
        let pixels: Vec<Rgb<u8>> = vec![
            Rgb {
                r: 50,
                g: 100,
                b: 150,
            };
            (w * h) as usize
        ];
        let img = Img::new(pixels, w as usize, h as usize);

        // Only set width, not height → falls back to buffered
        let config = PngEncoderConfig::new().with_compression(crate::Compression::None);
        let mut encoder = config.clone().job().encoder().unwrap(); // no with_canvas_size
        encoder
            .push_rows(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);
    }

    // ── Pre-filtered streaming (effort 1) tests ─────────────────────

    #[test]
    fn streaming_effort1_rgb8_roundtrip() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 8u32;
        let h = 6u32;
        let pixels: Vec<Rgb<u8>> = (0..w * h)
            .map(|i| Rgb {
                r: (i * 7) as u8,
                g: (i * 13) as u8,
                b: (i * 19) as u8,
            })
            .collect();
        let img = Img::new(pixels.clone(), w as usize, h as usize);

        let config = PngEncoderConfig::new().with_compression(crate::Compression::Fastest);
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        for strip_y in (0..h).step_by(2) {
            let strip = img.sub_image(0, strip_y as usize, w as usize, 2);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);

        // Pixel-exact match with one-shot
        let oneshot = config
            .job()
            .encoder()
            .unwrap()
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        let decoded_one = crate::decode(
            oneshot.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(
            decoded.pixels.copy_to_contiguous_bytes(),
            decoded_one.pixels.copy_to_contiguous_bytes()
        );
    }

    #[test]
    fn streaming_effort1_matches_oneshot_bytes() {
        // Pre-filtered streaming at effort 1 should produce byte-identical
        // output to one-shot encode at effort 1 (both use Paeth + Turbo).
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 12u32;
        let h = 8u32;
        let pixels: Vec<Rgb<u8>> = (0..w * h)
            .map(|i| Rgb {
                r: (i * 3 + 7) as u8,
                g: (i * 5 + 11) as u8,
                b: (i * 7 + 13) as u8,
            })
            .collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new().with_compression(crate::Compression::Fastest);

        let oneshot = config
            .clone()
            .job()
            .encoder()
            .unwrap()
            .encode(PixelSlice::from(img.as_ref()).erase())
            .unwrap();

        let mut encoder = config.job().with_canvas_size(w, h).encoder().unwrap();
        for strip_y in (0..h).step_by(3) {
            let strip_h = (h - strip_y).min(3);
            let strip = img.sub_image(0, strip_y as usize, w as usize, strip_h as usize);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let streaming = encoder.finish().unwrap();

        // Byte-identical (no auto-opt for RGB)
        assert_eq!(oneshot.data(), streaming.data());
    }

    #[test]
    fn streaming_effort1_smaller_than_effort0() {
        // Effort 1 (Paeth + Turbo) should compress better than effort 0 (None + Store).
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 64u32;
        let h = 64u32;
        // Smooth gradient compresses well with Paeth
        let pixels: Vec<Rgb<u8>> = (0..w * h)
            .map(|i| {
                let x = (i % w) as u8;
                let y = (i / w) as u8;
                Rgb {
                    r: x,
                    g: y,
                    b: x.wrapping_add(y),
                }
            })
            .collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config0 = PngEncoderConfig::new().with_compression(crate::Compression::None);
        let config1 = PngEncoderConfig::new().with_compression(crate::Compression::Fastest);

        let mut enc0 = config0.job().with_canvas_size(w, h).encoder().unwrap();
        let mut enc1 = config1.job().with_canvas_size(w, h).encoder().unwrap();

        enc0.push_rows(PixelSlice::from(img.as_ref()).erase())
            .unwrap();
        enc1.push_rows(PixelSlice::from(img.as_ref()).erase())
            .unwrap();

        let out0 = enc0.finish().unwrap();
        let out1 = enc1.finish().unwrap();

        assert!(
            out1.data().len() < out0.data().len(),
            "effort 1 ({}) should be smaller than effort 0 ({})",
            out1.data().len(),
            out0.data().len()
        );
    }

    #[test]
    fn streaming_effort1_rgba8_single_row() {
        use zencodec::encode::{EncodeJob, Encoder, EncoderConfig};

        let w = 5u32;
        let h = 4u32;
        let pixels: Vec<Rgba<u8>> = (0..w * h)
            .map(|i| Rgba {
                r: (i * 5) as u8,
                g: (i * 11) as u8,
                b: (i * 17) as u8,
                a: 200,
            })
            .collect();
        let img = Img::new(pixels, w as usize, h as usize);

        let config = PngEncoderConfig::new().with_compression(crate::Compression::Fastest);
        let mut encoder = config
            .clone()
            .job()
            .with_canvas_size(w, h)
            .encoder()
            .unwrap();
        for y in 0..h {
            let strip = img.sub_image(0, y as usize, w as usize, 1);
            encoder.push_rows(PixelSlice::from(strip).erase()).unwrap();
        }
        let output = encoder.finish().unwrap();

        let decoded = crate::decode(
            output.data(),
            &crate::PngDecodeConfig::strict(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, w);
        assert_eq!(decoded.info.height, h);
    }

    // ── Fix verification tests ──

    #[test]
    fn output_info_returns_gray8_for_grayscale_png() {
        // Encode a grayscale image
        let pixels: Vec<Gray<u8>> = vec![Gray(128); 16];
        let img = Img::new(pixels, 4, 4);
        let enc = PngEncoderConfig::new();
        let output = enc.encode_gray8(img.as_ref()).unwrap();

        // output_info() should report GRAY8_SRGB, not RGB8_SRGB
        let dec = PngDecoderConfig::new();
        let info = dec.job().output_info(output.data()).unwrap();
        assert_eq!(info.width, 4);
        assert_eq!(info.height, 4);
        assert_eq!(
            info.native_format,
            PixelDescriptor::GRAY8_SRGB,
            "grayscale PNG should report GRAY8_SRGB, not {:?}",
            info.native_format
        );
    }

    #[test]
    fn output_info_returns_gray16_for_grayscale16_png() {
        // Encode a 16-bit grayscale image.
        // Use a value with non-zero low byte (32769 = 0x8001) to prevent
        // the optimizer from reducing it to 8-bit.
        let pixels: Vec<Gray<u16>> = vec![Gray(32769); 16];
        let img = Img::new(pixels, 4, 4);
        let enc = PngEncoderConfig::new();
        let output = enc.encode_gray16(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let info = dec.job().output_info(output.data()).unwrap();
        assert_eq!(
            info.native_format,
            PixelDescriptor::GRAY16_SRGB,
            "16-bit grayscale PNG should report GRAY16_SRGB, not {:?}",
            info.native_format
        );
    }

    #[test]
    fn output_info_returns_rgb8_for_rgb_png() {
        // Encode an RGB image
        let pixels: Vec<Rgb<u8>> = vec![
            Rgb {
                r: 100,
                g: 150,
                b: 200,
            };
            16
        ];
        let img = Img::new(pixels, 4, 4);
        let enc = PngEncoderConfig::new();
        let output = enc.encode_rgb8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let info = dec.job().output_info(output.data()).unwrap();
        assert_eq!(
            info.native_format,
            PixelDescriptor::RGB8_SRGB,
            "RGB PNG should report RGB8_SRGB, not {:?}",
            info.native_format
        );
    }

    #[test]
    fn output_info_returns_rgba8_for_rgba_png() {
        let pixels: Vec<Rgba<u8>> = vec![
            Rgba {
                r: 100,
                g: 150,
                b: 200,
                a: 128,
            };
            16
        ];
        let img = Img::new(pixels, 4, 4);
        let enc = PngEncoderConfig::new();
        let output = enc.encode_rgba8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let info = dec.job().output_info(output.data()).unwrap();
        assert_eq!(
            info.native_format,
            PixelDescriptor::RGBA8_SRGB,
            "RGBA PNG should report RGBA8_SRGB, not {:?}",
            info.native_format
        );
    }

    #[test]
    fn apng_finish_respects_stop_token() {
        use enough::{Stop, StopReason};
        use zencodec::encode::AnimationFrameEncoder;

        /// A Stop that always says "stop now".
        struct AlreadyCancelled;
        impl Stop for AlreadyCancelled {
            fn check(&self) -> Result<(), StopReason> {
                Err(StopReason::Cancelled)
            }
        }

        let config = PngEncoderConfig::new();
        let job = config
            .clone()
            .job()
            .with_canvas_size(4, 4)
            .with_loop_count(Some(0));
        let mut enc = job.animation_frame_encoder().unwrap();

        // Push one frame
        let pixels: Vec<Rgba<u8>> = vec![
            Rgba {
                r: 0,
                g: 0,
                b: 0,
                a: 255,
            };
            16
        ];
        let img = imgref::ImgVec::new(pixels, 4, 4);
        enc.push_frame(PixelSlice::from(img.as_ref()).erase(), 100, None)
            .unwrap();

        // finish() with a cancelled stop token should fail
        let result = enc.finish(Some(&AlreadyCancelled));
        assert!(result.is_err(), "finish with cancelled stop should fail");
        match result.unwrap_err().decompose().0 {
            PngError::Stopped(reason) => {
                assert_eq!(reason, StopReason::Cancelled);
            }
            other => panic!("expected PngError::Stopped, got: {other}"),
        }
    }

    #[test]
    fn apng_finish_succeeds_without_stop_token() {
        use zencodec::encode::AnimationFrameEncoder;

        let config = PngEncoderConfig::new();
        let job = config
            .clone()
            .job()
            .with_canvas_size(4, 4)
            .with_loop_count(Some(0));
        let mut enc = job.animation_frame_encoder().unwrap();

        let pixels: Vec<Rgba<u8>> = vec![
            Rgba {
                r: 255,
                g: 0,
                b: 0,
                a: 255,
            };
            16
        ];
        let img = imgref::ImgVec::new(pixels, 4, 4);
        enc.push_frame(PixelSlice::from(img.as_ref()).erase(), 100, None)
            .unwrap();

        // finish() without stop token should succeed
        let result = enc.finish(None);
        assert!(
            result.is_ok(),
            "finish without stop should succeed: {:?}",
            result.err()
        );
    }

    #[test]
    fn apng_pixels_to_rgba8_rejects_unsupported_format() {
        use zencodec::encode::AnimationFrameEncoder;

        let config = PngEncoderConfig::new();
        let job = config
            .clone()
            .job()
            .with_canvas_size(4, 4)
            .with_loop_count(Some(0));
        let mut enc = job.animation_frame_encoder().unwrap();

        // Try pushing a 16-bit frame, which is not supported by the APNG encoder
        let pixels: Vec<Rgba<u16>> = vec![
            Rgba {
                r: 1000,
                g: 2000,
                b: 3000,
                a: 65535,
            };
            16
        ];
        let img = imgref::ImgVec::new(pixels, 4, 4);
        let result = enc.push_frame(PixelSlice::from(img.as_ref()).erase(), 100, None);
        assert!(result.is_err(), "16-bit RGBA should be rejected");
        let msg = alloc::format!("{}", result.unwrap_err());
        assert!(
            msg.contains("unsupported pixel format"),
            "error should mention unsupported pixel format, got: {msg}"
        );
        assert!(
            msg.contains("RGBA8") || msg.contains("supported formats"),
            "error should list supported formats, got: {msg}"
        );
    }

    #[test]
    fn apng_pixels_to_rgba8_handles_gray8() {
        use zencodec::encode::AnimationFrameEncoder;

        let config = PngEncoderConfig::new();
        let job = config
            .clone()
            .job()
            .with_canvas_size(4, 4)
            .with_loop_count(Some(0));
        let mut enc = job.animation_frame_encoder().unwrap();

        // Push a Gray8 frame — should be accepted and converted to RGBA8
        let pixels: Vec<Gray<u8>> = vec![Gray(128); 16];
        let img = imgref::ImgVec::new(pixels, 4, 4);
        enc.push_frame(PixelSlice::from(img.as_ref()).erase(), 100, None)
            .unwrap();

        // Finish and verify it produces valid output
        let output = enc.finish(None).unwrap();
        assert!(!output.data().is_empty());
        assert_eq!(output.format(), ImageFormat::Png);

        // Verify round-trip: decode and check pixel values
        let decoded = crate::decode::decode(
            output.data(),
            &PngDecodeConfig::none(),
            &enough::Unstoppable,
        )
        .unwrap();
        assert_eq!(decoded.info.width, 4);
        assert_eq!(decoded.info.height, 4);
    }

    /// Decoding an RGB-only PNG into an RGBA8/BGRA8 target must flag the
    /// output descriptor's alpha mode as `Opaque` — the alpha bytes were
    /// synthesized (all 0xFF) by the conversion, not carried by the source.
    #[test]
    fn decode_rgb_source_to_bgra8_reports_opaque_alpha() {
        use zenpixels::AlphaMode;

        let enc = PngEncoderConfig::new();
        let pixels = vec![
            Rgb {
                r: 10u8,
                g: 20,
                b: 30,
            };
            16
        ];
        let img = Img::new(pixels, 4, 4);
        let encoded = enc.encode_rgb8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let job = dec.job();
        let decoder = job
            .decoder(
                alloc::borrow::Cow::Borrowed(encoded.data()),
                &[PixelDescriptor::BGRA8_SRGB],
            )
            .unwrap();
        let out = decoder.decode().unwrap();
        assert!(!out.info().has_alpha, "container reports no alpha source");
        let desc = out.into_buffer().descriptor();
        assert_eq!(desc.alpha(), Some(AlphaMode::Opaque));
        assert_eq!(
            desc.pixel_format(),
            PixelDescriptor::BGRA8_SRGB.pixel_format()
        );
    }

    /// Decoding an RGBA source (with real alpha variation) keeps the
    /// descriptor's alpha mode as `Straight` — we don't scan pixels, only
    /// use container-level information.
    #[test]
    fn decode_rgba_source_keeps_straight_alpha_without_scan() {
        use zenpixels::AlphaMode;

        let enc = PngEncoderConfig::new();
        // Vary alpha so the encoder can't downcast to indexed/RGB.
        let mut pixels: Vec<Rgba<u8>> = Vec::with_capacity(16);
        for i in 0..16u8 {
            pixels.push(Rgba {
                r: i.wrapping_mul(17),
                g: 20,
                b: 30,
                a: if i == 0 { 128 } else { 255 },
            });
        }
        let img = Img::new(pixels, 4, 4);
        let encoded = enc.encode_rgba8(img.as_ref()).unwrap();

        let dec = PngDecoderConfig::new();
        let job = dec.job();
        let decoder = job
            .decoder(
                alloc::borrow::Cow::Borrowed(encoded.data()),
                &[PixelDescriptor::BGRA8_SRGB],
            )
            .unwrap();
        let out = decoder.decode().unwrap();
        assert!(out.info().has_alpha);
        assert_eq!(
            out.into_buffer().descriptor().alpha(),
            Some(AlphaMode::Straight),
        );
    }
}