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
/*
 * // Copyright (c) Radzivon Bartoshyk 5/2026. All rights reserved.
 * //
 * // Redistribution and use in source and binary forms, with or without modification,
 * // are permitted provided that the following conditions are met:
 * //
 * // 1.  Redistributions of source code must retain the above copyright notice, this
 * // list of conditions and the following disclaimer.
 * //
 * // 2.  Redistributions in binary form must reproduce the above copyright notice,
 * // this list of conditions and the following disclaimer in the documentation
 * // and/or other materials provided with the distribution.
 * //
 * // 3.  Neither the name of the copyright holder nor the names of its
 * // contributors may be used to endorse or promote products derived from
 * // this software without specific prior written permission.
 * //
 * // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
use crate::bit_writer::BitWriter;
use crate::coder_scratch::CoderScratch;
use crate::coding::CodingTransform;
use crate::color::{
    ColorTransform, FloatTransferDecoder, RgbBlockTransform, TransferDecoder, TransferLut,
};
use crate::color_encoding::write_color_encoding_with_icc;
use crate::encoding_context::EncodingContext;
use crate::frame::encode_frame;
use crate::gain_map::{EncodedGainMap, GainMap, encode_gain_map};
use crate::image::{Image3F, Image3Si};
use crate::jpeg::BrotliCompression;
use crate::lossless::{encode_frame_lossless, encode_frame_lossless_float, forward_ycocg};
use crate::orientation::Orientation;
use crate::xyb::XybMatrix;
use crate::{ColorEncoding, EncodeError};
use std::num::NonZero;
use std::sync::Arc;
use std::thread::available_parallelism;

pub(crate) fn checked_buffer_size<T>(
    width: usize,
    height: usize,
    channels: usize,
) -> Result<usize, EncodeError> {
    let pixel_size = size_of::<T>();
    let total_size = width
        .checked_mul(height)
        .and_then(|v| v.checked_mul(channels));

    _ = total_size
        .and_then(|v| v.checked_mul(pixel_size))
        .and_then(|v| isize::try_from(v).ok())
        .map(|v| v as usize)
        .ok_or(EncodeError::DimensionTooLarge {
            width: height,
            height,
        })?;

    total_size
        .and_then(|v| isize::try_from(v).ok())
        .map(|v| v as usize)
        .ok_or(EncodeError::DimensionTooLarge {
            width: height,
            height,
        })
}

/// 8-bit alpha plane (row-major, stride = `xsize`).
#[derive(Debug, Clone)]
pub(crate) enum AlphaPlane {
    /// 8-bit alpha, values 0..=255.
    U8(Vec<u8>),
    /// 10-bit (`bits=10`, values 0..=1023) or 12-bit (`bits=12`, values 0..=4095) alpha.
    U16 { data: Vec<u16>, bits: u8 },
    /// IEEE-754 single-precision alpha, stored as the raw 32-bit float bits
    /// reinterpreted as `i32` (matching libjxl's float_to_int for 32-bit float).
    F32(Vec<i32>),
}

/// Codestream marker byte that follows the leading 0xFF. Identifies this as
/// a raw JXL codestream (vs an ISOBMFF-wrapped one).
const CODESTREAM_MARKER: u8 = 0x0A;

/// Practical lower bound for lossy encoding; lossless bypasses this clamp.
pub(crate) const MIN_DISTANCE: f32 = 0.05;

/// JXL's image dimension field encodes (size - 1) in either 9, 13, 18, or
/// 30 bits, so 2^30 is the largest representable dimension.
pub(crate) const MAX_DIMENSION: usize = 0x3FFF_FFFF;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum BitsPerSample {
    #[default]
    Eight,
    Ten,
    Twelve,
    Sixteen,
    /// IEEE-754 half (16-bit, 5 exponent bits). Lossy only.
    F16,
    /// IEEE-754 single (32-bit, 8 exponent bits). Lossy only.
    F32,
}

impl BitsPerSample {
    pub(crate) fn bits(self) -> u32 {
        match self {
            BitsPerSample::Eight => 8,
            BitsPerSample::Ten => 10,
            BitsPerSample::Twelve => 12,
            BitsPerSample::Sixteen => 16,
            BitsPerSample::F16 => 16,
            BitsPerSample::F32 => 32,
        }
    }

    /// True for IEEE-754 float sample formats (f16/f32).
    pub(crate) fn is_float(self) -> bool {
        matches!(self, BitsPerSample::F16 | BitsPerSample::F32)
    }

    /// Number of exponent bits (5 for f16, 8 for f32); 0 for integer formats.
    pub(crate) fn exp_bits(self) -> u32 {
        match self {
            BitsPerSample::F16 => 5,
            BitsPerSample::F32 => 8,
            _ => 0,
        }
    }
}

impl AlphaPlane {
    /// Create an 8-bit alpha plane.
    #[inline]
    pub(crate) fn from_u8(data: Vec<u8>) -> Self {
        Self::U8(data)
    }

    /// Create a 10-bit alpha plane (values 0..=1023).
    #[inline]
    pub(crate) fn from_u16_10bit(data: Vec<u16>) -> Self {
        Self::U16 { data, bits: 10 }
    }

    /// Create a 12-bit alpha plane (values 0..=4095).
    #[inline]
    pub(crate) fn from_u16_12bit(data: Vec<u16>) -> Self {
        Self::U16 { data, bits: 12 }
    }

    /// Create a 16-bit alpha plane (values 0..=65535).
    #[inline]
    pub(crate) fn from_u16_16bit(data: Vec<u16>) -> Self {
        Self::U16 { data, bits: 16 }
    }

    /// Number of pixels.
    #[inline]
    pub(crate) fn len(&self) -> usize {
        match self {
            Self::U8(v) => v.len(),
            Self::U16 { data, .. } => data.len(),
            Self::F32(v) => v.len(),
        }
    }

    /// Bit depth of the alpha samples (8, 10, or 12).
    #[inline]
    pub(crate) fn bits(&self) -> u8 {
        match self {
            Self::U8(_) => 8,
            Self::U16 { bits, .. } => *bits,
            Self::F32(_) => 32,
        }
    }

    /// True if the alpha samples are IEEE-754 float (stored as raw bits).
    #[inline]
    pub(crate) fn is_float(&self) -> bool {
        matches!(self, Self::F32(_))
    }

    /// Read pixel `idx` as `i32`.  Encoder hot path — kept tiny for inlining.
    #[inline]
    pub(crate) fn get_i32(&self, idx: usize) -> i32 {
        match self {
            Self::U8(v) => v[idx] as i32,
            Self::U16 { data, .. } => data[idx] as i32,
            Self::F32(v) => v[idx],
        }
    }
}

/// The JXL ToneMapping bundle (HDR luminance metadata). All fields are
/// optional refinements on top of the SDR defaults; set them for fuller
/// mastering metadata. Constraints (enforced by decoders): `intensity_target`
/// must be > 0 and `0 <= min_nits <= intensity_target`.
#[derive(Debug, Clone, Copy)]
pub(crate) struct ToneMappingParams {
    /// Peak display luminance in nits. `None` keeps the 255-nit SDR default.
    pub intensity_target: Option<f32>,
    /// Minimum display luminance (mastering black level) in nits. Default 0.
    pub min_nits: f32,
    /// If true, sample values are relative to the max display luminance. Default false.
    pub relative_to_max_display: bool,
    /// Luminance below which the transfer is linear. Relative (0..1) when
    /// `relative_to_max_display`, otherwise in nits. Default 0.
    pub linear_below: f32,
}

impl ToneMappingParams {
    /// True when every field is at its JXL default (no ToneMapping bundle needed).
    fn is_default(&self) -> bool {
        self.intensity_target.is_none()
            && self.min_nits == 0.0
            && !self.relative_to_max_display
            && self.linear_below == 0.0
    }
}

/// Encoder speed/density tradeoff, ordered from fastest to densest.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[non_exhaustive]
pub enum Speed {
    /// No transform search at all: every block is coded as a plain 8×8 DCT
    /// with the cheapest entropy coding. Skips everything `Fastest` skips.
    UltraFast,
    /// 16×16 merges on quiet blocks only, prefix-clustered contexts and the
    /// DC predictor choice; none of `Fast`'s quantizer refinement, learned DC
    /// tree, or entropy-code refinement. Lossless is coded as at `Fast`.
    Fastest,
    /// Square transforms only; lossless uses no learned context trees.
    #[default]
    Fast,
    /// The full transform search and color tools of `Slow` without its
    /// costliest coding refinements; lossless learns its context tree from a
    /// smaller sample and skips the predictor-preset ranking.
    Medium,
    /// Every coding tool with the standard search budget.
    Slow,
    /// All `Slow` tools with stronger final ANS entropy search for lossy and
    /// lossless encoding, additional lossless LZ77 candidates, and wider
    /// large-transform quantization search at distance >= 3.
    ExtraSlow,
}

/// The perceptual metric whose preferences settle the **lossy** encoder's
/// decisions where metrics disagree. Ignored for lossless.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
#[non_exhaustive]
pub enum Arbiter {
    /// SSIMULACRA2.
    #[default]
    Ssimulacra2,
    /// ColorVideoVDP
    Cvvdp,
}

/// Decode-speed/density tradeoff for **lossless** encoding. Ignored for lossy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum DecodingSpeed {
    /// No Weighted Predictor and no meta-adaptive context trees
    Fastest,
    /// No Weighted Predictor.
    Fast,
    /// All coding tools; densest output, slowest to decode.
    #[default]
    Slow,
}

impl DecodingSpeed {
    /// Whether the emitted stream may use the Weighted Predictor (and the
    /// WP-error tree property, which also forces decoder-side WP state).
    pub(crate) fn use_weighted_predictor(self) -> bool {
        matches!(self, DecodingSpeed::Slow)
    }

    /// Whether the encoder may signal per-pixel meta-adaptive context trees.
    pub(crate) fn use_ma_trees(self) -> bool {
        !matches!(self, DecodingSpeed::Fastest)
    }
}

#[derive(Debug, Clone)]
pub struct EncodeConfig {
    /// Positive, finite lossy distance, clamped to a minimum of 0.05.
    /// Ignored when `lossless` is true.
    pub distance: f32,
    pub color_encoding: ColorEncoding,
    pub icc_profile: Option<Vec<u8>>,
    /// EXIF/TIFF metadata to embed via an `Exif` container box. Forces the
    /// output into the JXL container form. Raw TIFF bytes (no "Exif\0\0" prefix).
    pub exif: Option<Vec<u8>>,
    /// XMP packet to embed via an `xml ` container box, or a `brob` box when a
    /// Brotli implementation is supplied. Forces the output into container form.
    pub xmp: Option<Vec<u8>>,
    /// Optional Brotli encoder for EXIF and XMP metadata boxes.
    ///
    /// When set, metadata is emitted in `brob` boxes. When absent, it remains
    /// in uncompressed `Exif` and `xml ` boxes.
    pub brotli_compression: Option<Arc<dyn BrotliCompression>>,
    /// Image orientation: how the decoder should rotate/flip the stored pixels
    /// for display (default [`Orientation::Normal`]).
    pub orientation: Orientation,
    /// If true, encode losslessly via the modular encoder. `distance` is then
    /// ignored. RGB and alpha both round-trip bit-perfectly.
    pub lossless: bool,
    /// Smooth color samples underneath fully transparent pixels before lossy
    /// encoding, using libjxl's neighbor fill. Alpha and partially transparent
    /// source samples are unchanged by this preprocessing. Defaults to true.
    /// Ignored for lossless encoding and CMYK images.
    pub fill_invisible: bool,
    /// If true (and lossless), use the progressive Squeeze transform: a low-res
    /// preview that refines to bit-exact. Works at any size (single- and
    /// multi-group) and with alpha.
    ///
    /// For lossy (`!lossless`) encoding, `true` selects 2-pass progressive
    /// VarDCT (equivalent to `progressive_passes = Some(2)`).
    pub progressive: bool,
    /// Encode repeated content through the JPEG XL patch dictionary: glyphs
    /// and other small marks on flat backgrounds at any position, and
    /// repeated grid-aligned tiles. Supported for both lossless Modular and
    /// lossy VarDCT encoding. Lossless keeps patches only when they reduce
    /// the final size; lossy takes a plan on its coverage, since the patched
    /// frame is also the sharper one, and photographic content finds none.
    pub patches: bool,
    /// Experimental: detect thin curvilinear structures (wires, veins, ink
    /// lines) and code them as JPEG XL splines next to the lossy VarDCT image.
    /// Every spline passes a rate-distortion test against the VarDCT cost of
    /// the same pixels. Slow speed and the default decoding speed only; costs
    /// encode time and some decode time.
    /// Requires the `splines` Cargo feature. Defaults to false.
    #[cfg(feature = "splines")]
    pub splines: bool,
    /// Experimental: detect isolated bright or dark spots and code them as
    /// signed Gaussian dots drawn from a small template atlas (additive
    /// patches), next to the lossy VarDCT image. Dots, templates and the whole
    /// set pass rate-distortion tests; unprofitable sets fall back to VarDCT.
    /// Slow speed and the default decoding speed only; costs encode time.
    /// Requires the `splines` Cargo feature. Defaults to false.
    #[cfg(feature = "splines")]
    pub dots: bool,
    /// Number of VarDCT passes for **lossy** progressive encoding. `None` falls
    /// back to `progressive` (2 passes if set, else 1). `Some(1)` = single pass;
    /// `Some(n)` for n in 2..=4 = n-pass progressive with an automatic
    /// coarse-to-fine bit-shift schedule (`[n-1, .., 1, 0]`). Values above 4 are
    /// clamped (the per-pass shift field is 2 bits with no downsampling).
    /// Ignored when `lossless`. Overridden by `progressive_shifts` if set.
    pub progressive_passes: Option<u32>,
    /// Explicit per-pass coefficient-shift schedule for lossy progressive
    /// encoding, overriding `progressive_passes`. The length is the pass count;
    /// each entry is the decoder left-shift for that pass (0..=3). A larger
    /// pass-0 shift makes the first (preview) pass smaller and coarser. Must end
    /// in 0 and contain only values 0..=3; otherwise it is ignored. Examples:
    /// `[1,0]` (default 2-pass), `[2,0]` / `[3,0]` (coarser thumbnail then full),
    /// `[2,1,0]` (3-step ramp). Ignored when `lossless`.
    pub progressive_shifts: Option<Vec<u32>>,
    /// HDR luminance signaling. When `Some(nits)`, the codestream's tone-mapping
    /// metadata declares this peak display luminance (`intensity_target`), e.g.
    /// `10000.0` for PQ/HDR10 or a measured mastering peak. `None` leaves the
    /// SDR default. Must be > 0.
    pub intensity_target: Option<f32>,
    /// HDR mastering black level in nits (ToneMapping `min_nits`). Default 0.
    pub min_nits: f32,
    /// ToneMapping `relative_to_max_display`. Default false.
    pub relative_to_max_display: bool,
    /// ToneMapping `linear_below` (nits, or 0..1 if relative). Default 0.
    pub linear_below: f32,
    pub num_threads: usize,
    pub speed: Speed,
    /// Metric the lossy encoder tunes for (see [`Arbiter`]). Default
    /// [`Arbiter::Ssimulacra2`].
    pub arbiter: Arbiter,
    /// Decode-speed/density tradeoff for lossless encoding (see
    /// [`DecodingSpeed`]). Ignored for lossy.
    pub decoding_speed: DecodingSpeed,
    /// Lossy encoding arm selection (see [`LossyModular`]). Default `Off`.
    pub lossy_modular: LossyModular,
    /// Progressive DC for lossy VarDCT: the 1:8 DC image is coded as its own
    /// squeezed modular frame ahead of the main frame, so a decoder can show
    /// previews refining from 1:256 to 1:8 before any AC data arrives.
    /// Costs some size. XYB frames without alpha only; other frames ignore it.
    /// Defaults to false.
    pub progressive_dc: bool,
    /// Squeeze levels of the progressive DC frame, finest first; each level
    /// halves the preview resolution. `None` (default) squeezes down to an
    /// 8x8 preview. `Some(n)` keeps the `n` finest levels, clamped to between
    /// one and the most the image allows; fewer levels give fewer, larger
    /// previews. A single level costs noticeably more size; two or more cost
    /// about the same as the full pyramid. Used only with `progressive_dc`.
    pub progressive_dc_levels: Option<u32>,
    /// Codestream order of the lossy VarDCT groups (see [`GroupOrder`]).
    /// Default [`GroupOrder::Scanline`].
    pub group_order: GroupOrder,
    /// Choose VarDCT transforms by what each candidate costs under the
    /// image's own coefficient statistics instead of a fixed rate model.
    /// Patterned and synthetic content compresses much better; photographs
    /// are about unchanged. Takes effect at [`Speed::Slow`] and above, where it
    /// costs encode time. Defaults to true.
    pub learned_rate: bool,
    /// Optional HDR gain map (see [`GainMap`]). When set, the gain map is
    /// encoded as a second JPEG XL codestream and shipped in a `jhgm`
    /// container box together with its ISO 21496-1 metadata. Forces the
    /// output into the JXL container form.
    pub gain_map: Option<GainMap>,
    /// Color transform of lossy frames (see [`CodingTransform`]).
    pub coding_transform: CodingTransform,
}

/// Order in which a lossy VarDCT frame stores its groups. A progressive
/// decoder renders groups as they arrive, so this is the order the image
/// fills in. Costs a few bytes for the signaled permutation; the pixels are
/// identical.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GroupOrder {
    /// Row by row from the top left (the default).
    #[default]
    Scanline,
    /// Rings around the image center, each swept clockwise from the top;
    /// with several passes, every pass fills in from the center again.
    CenterFirst,
    /// Both corner-to-corner diagonals first, growing out from the center,
    /// then bands ever farther from them: the image draws an X that
    /// thickens until it fills the frame.
    Diagonals,
}

/// Which arm the **lossy** encoder uses. Besides VarDCT, jixel carries a lossy
/// modular arm (quantized Squeeze pyramid): multi-resolution residual coding
/// that outperforms block DCT on smooth/gradient-heavy content, most clearly
/// from medium quality down.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LossyModular {
    /// VarDCT only (the default).
    #[default]
    Off,
    /// Encode BOTH arms per frame — the modular arm at a distance calibrated
    /// to match the VarDCT arm's quality — and keep the smaller frame.
    /// [`Speed::Slow`] and above (falls back to VarDCT otherwise).
    Auto,
    /// Always use the modular arm when the frame supports it (XYB: RGB
    /// without alpha; other coding transforms: any integer image, gray, CMYK
    /// and alpha included; all above tiny sizes); other frames fall back to
    /// VarDCT.
    Force,
}

#[derive(Debug, Clone)]
pub(crate) struct EncodeConfigImpl {
    pub(crate) distance: f32,
    pub(crate) color_encoding: ColorEncoding,
    pub(crate) icc_profile: Option<Vec<u8>>,
    pub(crate) exif: Option<Vec<u8>>,
    pub(crate) xmp: Option<Vec<u8>>,
    pub(crate) brotli_compression: Option<Arc<dyn BrotliCompression>>,
    pub(crate) orientation: Orientation,
    pub(crate) alpha: Option<AlphaPlane>,
    /// The `alpha` plane is the K channel of a CMYK image (kBlack).
    pub(crate) black: bool,
    /// Bit depth declared in the codestream (default: 8).
    pub(crate) bits_per_sample: BitsPerSample,
    /// If true, encode losslessly via the modular encoder. `distance` is then
    /// ignored. RGB and alpha both round-trip bit-perfectly.
    pub(crate) lossless: bool,
    /// Invisible-color preprocessing (see `EncodeConfig::fill_invisible`).
    pub(crate) fill_invisible: bool,
    pub(crate) progressive: bool,
    pub(crate) patches: bool,
    #[cfg(feature = "splines")]
    pub(crate) splines: bool,
    #[cfg(feature = "splines")]
    pub(crate) dots: bool,
    /// Number of lossy VarDCT passes (see `EncodeConfig::progressive_passes`).
    pub(crate) progressive_passes: Option<u32>,
    /// Explicit per-pass shift schedule (see `EncodeConfig::progressive_shifts`).
    pub(crate) progressive_shifts: Option<Vec<u32>>,
    /// If true, the image is grayscale: the codestream declares a Gray color
    /// space so the decoder emits a single-channel (L / LA) image. Internally
    /// the data still flows through the XYB pipeline with R=G=B, so the X and B
    /// chroma channels are ~constant and cost almost nothing.
    pub(crate) grayscale: bool,
    /// HDR peak display luminance in nits (see `EncodeConfig::intensity_target`).
    pub(crate) intensity_target: Option<f32>,
    pub(crate) min_nits: f32,
    pub(crate) relative_to_max_display: bool,
    pub(crate) linear_below: f32,
    /// Worker-thread count for VarDCT encoding (see `EncodeConfig::num_threads`).
    pub(crate) num_threads: usize,
    pub(crate) speed: Speed,
    /// Decode-speed/density tradeoff for lossless (see `EncodeConfig::decoding_speed`).
    pub(crate) decoding_speed: DecodingSpeed,
    /// Pre-encoded `jhgm` gain map bundle (see `EncodeConfig::gain_map`).
    pub(crate) gain_map: Option<EncodedGainMap>,
}

impl Default for EncodeConfig {
    fn default() -> Self {
        Self {
            distance: 1.0,
            color_encoding: ColorEncoding::default(),
            icc_profile: None,
            exif: None,
            xmp: None,
            brotli_compression: None,
            orientation: Orientation::Normal,
            lossless: false,
            fill_invisible: true,
            progressive: false,
            patches: false,
            #[cfg(feature = "splines")]
            splines: false,
            #[cfg(feature = "splines")]
            dots: false,
            progressive_passes: None,
            progressive_shifts: None,
            intensity_target: None,
            min_nits: 0.0,
            relative_to_max_display: false,
            linear_below: 0.0,
            num_threads: available_parallelism()
                .unwrap_or(NonZero::new(1).unwrap())
                .get(),
            speed: Speed::Fast,
            arbiter: Arbiter::Ssimulacra2,
            decoding_speed: DecodingSpeed::Slow,
            lossy_modular: LossyModular::Off,
            progressive_dc: false,
            progressive_dc_levels: None,
            group_order: GroupOrder::Scanline,
            learned_rate: true,
            gain_map: None,
            coding_transform: CodingTransform::Xyb,
        }
    }
}

impl Default for EncodeConfigImpl {
    fn default() -> Self {
        Self {
            distance: 1.0,
            color_encoding: ColorEncoding::default(),
            icc_profile: None,
            exif: None,
            xmp: None,
            brotli_compression: None,
            orientation: Orientation::Normal,
            alpha: None,
            black: false,
            bits_per_sample: BitsPerSample::Eight,
            lossless: false,
            fill_invisible: true,
            progressive: false,
            patches: false,
            #[cfg(feature = "splines")]
            splines: false,
            #[cfg(feature = "splines")]
            dots: false,
            grayscale: false,
            progressive_passes: None,
            progressive_shifts: None,
            intensity_target: None,
            min_nits: 0.0,
            relative_to_max_display: false,
            linear_below: 0.0,
            num_threads: available_parallelism()
                .unwrap_or(NonZero::new(1).unwrap())
                .get(),
            speed: Speed::Fast,
            decoding_speed: DecodingSpeed::Slow,
            gain_map: None,
        }
    }
}

impl EncodeConfigImpl {
    /// Convenience builder with the given butteraugli distance and otherwise
    /// default settings (sRGB primaries and transfer).
    pub(crate) fn with_distance(distance: f32) -> Self {
        Self {
            distance,
            ..Self::default()
        }
    }

    /// Set the worker-thread count (see `EncodeConfig::num_threads`).
    pub(crate) fn with_num_threads(mut self, n: usize) -> Self {
        self.num_threads = n;
        self
    }

    /// Embed an ICC profile in the codestream (predicted + entropy-coded ICC stream).
    pub(crate) fn with_icc_profile(mut self, icc: Option<Vec<u8>>) -> Self {
        self.icc_profile = icc;
        self
    }
    pub(crate) fn with_exif(mut self, exif: Option<Vec<u8>>) -> Self {
        self.exif = exif;
        self
    }
    pub(crate) fn with_xmp(mut self, xmp: Option<Vec<u8>>) -> Self {
        self.xmp = xmp;
        self
    }
    pub(crate) fn with_brotli_compression(
        mut self,
        compressor: Option<Arc<dyn BrotliCompression>>,
    ) -> Self {
        self.brotli_compression = compressor;
        self
    }
    pub(crate) fn with_orientation(mut self, orientation: Orientation) -> Self {
        self.orientation = orientation;
        self
    }

    /// Attach an 8-bit alpha plane to be encoded losslessly via Modular.
    /// Length must equal `xsize * ysize` of the image passed to encode.
    pub(crate) fn with_alpha(mut self, alpha: AlphaPlane) -> Self {
        self.alpha = Some(alpha);
        self
    }

    /// Declare the extra plane as the K channel of a CMYK image.
    pub(crate) fn with_black(mut self, black: bool) -> Self {
        self.black = black;
        self
    }

    pub(crate) fn with_bits_per_sample(mut self, bps: BitsPerSample) -> Self {
        self.bits_per_sample = bps;
        self
    }

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

    pub(crate) fn with_fill_invisible(mut self, fill_invisible: bool) -> Self {
        self.fill_invisible = fill_invisible;
        self
    }

    pub(crate) fn with_progressive(mut self, progressive: bool) -> Self {
        self.progressive = progressive;
        self
    }

    pub(crate) fn with_patches(mut self, patches: bool) -> Self {
        self.patches = patches;
        self
    }

    #[cfg(feature = "splines")]
    pub(crate) fn with_splines(mut self, splines: bool) -> Self {
        self.splines = splines;
        self
    }

    #[cfg(feature = "splines")]
    pub(crate) fn with_dots(mut self, dots: bool) -> Self {
        self.dots = dots;
        self
    }

    pub(crate) fn with_progressive_passes(mut self, passes: Option<u32>) -> Self {
        self.progressive_passes = passes;
        self
    }

    pub(crate) fn with_progressive_shifts(mut self, shifts: Option<Vec<u32>>) -> Self {
        self.progressive_shifts = shifts;
        self
    }

    /// Copy frame settings from a public `EncodeConfig`.
    pub(crate) fn with_progressive_from(self, config: &EncodeConfig) -> Self {
        #[cfg(feature = "splines")]
        let this = self.with_splines(config.splines).with_dots(config.dots);
        #[cfg(not(feature = "splines"))]
        let this = self;
        this.with_progressive(config.progressive)
            .with_fill_invisible(config.fill_invisible)
            .with_patches(config.patches)
            .with_progressive_passes(config.progressive_passes)
            .with_progressive_shifts(config.progressive_shifts.clone())
            .with_speed(config.speed)
            .with_decoding_speed(config.decoding_speed)
    }

    pub(crate) fn with_speed(mut self, speed: Speed) -> Self {
        self.speed = speed;
        self
    }

    pub(crate) fn with_decoding_speed(mut self, decoding_speed: DecodingSpeed) -> Self {
        self.decoding_speed = decoding_speed;
        self
    }

    /// Mark the image as grayscale (declares a Gray color space).
    pub(crate) fn with_grayscale(mut self, grayscale: bool) -> Self {
        self.grayscale = grayscale;
        self
    }

    /// Replace the color encoding (white point / primaries / transfer / intent).
    pub(crate) fn with_color_encoding(mut self, enc: ColorEncoding) -> Self {
        self.color_encoding = enc;
        self
    }

    pub(crate) fn tone_mapping(&self) -> ToneMappingParams {
        ToneMappingParams {
            intensity_target: self.intensity_target,
            min_nits: self.min_nits,
            relative_to_max_display: self.relative_to_max_display,
            linear_below: self.linear_below,
        }
    }

    pub(crate) fn with_intensity_target(mut self, nits: Option<f32>) -> Self {
        self.intensity_target = nits;
        self
    }

    /// Attach an already-encoded gain map bundle to be written as a `jhgm` box.
    pub(crate) fn with_gain_map(mut self, gain_map: Option<EncodedGainMap>) -> Self {
        self.gain_map = gain_map;
        self
    }
}

impl EncodeConfig {
    /// Convenience builder with the given butteraugli distance and otherwise
    /// default settings (sRGB primaries, linear transfer).
    pub fn with_distance(mut self, distance: f32) -> Self {
        self.distance = distance;
        self
    }

    /// Convenience builder with quality on a libjpeg-like 0..=100 scale.
    /// See [`distance_from_quality`] for the mapping.
    pub fn with_quality(self, quality: f32) -> Self {
        self.with_distance(distance_from_quality(quality))
    }

    /// Replace the color encoding (white point / primaries / transfer / intent).
    pub fn with_color_encoding(mut self, enc: ColorEncoding) -> Self {
        self.color_encoding = enc;
        self
    }

    /// Signal HDR peak display luminance (nits) in the tone-mapping metadata.
    pub fn with_intensity_target(mut self, nits: f32) -> Self {
        self.intensity_target = Some(nits);
        self
    }

    /// HDR mastering black level in nits (ToneMapping `min_nits`).
    pub fn with_min_nits(mut self, nits: f32) -> Self {
        self.min_nits = nits;
        self
    }

    /// Set ToneMapping `relative_to_max_display`.
    pub fn with_relative_to_max_display(mut self, rel: bool) -> Self {
        self.relative_to_max_display = rel;
        self
    }

    /// Set ToneMapping `linear_below` (nits, or 0..1 when relative).
    pub fn with_linear_below(mut self, v: f32) -> Self {
        self.linear_below = v;
        self
    }

    pub(crate) fn tone_mapping(&self) -> ToneMappingParams {
        ToneMappingParams {
            intensity_target: self.intensity_target,
            min_nits: self.min_nits,
            relative_to_max_display: self.relative_to_max_display,
            linear_below: self.linear_below,
        }
    }

    /// Embed an ICC profile in the codestream (predicted + entropy-coded ICC stream).
    pub fn with_icc_profile(mut self, icc: Vec<u8>) -> Self {
        self.icc_profile = Some(icc);
        self
    }
    /// Embed EXIF/TIFF metadata (raw TIFF bytes) via an `Exif` container box.
    pub fn with_exif(mut self, exif: Vec<u8>) -> Self {
        self.exif = Some(exif);
        self
    }
    /// Embed an XMP packet via an uncompressed `xml ` container box.
    pub fn with_xmp(mut self, xmp: Vec<u8>) -> Self {
        self.xmp = Some(xmp);
        self
    }
    /// Compress EXIF and XMP metadata using a caller-provided Brotli encoder.
    pub fn with_brotli_compression(mut self, compressor: Box<dyn BrotliCompression>) -> Self {
        self.brotli_compression = Some(Arc::from(compressor));
        self
    }
    /// Set the image [`Orientation`].
    pub fn with_orientation(mut self, orientation: Orientation) -> Self {
        self.orientation = orientation;
        self
    }
    pub fn with_lossless(mut self, lossless: bool) -> Self {
        self.lossless = lossless;
        self
    }

    /// Enable invisible-color preprocessing (see [`EncodeConfig::fill_invisible`]).
    /// Enabled by default; set to false to retain the original hidden colors
    /// as input to lossy encoding.
    pub fn with_fill_invisible(mut self, fill_invisible: bool) -> Self {
        self.fill_invisible = fill_invisible;
        self
    }

    /// Enable progressive lossless. Only effective when `lossless`.
    pub fn with_progressive(mut self, progressive: bool) -> Self {
        self.progressive = progressive;
        self
    }

    /// Enable exact patch-dictionary matching with full rate comparison.
    pub fn with_patches(mut self, patches: bool) -> Self {
        self.patches = patches;
        self
    }

    /// Experimental spline coding for lossy VarDCT (see [`EncodeConfig::splines`]).
    /// Requires the `splines` Cargo feature.
    #[cfg(feature = "splines")]
    pub fn with_splines(mut self, splines: bool) -> Self {
        self.splines = splines;
        self
    }

    /// Experimental bright/dark dot coding for lossy VarDCT (see [`EncodeConfig::dots`]).
    /// Requires the `splines` Cargo feature.
    #[cfg(feature = "splines")]
    pub fn with_dots(mut self, dots: bool) -> Self {
        self.dots = dots;
        self
    }

    /// Code lossy frames in `transform` (see [`CodingTransform`]).
    pub fn with_coding_transform(mut self, transform: CodingTransform) -> Self {
        self.coding_transform = transform;
        self
    }

    /// Select the lossy encoding arm (see [`LossyModular`]).
    pub fn with_lossy_modular(mut self, mode: LossyModular) -> Self {
        self.lossy_modular = mode;
        self
    }

    /// Code the lossy DC as a progressive DC frame (see
    /// [`EncodeConfig::progressive_dc`]).
    pub fn with_progressive_dc(mut self, progressive_dc: bool) -> Self {
        self.progressive_dc = progressive_dc;
        self
    }

    /// Store the lossy VarDCT groups in `order` (see [`GroupOrder`]).
    pub fn with_group_order(mut self, order: GroupOrder) -> Self {
        self.group_order = order;
        self
    }

    /// Limit the progressive DC frame to its `levels` finest squeeze levels
    /// (see [`EncodeConfig::progressive_dc_levels`]).
    pub fn with_progressive_dc_levels(mut self, levels: u32) -> Self {
        self.progressive_dc_levels = Some(levels);
        self
    }

    /// Price VarDCT transform candidates by the image's own coefficient
    /// statistics (see [`EncodeConfig::learned_rate`]).
    pub fn with_learned_rate(mut self, learned_rate: bool) -> Self {
        self.learned_rate = learned_rate;
        self
    }

    /// Attach an HDR gain map (see [`GainMap`]). It is encoded as its own
    /// JPEG XL codestream and written into a `jhgm` container box.
    pub fn with_gain_map(mut self, gain_map: GainMap) -> Self {
        self.gain_map = Some(gain_map);
        self
    }

    /// Set the worker-thread count (see `EncodeConfig::num_threads`).
    pub fn with_num_threads(mut self, n: usize) -> Self {
        self.num_threads = n;
        self
    }

    /// Select the lossless decode-speed/density tradeoff (see [`DecodingSpeed`]).
    pub fn with_decoding_speed(mut self, decoding_speed: DecodingSpeed) -> Self {
        self.decoding_speed = decoding_speed;
        self
    }

    /// Select the metric the lossy encoder tunes for (see [`Arbiter`]).
    pub fn with_arbiter(mut self, arbiter: Arbiter) -> Self {
        self.arbiter = arbiter;
        self
    }

    /// Select the encode-speed/density tradeoff (see [`Speed`]).
    /// [`Speed::Slow`] and [`Speed::ExtraSlow`] also turn on [`EncodeConfig::patches`].
    pub fn with_speed(mut self, speed: Speed) -> Self {
        self.speed = speed;
        if speed.effort().patches_default {
            self.patches = true;
        }
        self
    }
}

pub fn distance_from_quality(quality: f32) -> f32 {
    assert!(!quality.is_nan(), "quality must not be NaN");
    let q = quality.clamp(0.0, 100.0);
    let d = if q >= 99.0 {
        // Reserve the final quality point for the practical VarDCT ceiling:
        // q99 = 0.10, q100 = 0.05.
        0.05 * 2.0f32.powf(100.0 - q)
    } else if q >= 90.0 {
        // Logarithmic upper range: q90 = 1.0, q99 = 0.1.
        10.0f32.powf((99.0 - q) / 9.0 - 1.0)
    } else if q >= 30.0 {
        0.1 + (100.0 - q) * 0.09
    } else {
        6.24 + 2.5f32.powf((30.0 - q) / 5.0) / 6.25
    };
    d.min(25.0)
}

/// Adaptive B-bias opsin swap for yellow content that quantization would
/// desaturate (two tiers, `Speed::Slow` only — see `yellow_opsin`). Must run
/// after linearization and before any XYB conversion; the non-spec matrix is
/// signaled via the explicit CustomTransformData bundle in `write_headers`.
fn apply_yellow_opsin(ctx: &mut EncodingContext, linear: &Image3F, distance: f32) {
    if !ctx.speed.effort().yellow_opsin || !ctx.coding.is_xyb() {
        return;
    }
    let selection = crate::yellow_opsin::select_yellow(linear, distance);
    if let Some(m) = selection.matrix {
        ctx.set_xyb_matrix(m, distance, selection.default_channel_weights);
    }
    // The yellow selector runs before XYB conversion, so the post-XYB
    // `x_heavy` flag is not available yet. Apply only its own staged B scale
    // here; `frame::encode_frame` ORs in the X-gradient decision later.
    ctx.raise_b_qm_scale(selection.b_qm_scale);
}

pub(crate) fn lossy_context(
    config: &EncodeConfig,
    distance: f32,
    xyb: XybMatrix,
    pixels: usize,
) -> EncodingContext {
    // The fastest tiers' work per pixel is deliberately small, so
    // oversubscribing tiny images spends more time constructing and
    // synchronizing workers than it saves. Keep the requested count as a maximum and give each active lane
    // roughly 64K pixels; larger images still receive the full thread budget.
    let num_threads = if config.speed.effort().full_threads {
        config.num_threads
    } else {
        config.num_threads.min(pixels.div_ceil(64 * 1024).max(1))
    };
    let mut ctx = EncodingContext::new(config.speed, config.arbiter, xyb, distance, num_threads);
    ctx.lossy_modular = config.lossy_modular;
    ctx.progressive_dc = config.progressive_dc;
    ctx.progressive_dc_levels = config.progressive_dc_levels;
    ctx.group_order = config.group_order;
    ctx.learned_rate = config.learned_rate && config.speed.effort().learned_rate;
    #[cfg(feature = "splines")]
    {
        let slow = config.speed.effort().splines && config.decoding_speed == DecodingSpeed::Slow;
        ctx.splines = config.splines && slow;
        ctx.dots = config.dots && slow;
    }
    ctx
}

fn for_each_linear_band<F>(
    image: &mut Image3F,
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
    f: F,
) where
    F: Fn(usize, [&mut [f32]; 3]) + Sync,
{
    let mut pixel_start = 0;
    let mut jobs: Vec<_> = image
        .row_bands_mut(ctx.thread_pool.num_threads())
        .into_iter()
        .map(|band| {
            let start = pixel_start;
            pixel_start += band[0].len();
            Some((start, band))
        })
        .collect();

    if jobs.len() <= 1 {
        for job in jobs {
            let (start, band) = job.unwrap();
            f(start, band);
        }
    } else {
        ctx.thread_pool
            .steal_for_each_mut(scratch, &mut jobs, |_i, job, _scratch| {
                let (start, band) = job.take().unwrap();
                f(start, band);
            });
    }
}

fn linearize_rgb<T, X, const CHANNELS: usize>(
    input: &[T],
    width: usize,
    height: usize,
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
    transform: &X,
) -> Image3F
where
    T: Copy + Sync,
    X: RgbBlockTransform<T>,
{
    debug_assert!(CHANNELS >= 3);
    let mut linear = Image3F::new(width, height);
    for_each_linear_band(&mut linear, ctx, scratch, |pixel_start, [r, g, b]| {
        let src = &input[pixel_start * CHANNELS..][..r.len() * CHANNELS];
        transform.transform_block(src.as_chunks::<CHANNELS>().0, [r, g, b]);
    });
    linear
}

fn linearize_gray<T, D>(
    input: &[T],
    width: usize,
    height: usize,
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
    decoder: &D,
) -> Image3F
where
    T: Copy + Sync,
    D: TransferDecoder<T>,
{
    let mut linear = Image3F::new(width, height);
    for_each_linear_band(&mut linear, ctx, scratch, |pixel_start, [r, g, b]| {
        let src = &input[pixel_start..][..r.len()];
        for (((r, g), b), &v) in r
            .iter_mut()
            .zip(g.iter_mut())
            .zip(b.iter_mut())
            .zip(src.iter())
        {
            let linear = decoder.decode(v);
            *r = linear;
            *g = linear;
            *b = linear;
        }
    });
    linear
}

/// Encode interleaved 8-bit RGB samples. Lossy encoding interprets the samples
/// using `config.color_encoding`; the default is sRGB.
pub fn encode_image(
    input: &[u8],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    if width == 0 || height == 0 {
        return Err(EncodeError::EmptyImage);
    }
    if width > MAX_DIMENSION || height > MAX_DIMENSION {
        return Err(EncodeError::DimensionTooLarge { width, height });
    }
    let expected = checked_buffer_size::<u8>(width, height, 3)?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected,
            actual: input.len(),
        });
    }
    if !config.distance.is_finite() || config.distance <= 0.0 {
        return Err(EncodeError::InvalidDistance(config.distance));
    }
    if config.lossless {
        return encode_with_config_loseless(
            input,
            width,
            height,
            false,
            8,
            &EncodeConfigImpl::with_distance(config.distance)
                .with_lossless(config.lossless)
                .with_progressive(config.progressive)
                .with_patches(config.patches)
                .with_icc_profile(config.icc_profile.clone())
                .with_exif(config.exif.clone())
                .with_gain_map(encode_gain_map(config)?)
                .with_xmp(config.xmp.clone())
                .with_brotli_compression(config.brotli_compression.clone())
                .with_orientation(config.orientation)
                .with_color_encoding(config.color_encoding)
                .with_intensity_target(config.intensity_target)
                .with_speed(config.speed)
                .with_decoding_speed(config.decoding_speed)
                .with_num_threads(config.num_threads),
        );
    }
    let distance = config.distance.max(MIN_DISTANCE);
    let transform = ColorTransform::for_integer(
        8,
        config.color_encoding.transfer,
        config.color_encoding.primaries,
    );
    let ctx = lossy_context(config, distance, XybMatrix::SPEC, width * height);
    let mut scratch = Box::<CoderScratch>::default();
    let linear = linearize_rgb::<_, _, 3>(input, width, height, &ctx, &mut scratch, &transform);
    let mut ctx = ctx;
    ctx.set_coding(config.coding_transform, distance);
    apply_yellow_opsin(&mut ctx, &linear, distance);
    let cfg = EncodeConfigImpl::with_distance(distance)
        .with_progressive_from(config)
        .with_icc_profile(config.icc_profile.clone())
        .with_exif(config.exif.clone())
        .with_gain_map(encode_gain_map(config)?)
        .with_xmp(config.xmp.clone())
        .with_brotli_compression(config.brotli_compression.clone())
        .with_orientation(config.orientation)
        .with_color_encoding(config.color_encoding)
        .with_intensity_target(config.intensity_target)
        .with_num_threads(config.num_threads);
    encode_samples_lossy(
        Samples::U8 {
            data: input,
            stride: 3,
        },
        false,
        linear,
        &cfg,
        &ctx,
        &mut scratch,
    )
}

/// Encode interleaved 8-bit RGBA samples. Lossy RGB samples use
/// `config.color_encoding`; alpha is linear opacity.
pub fn encode_image_with_alpha(
    input: &[u8],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    if width == 0 || height == 0 {
        return Err(EncodeError::EmptyImage);
    }
    if width > MAX_DIMENSION || height > MAX_DIMENSION {
        return Err(EncodeError::DimensionTooLarge { width, height });
    }
    let expected = checked_buffer_size::<u8>(width, height, 4)?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected,
            actual: input.len(),
        });
    }
    if !config.distance.is_finite() || config.distance <= 0.0 {
        return Err(EncodeError::InvalidDistance(config.distance));
    }

    if config.lossless {
        return encode_with_config_loseless(
            input,
            width,
            height,
            true,
            8,
            &EncodeConfigImpl::with_distance(config.distance)
                .with_lossless(config.lossless)
                .with_progressive(config.progressive)
                .with_patches(config.patches)
                .with_icc_profile(config.icc_profile.clone())
                .with_exif(config.exif.clone())
                .with_gain_map(encode_gain_map(config)?)
                .with_xmp(config.xmp.clone())
                .with_brotli_compression(config.brotli_compression.clone())
                .with_orientation(config.orientation)
                .with_color_encoding(config.color_encoding)
                .with_intensity_target(config.intensity_target)
                .with_speed(config.speed)
                .with_decoding_speed(config.decoding_speed)
                .with_num_threads(config.num_threads),
        );
    }
    let distance = config.distance.max(MIN_DISTANCE);
    let transform = ColorTransform::for_integer(
        8,
        config.color_encoding.transfer,
        config.color_encoding.primaries,
    );
    let ctx = lossy_context(config, distance, XybMatrix::SPEC, width * height);
    let mut scratch = Box::<CoderScratch>::default();
    let linear = linearize_rgb::<_, _, 4>(input, width, height, &ctx, &mut scratch, &transform);
    let mut ctx = ctx;
    ctx.set_coding(config.coding_transform, distance);
    apply_yellow_opsin(&mut ctx, &linear, distance);
    let alpha_plane = input.as_chunks::<4>().0.iter().map(|px| px[3]).collect();
    let cfg = EncodeConfigImpl::with_distance(distance)
        .with_progressive_from(config)
        .with_alpha(AlphaPlane::from_u8(alpha_plane))
        .with_icc_profile(config.icc_profile.clone())
        .with_exif(config.exif.clone())
        .with_gain_map(encode_gain_map(config)?)
        .with_xmp(config.xmp.clone())
        .with_brotli_compression(config.brotli_compression.clone())
        .with_orientation(config.orientation)
        .with_color_encoding(config.color_encoding)
        .with_intensity_target(config.intensity_target)
        .with_num_threads(config.num_threads);
    encode_samples_lossy(
        Samples::U8 {
            data: input,
            stride: 4,
        },
        false,
        linear,
        &cfg,
        &ctx,
        &mut scratch,
    )
}

pub fn encode_image_with_alpha_10bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_high_depth_rgba(input, width, height, true, config, BitsPerSample::Ten)
}

pub fn encode_image_with_alpha_12bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_high_depth_rgba(input, width, height, true, config, BitsPerSample::Twelve)
}

/// Encode a 16-bit RGBA image. `input` is interleaved `[R, G, B, A]`,
/// `width * height * 4` samples, each in 0..=65535.
pub fn encode_image_with_alpha_16bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_high_depth_rgba(input, width, height, true, config, BitsPerSample::Sixteen)
}

/// Encode a 16-bit RGB image. `input` is interleaved `[R, G, B]`,
/// `width * height * 3` samples, each in 0..=65535.
pub fn encode_image_16bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_high_depth_rgba(input, width, height, false, config, BitsPerSample::Sixteen)
}

pub fn encode_image_10bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_high_depth_rgba(input, width, height, false, config, BitsPerSample::Ten)
}

pub fn encode_image_12bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_high_depth_rgba(input, width, height, false, config, BitsPerSample::Twelve)
}

/// Encode an 8-bit grayscale image. `input` is `width * height` luma bytes.
/// The codestream declares a Gray color space, so the decoder emits a
/// single-channel (L) image. Internally the luma is run through the XYB
/// pipeline with R=G=B; the chroma channels are ~constant and cost almost
/// nothing.
pub fn encode_image_gray(
    input: &[u8],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_gray_impl(input, None, width, height, config)
}

pub fn encode_image_gray_alpha(
    input: &[u8],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    let expected = checked_buffer_size::<u8>(width, height, 2)?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected: width * height * 2,
            actual: input.len(),
        });
    }
    let (luma, alpha): (Vec<u8>, Vec<u8>) = input
        .as_chunks::<2>()
        .0
        .iter()
        .map(|px| (px[0], px[1]))
        .unzip();
    encode_gray_impl(&luma, Some(alpha), width, height, config)
}

/// Shared grayscale encode path. `luma` is `width * height` bytes; `alpha`, if
/// present, is the same length.
fn encode_gray_impl(
    luma: &[u8],
    alpha: Option<Vec<u8>>,
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    if width == 0 || height == 0 {
        return Err(EncodeError::EmptyImage);
    }
    if width > MAX_DIMENSION || height > MAX_DIMENSION {
        return Err(EncodeError::DimensionTooLarge { width, height });
    }
    let expected = checked_buffer_size::<u8>(width, height, 1)?;
    if luma.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected: width * height,
            actual: luma.len(),
        });
    }
    if !config.distance.is_finite() || config.distance <= 0.0 {
        return Err(EncodeError::InvalidDistance(config.distance));
    }
    if config.lossless {
        let mut image = Image3Si::try_new_per_plane([(width, height), (0, 0), (0, 0)])?;
        for (out, &value) in image.plane_mut(0).as_mut_slice().iter_mut().zip(luma) {
            *out = value.to_signed_int(8);
        }
        let alpha_plane = alpha.map(AlphaPlane::U8);
        return encode_lossless_planes(
            &image,
            &alpha_plane,
            8,
            &EncodeConfigImpl::with_distance(config.distance)
                .with_lossless(true)
                .with_grayscale(true)
                .with_patches(config.patches)
                .with_icc_profile(config.icc_profile.clone())
                .with_exif(config.exif.clone())
                .with_gain_map(encode_gain_map(config)?)
                .with_xmp(config.xmp.clone())
                .with_brotli_compression(config.brotli_compression.clone())
                .with_orientation(config.orientation)
                .with_color_encoding(config.color_encoding)
                .with_intensity_target(config.intensity_target)
                .with_speed(config.speed)
                .with_decoding_speed(config.decoding_speed)
                .with_num_threads(config.num_threads),
        );
    }
    let distance = config.distance.max(MIN_DISTANCE);
    let decoder = TransferLut::new(8, config.color_encoding.transfer);
    let mut ctx = lossy_context(config, distance, XybMatrix::SPEC, width * height);
    ctx.set_coding(config.coding_transform, distance);
    let mut scratch = Box::<CoderScratch>::default();
    let linear = linearize_gray(luma, width, height, &ctx, &mut scratch, &decoder);
    let mut cfg = EncodeConfigImpl::with_distance(distance)
        .with_progressive_from(config)
        .with_grayscale(true)
        .with_icc_profile(config.icc_profile.clone())
        .with_exif(config.exif.clone())
        .with_gain_map(encode_gain_map(config)?)
        .with_xmp(config.xmp.clone())
        .with_brotli_compression(config.brotli_compression.clone())
        .with_orientation(config.orientation)
        .with_color_encoding(config.color_encoding)
        .with_intensity_target(config.intensity_target)
        .with_num_threads(config.num_threads);
    if let Some(a) = alpha {
        cfg = cfg.with_alpha(AlphaPlane::from_u8(a));
    }
    encode_samples_lossy(
        Samples::U8 {
            data: luma,
            stride: 1,
        },
        true,
        linear,
        &cfg,
        &ctx,
        &mut scratch,
    )
}

/// Encode a 10-bit grayscale image. `input` is `width * height` luma samples (0..=1023).
pub fn encode_image_gray_10bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_gray_high_depth_impl(input, None, width, height, config, BitsPerSample::Ten)
}

/// Encode a 12-bit grayscale image. `input` is `width * height` luma samples (0..=4095).
pub fn encode_image_gray_12bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_gray_high_depth_impl(input, None, width, height, config, BitsPerSample::Twelve)
}

/// Encode a 10-bit grayscale+alpha image. `input` is interleaved `[L, A]` pairs,
/// `width * height * 2` samples total, each in 0..=1023.
pub fn encode_image_gray_alpha_10bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    let expected = checked_buffer_size::<u16>(width, height, 2)?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected: width * height * 2,
            actual: input.len(),
        });
    }
    let (luma, alpha): (Vec<u16>, Vec<u16>) = input
        .as_chunks::<2>()
        .0
        .iter()
        .map(|px| (px[0], px[1]))
        .unzip();
    encode_gray_high_depth_impl(
        &luma,
        Some(alpha),
        width,
        height,
        config,
        BitsPerSample::Ten,
    )
}

/// Encode a 12-bit grayscale+alpha image. `input` is interleaved `[L, A]` pairs,
/// `width * height * 2` samples total, each in 0..=4095.
pub fn encode_image_gray_alpha_12bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    let expected = checked_buffer_size::<u16>(width, height, 2)?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected: width * height * 2,
            actual: input.len(),
        });
    }
    let (luma, alpha): (Vec<u16>, Vec<u16>) = input
        .as_chunks::<2>()
        .0
        .iter()
        .map(|px| (px[0], px[1]))
        .unzip();
    encode_gray_high_depth_impl(
        &luma,
        Some(alpha),
        width,
        height,
        config,
        BitsPerSample::Twelve,
    )
}

/// Encode a 16-bit grayscale image. `input` is `width * height` luma samples (0..=65535).
pub fn encode_image_gray_16bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_gray_high_depth_impl(input, None, width, height, config, BitsPerSample::Sixteen)
}

/// Encode a 16-bit grayscale+alpha image. `input` is interleaved `[L, A]` pairs,
/// `width * height * 2` samples total, each in 0..=65535.
pub fn encode_image_gray_alpha_16bit(
    input: &[u16],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    let expected = checked_buffer_size::<u16>(width, height, 2)?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected: width * height * 2,
            actual: input.len(),
        });
    }
    let (luma, alpha): (Vec<u16>, Vec<u16>) = input
        .as_chunks::<2>()
        .0
        .iter()
        .map(|px| (px[0], px[1]))
        .unzip();
    encode_gray_high_depth_impl(
        &luma,
        Some(alpha),
        width,
        height,
        config,
        BitsPerSample::Sixteen,
    )
}

/// Shared high-bit-depth grayscale encode path.
/// `luma` is `width * height` samples; `alpha`, if present, is the same length.
fn encode_gray_high_depth_impl(
    luma: &[u16],
    alpha: Option<Vec<u16>>,
    width: usize,
    height: usize,
    config: &EncodeConfig,
    bps: BitsPerSample,
) -> Result<Vec<u8>, EncodeError> {
    if width == 0 || height == 0 {
        return Err(EncodeError::EmptyImage);
    }
    if width > MAX_DIMENSION || height > MAX_DIMENSION {
        return Err(EncodeError::DimensionTooLarge { width, height });
    }
    let expected = checked_buffer_size::<u16>(width, height, 1)?;
    if luma.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected: width * height,
            actual: luma.len(),
        });
    }
    if let Some(alpha) = alpha.as_ref()
        && alpha.len() != expected
    {
        return Err(EncodeError::InputSizeMismatch {
            expected: width * height,
            actual: luma.len(),
        });
    }
    if !config.distance.is_finite() || config.distance <= 0.0 {
        return Err(EncodeError::InvalidDistance(config.distance));
    }

    if config.lossless {
        let mut image = Image3Si::try_new_per_plane([(width, height), (0, 0), (0, 0)])?;
        for (out, &value) in image.plane_mut(0).as_mut_slice().iter_mut().zip(luma) {
            *out = value.to_signed_int(bps.bits() as u8);
        }
        let alpha_plane = alpha.map(|mut data| {
            let bits = bps.bits() as u8;
            for value in &mut data {
                *value = (*value).to_signed_int(bits) as u16;
            }
            AlphaPlane::U16 { data, bits }
        });
        return encode_lossless_planes(
            &image,
            &alpha_plane,
            bps.bits() as u8,
            &EncodeConfigImpl::with_distance(config.distance)
                .with_lossless(true)
                .with_grayscale(true)
                .with_patches(config.patches)
                .with_bits_per_sample(bps)
                .with_icc_profile(config.icc_profile.clone())
                .with_exif(config.exif.clone())
                .with_gain_map(encode_gain_map(config)?)
                .with_xmp(config.xmp.clone())
                .with_brotli_compression(config.brotli_compression.clone())
                .with_orientation(config.orientation)
                .with_color_encoding(config.color_encoding)
                .with_intensity_target(config.intensity_target)
                .with_speed(config.speed)
                .with_decoding_speed(config.decoding_speed)
                .with_num_threads(config.num_threads),
        );
    }

    let distance = config.distance.max(MIN_DISTANCE);
    let decoder = TransferLut::new(bps.bits(), config.color_encoding.transfer);
    let mut ctx = lossy_context(config, distance, XybMatrix::SPEC, width * height);
    ctx.set_coding(config.coding_transform, distance);
    let mut scratch = Box::<CoderScratch>::default();
    let linear = linearize_gray(luma, width, height, &ctx, &mut scratch, &decoder);

    let alpha_plane = alpha.map(|a| match bps {
        BitsPerSample::Ten => AlphaPlane::from_u16_10bit(a),
        BitsPerSample::Twelve => AlphaPlane::from_u16_12bit(a),
        BitsPerSample::Sixteen => AlphaPlane::from_u16_16bit(a),
        BitsPerSample::Eight => unreachable!("high-depth gray path called with 8-bit bps"),
        BitsPerSample::F16 | BitsPerSample::F32 => {
            unreachable!("float path does not use the integer alpha match")
        }
    });

    let mut cfg = EncodeConfigImpl::with_distance(distance)
        .with_progressive_from(config)
        .with_grayscale(true)
        .with_bits_per_sample(bps)
        .with_icc_profile(config.icc_profile.clone())
        .with_exif(config.exif.clone())
        .with_gain_map(encode_gain_map(config)?)
        .with_xmp(config.xmp.clone())
        .with_brotli_compression(config.brotli_compression.clone())
        .with_orientation(config.orientation)
        .with_color_encoding(config.color_encoding)
        .with_intensity_target(config.intensity_target)
        .with_num_threads(config.num_threads);
    if let Some(ap) = alpha_plane {
        cfg = cfg.with_alpha(ap);
    }
    encode_samples_lossy(
        Samples::U16 {
            data: luma,
            stride: 1,
            max: ((1u32 << bps.bits()) - 1) as u16,
        },
        true,
        linear,
        &cfg,
        &ctx,
        &mut scratch,
    )
}

/// Shared implementation for 10-bit and 12-bit RGBA encoding.
fn encode_high_depth_rgba(
    input: &[u16],
    width: usize,
    height: usize,
    has_alpha: bool,
    config: &EncodeConfig,
    bps: BitsPerSample,
) -> Result<Vec<u8>, EncodeError> {
    let expected = checked_buffer_size::<u16>(width, height, if has_alpha { 4 } else { 3 })?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected,
            actual: input.len(),
        });
    }

    if config.lossless {
        return encode_with_config_loseless(
            input,
            width,
            height,
            has_alpha,
            bps.bits() as u8,
            &EncodeConfigImpl::with_distance(config.distance)
                .with_lossless(config.lossless)
                .with_bits_per_sample(bps)
                .with_patches(config.patches)
                .with_icc_profile(config.icc_profile.clone())
                .with_exif(config.exif.clone())
                .with_gain_map(encode_gain_map(config)?)
                .with_xmp(config.xmp.clone())
                .with_brotli_compression(config.brotli_compression.clone())
                .with_orientation(config.orientation)
                .with_color_encoding(config.color_encoding)
                .with_intensity_target(config.intensity_target)
                .with_speed(config.speed)
                .with_decoding_speed(config.decoding_speed)
                .with_num_threads(config.num_threads),
        );
    }
    let distance = config.distance.max(MIN_DISTANCE);
    let transform = ColorTransform::for_integer(
        bps.bits(),
        config.color_encoding.transfer,
        config.color_encoding.primaries,
    );
    let ctx = lossy_context(config, distance, XybMatrix::SPEC, width * height);
    let mut scratch = Box::<CoderScratch>::default();

    // For 16-bit, (1 << 16) - 1 overflows u16's shift; compute in u32 and cap.
    let bp_max: u16 = if bps.bits() >= 16 {
        u16::MAX
    } else {
        ((1u32 << bps.bits()) - 1) as u16
    };

    if has_alpha {
        let linear = linearize_rgb::<_, _, 4>(input, width, height, &ctx, &mut scratch, &transform);
        let mut ctx = ctx;
        ctx.set_coding(config.coding_transform, distance);
        apply_yellow_opsin(&mut ctx, &linear, distance);
        let alpha_plane = input
            .as_chunks::<4>()
            .0
            .iter()
            .map(|px| px[3].min(bp_max))
            .collect();
        let cfg = EncodeConfigImpl::with_distance(distance)
            .with_progressive_from(config)
            .with_alpha(match bps {
                BitsPerSample::Ten => AlphaPlane::from_u16_10bit(alpha_plane),
                BitsPerSample::Twelve => AlphaPlane::from_u16_12bit(alpha_plane),
                BitsPerSample::Sixteen => AlphaPlane::from_u16_16bit(alpha_plane),
                BitsPerSample::Eight => unreachable!("high-depth path called with 8-bit bps"),
                BitsPerSample::F16 | BitsPerSample::F32 => {
                    unreachable!("float path does not use the integer alpha match")
                }
            })
            .with_bits_per_sample(bps)
            .with_icc_profile(config.icc_profile.clone())
            .with_exif(config.exif.clone())
            .with_gain_map(encode_gain_map(config)?)
            .with_xmp(config.xmp.clone())
            .with_brotli_compression(config.brotli_compression.clone())
            .with_orientation(config.orientation)
            .with_color_encoding(config.color_encoding)
            .with_intensity_target(config.intensity_target)
            .with_num_threads(config.num_threads);
        encode_samples_lossy(
            Samples::U16 {
                data: input,
                stride: 4,
                max: bp_max,
            },
            false,
            linear,
            &cfg,
            &ctx,
            &mut scratch,
        )
    } else {
        let linear = linearize_rgb::<_, _, 3>(input, width, height, &ctx, &mut scratch, &transform);
        let mut ctx = ctx;
        ctx.set_coding(config.coding_transform, distance);
        apply_yellow_opsin(&mut ctx, &linear, distance);
        let cfg = EncodeConfigImpl::with_distance(distance)
            .with_progressive_from(config)
            .with_bits_per_sample(bps)
            .with_icc_profile(config.icc_profile.clone())
            .with_exif(config.exif.clone())
            .with_gain_map(encode_gain_map(config)?)
            .with_xmp(config.xmp.clone())
            .with_brotli_compression(config.brotli_compression.clone())
            .with_orientation(config.orientation)
            .with_color_encoding(config.color_encoding)
            .with_intensity_target(config.intensity_target)
            .with_num_threads(config.num_threads);
        encode_samples_lossy(
            Samples::U16 {
                data: input,
                stride: 3,
                max: bp_max,
            },
            false,
            linear,
            &cfg,
            &ctx,
            &mut scratch,
        )
    }
}

/// Shared float (f16/f32) RGB(A) **lossy** encode path. `input` is interleaved
/// f32 samples (encoded per `config.color_encoding`, normalized to [0, 1]), 3
/// or 4 per pixel. Alpha,
/// if present, is linear opacity quantized to a 16-bit integer extra channel
/// (alpha rarely needs float precision, and this reuses the 16-bit alpha path).
/// Lossless float is not supported here; `config.lossless` is ignored.
/// f32 lossless (v1): non-negative float RGB only. Reinterprets each float's
/// IEEE-754 bits as an int32 modular channel (matching libjxl's float_to_int
/// for 32-bit float) and codes them with no RCT and no LZ77.
fn encode_f32_lossless_rgba(
    input: &[f32],
    width: usize,
    height: usize,
    has_alpha: bool,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    if width == 0 || height == 0 {
        return Err(EncodeError::EmptyImage);
    }
    if width > MAX_DIMENSION || height > MAX_DIMENSION {
        return Err(EncodeError::DimensionTooLarge { width, height });
    }

    // Guard once: v1 supports only finite, non-negative floats (negatives map to
    // large-magnitude negative int32 bits whose residuals overflow i32, which
    // needs the future 64-bit token path). Applies to RGB and alpha alike.
    for &v in input.iter() {
        if !v.is_finite() || v < 0.0 {
            return Err(EncodeError::Unsupported(
                "f32 lossless v1 supports only finite non-negative values",
            ));
        }
    }

    let nchan = if has_alpha { 4 } else { 3 };
    let mut image3s = Image3Si::new(width, height);
    let mut alpha_bits: Vec<i32> = if has_alpha {
        Vec::with_capacity(width * height)
    } else {
        Vec::new()
    };
    for (y, row) in input.chunks_exact(width * nchan).enumerate() {
        let [r_row, g_row, b_row] = image3s.all_plane_rows_mut(y);
        for (x, src) in row.chunks_exact(nchan).enumerate() {
            r_row[x] = src[0].to_bits() as i32;
            g_row[x] = src[1].to_bits() as i32;
            b_row[x] = src[2].to_bits() as i32;
            if has_alpha {
                alpha_bits.push(src[3].to_bits() as i32);
            }
        }
    }
    let alpha = if has_alpha {
        Some(AlphaPlane::F32(alpha_bits))
    } else {
        None
    };

    let mut w = BitWriter::new();
    w.write(8, 0xFF);
    w.write(8, CODESTREAM_MARKER as u64);
    write_size_header(width, height, &mut w);
    {
        let mut metadata_scratch = Box::new(CoderScratch::lossless());
        write_image_metadata(
            &ImageMetadataParams {
                tone_mapping: config.tone_mapping(),
                color_encoding: &config.color_encoding,
                alpha: alpha.as_ref(),
                black: false,
                icc_profile: config.icc_profile.as_deref(),
                bps: BitsPerSample::F32,
                lossless: true,
                xyb_encoded: false,
                xyb: &XybMatrix::SPEC,
                grayscale: false,
                orientation: config.orientation,
                lossy_modular_16: false,
            },
            &mut metadata_scratch,
            &mut w,
        );
    }
    encode_frame_lossless_float(&image3s, alpha.as_ref(), config.num_threads, &mut w);
    let codestream = w.into_bytes();
    let alpha_bits_md = if has_alpha { 32 } else { 0 };
    let gain_map = encode_gain_map(config)?;
    finalize_container(
        codestream,
        config.exif.as_deref(),
        config.xmp.as_deref(),
        config.brotli_compression.as_deref(),
        needs_level_10(32, true, alpha_bits_md),
        gain_map.as_ref(),
    )
}

fn encode_float_rgba(
    input: &[f32],
    width: usize,
    height: usize,
    has_alpha: bool,
    config: &EncodeConfig,
    bps: BitsPerSample,
) -> Result<Vec<u8>, EncodeError> {
    let expected = checked_buffer_size::<f32>(width, height, if has_alpha { 4 } else { 3 })?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected,
            actual: input.len(),
        });
    }
    if config.lossless && matches!(bps, BitsPerSample::F32) {
        return encode_f32_lossless_rgba(input, width, height, has_alpha, config);
    }
    let distance = config.distance.max(MIN_DISTANCE);
    // Float input skips the red-dominance classifier (integer-domain sampling).
    let ctx = lossy_context(config, distance, XybMatrix::SPEC, width * height);
    let mut scratch = Box::<CoderScratch>::default();
    let transform = ColorTransform::for_float(
        config.color_encoding.transfer,
        config.color_encoding.primaries,
    );

    if has_alpha {
        let linear = linearize_rgb::<_, _, 4>(input, width, height, &ctx, &mut scratch, &transform);
        let mut ctx = ctx;
        ctx.set_coding(config.coding_transform, distance);
        apply_yellow_opsin(&mut ctx, &linear, distance);
        let alpha_plane = input
            .as_chunks::<4>()
            .0
            .iter()
            .map(|px| (px[3].clamp(0.0, 1.0) * 65535.0 + 0.5) as u16)
            .collect();
        let cfg = EncodeConfigImpl::with_distance(distance)
            .with_progressive_from(config)
            .with_alpha(AlphaPlane::from_u16_16bit(alpha_plane))
            .with_bits_per_sample(bps)
            .with_icc_profile(config.icc_profile.clone())
            .with_exif(config.exif.clone())
            .with_gain_map(encode_gain_map(config)?)
            .with_xmp(config.xmp.clone())
            .with_brotli_compression(config.brotli_compression.clone())
            .with_orientation(config.orientation)
            .with_color_encoding(config.color_encoding)
            .with_intensity_target(config.intensity_target)
            .with_num_threads(config.num_threads);
        encode_samples_lossy(
            Samples::F32 {
                data: input,
                stride: 4,
            },
            false,
            linear,
            &cfg,
            &ctx,
            &mut scratch,
        )
    } else {
        let linear = linearize_rgb::<_, _, 3>(input, width, height, &ctx, &mut scratch, &transform);
        let mut ctx = ctx;
        ctx.set_coding(config.coding_transform, distance);
        apply_yellow_opsin(&mut ctx, &linear, distance);
        let cfg = EncodeConfigImpl::with_distance(distance)
            .with_progressive_from(config)
            .with_bits_per_sample(bps)
            .with_icc_profile(config.icc_profile.clone())
            .with_exif(config.exif.clone())
            .with_gain_map(encode_gain_map(config)?)
            .with_xmp(config.xmp.clone())
            .with_brotli_compression(config.brotli_compression.clone())
            .with_orientation(config.orientation)
            .with_color_encoding(config.color_encoding)
            .with_intensity_target(config.intensity_target)
            .with_num_threads(config.num_threads);
        encode_samples_lossy(
            Samples::F32 {
                data: input,
                stride: 3,
            },
            false,
            linear,
            &cfg,
            &ctx,
            &mut scratch,
        )
    }
}

/// Float (f16/f32) grayscale **lossy** encode path. `luma` is `width * height`
/// f32 samples (encoded per `config.color_encoding`, [0, 1]).
fn encode_float_gray(
    luma: &[f32],
    width: usize,
    height: usize,
    config: &EncodeConfig,
    bps: BitsPerSample,
) -> Result<Vec<u8>, EncodeError> {
    let expected = checked_buffer_size::<f32>(width, height, 1)?;
    if luma.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected: width * height,
            actual: luma.len(),
        });
    }
    let distance = config.distance.max(MIN_DISTANCE);
    let mut ctx = lossy_context(config, distance, XybMatrix::SPEC, width * height);
    ctx.set_coding(config.coding_transform, distance);
    let mut scratch = Box::<CoderScratch>::default();
    let decoder = FloatTransferDecoder::new(config.color_encoding.transfer);
    let linear = linearize_gray(luma, width, height, &ctx, &mut scratch, &decoder);
    let cfg = EncodeConfigImpl::with_distance(distance)
        .with_progressive_from(config)
        .with_grayscale(true)
        .with_bits_per_sample(bps)
        .with_icc_profile(config.icc_profile.clone())
        .with_exif(config.exif.clone())
        .with_gain_map(encode_gain_map(config)?)
        .with_xmp(config.xmp.clone())
        .with_brotli_compression(config.brotli_compression.clone())
        .with_orientation(config.orientation)
        .with_color_encoding(config.color_encoding)
        .with_intensity_target(config.intensity_target)
        .with_num_threads(config.num_threads);
    encode_samples_lossy(
        Samples::F32 {
            data: luma,
            stride: 1,
        },
        true,
        linear,
        &cfg,
        &ctx,
        &mut scratch,
    )
}

/// Encode a 32-bit float RGB image (lossy). `input` is interleaved `[R, G, B]`,
/// `width * height * 3` samples encoded per `config.color_encoding` in [0, 1].
pub fn encode_image_f32(
    input: &[f32],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_float_rgba(input, width, height, false, config, BitsPerSample::F32)
}

/// Encode a 16-bit-half float RGB image (lossy). Input is f32 in [0, 1]; the
/// stream is declared as f16.
pub fn encode_image_f16(
    input: &[f32],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_float_rgba(input, width, height, false, config, BitsPerSample::F16)
}

/// Encode a 32-bit float RGBA image (lossy). `input` is interleaved
/// `[R, G, B, A]`; RGB uses `config.color_encoding` in [0, 1], A is linear opacity in [0, 1]
/// (quantized to a 16-bit alpha channel).
pub fn encode_image_with_alpha_f32(
    input: &[f32],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_float_rgba(input, width, height, true, config, BitsPerSample::F32)
}

/// Encode a 16-bit-half float RGBA image (lossy).
pub fn encode_image_with_alpha_f16(
    input: &[f32],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_float_rgba(input, width, height, true, config, BitsPerSample::F16)
}

/// Encode a 32-bit float grayscale image (lossy). `input` is `width * height`
/// luma samples encoded per `config.color_encoding` in [0, 1].
pub fn encode_image_gray_f32(
    input: &[f32],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_float_gray(input, width, height, config, BitsPerSample::F32)
}

/// Encode a 16-bit-half float grayscale image (lossy).
pub fn encode_image_gray_f16(
    input: &[f32],
    width: usize,
    height: usize,
    config: &EncodeConfig,
) -> Result<Vec<u8>, EncodeError> {
    encode_float_gray(input, width, height, config, BitsPerSample::F16)
}

/// Resolve the per-pass VarDCT coefficient-shift schedule for lossy encoding.
/// Returns `[shift_pass0, .., shift_passN-1]` with the last element 0. A single
/// pass is `[0]`. The decoder reconstructs each AC coefficient by summing
/// `(sent_p << shift_p)` over passes, so the schedule must end in 0.
///
/// An explicit `shifts` is used when valid (non-empty, ends in 0, all entries
/// 0..=3, non-increasing); otherwise it is ignored and we fall back to a count:
/// `passes` (clamped 1..=4) or the `progressive` bool, yielding the
/// coarse-to-fine schedule `[n-1, .., 1, 0]`.
pub(crate) fn progressive_schedule(
    progressive: bool,
    passes: Option<u32>,
    shifts: Option<&[u32]>,
) -> Vec<u32> {
    if let Some(s) = shifts {
        let valid = !s.is_empty()
            && s.len() <= 11
            && *s.last().unwrap() == 0
            && s.iter().all(|&v| v <= 3)
            && s.array_windows::<2>().all(|w| w[0] >= w[1]);
        if valid {
            return s.to_vec();
        }
    }
    let n = passes
        .map(|p| p.clamp(1, 4))
        .unwrap_or(if progressive { 2 } else { 1 }) as usize;
    (0..n).rev().map(|p| p as u32).collect()
}

/// Integer or float samples of one lossy entry point, as the frame codes
/// them under a non-XYB transform.
enum Samples<'a> {
    /// Interleaved integer channels (`stride` per pixel), at most `max`.
    U8 { data: &'a [u8], stride: usize },
    U16 {
        data: &'a [u16],
        stride: usize,
        max: u16,
    },
    /// Interleaved float channels, coded as given.
    F32 { data: &'a [f32], stride: usize },
}

impl Samples<'_> {
    /// Channel `c` of pixel `px` in nominal [0, 1] units.
    #[inline]
    fn get(&self, px: usize, c: usize) -> f32 {
        match *self {
            Samples::U8 { data, stride } => f32::from(data[px * stride + c]) * (1.0 / 255.0),
            Samples::U16 { data, stride, max } => {
                f32::from(data[px * stride + c].min(max)) / f32::from(max)
            }
            Samples::F32 { data, stride } => data[px * stride + c],
        }
    }
}

/// Lossy encode from the input samples. Non-XYB transforms code them as given,
/// in the image's declared color space (gray as three equal channels); `linear`
/// then only steers adaptive quantization.
fn encode_samples_lossy(
    samples: Samples<'_>,
    gray: bool,
    linear: Image3F,
    config: &EncodeConfigImpl,
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
) -> Result<Vec<u8>, EncodeError> {
    if ctx.coding.is_xyb() {
        return encode_with_context(linear, config, ctx, scratch);
    }
    let (width, height) = (linear.xsize(), linear.ysize());
    let mut coded = Image3F::try_new(width, height)?;
    for y in 0..height {
        let [p0, p1, p2] = coded.all_plane_rows_mut(y);
        for x in 0..width {
            let px = y * width + x;
            let [r, g, b] = if gray {
                [samples.get(px, 0); 3]
            } else {
                [samples.get(px, 0), samples.get(px, 1), samples.get(px, 2)]
            };
            [p0[x], p1[x], p2[x]] = ctx.coding.code(r, g, b);
        }
    }
    encode_with_coded_planes(linear, Some(coded), config, ctx, scratch)
}

fn encode_with_context(
    input: Image3F,
    config: &EncodeConfigImpl,
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
) -> Result<Vec<u8>, EncodeError> {
    encode_with_coded_planes(input, None, config, ctx, scratch)
}

/// `coded` carries the planes of a non-XYB frame when they are not the
/// sRGB rendition of `input`, which then only steers adaptive quantization.
pub(crate) fn encode_with_coded_planes(
    input: Image3F,
    coded: Option<Image3F>,
    config: &EncodeConfigImpl,
    ctx: &EncodingContext,
    scratch: &mut CoderScratch,
) -> Result<Vec<u8>, EncodeError> {
    let (width, height) = (input.xsize(), input.ysize());
    if width == 0 || height == 0 {
        return Err(EncodeError::EmptyImage);
    }
    if width > MAX_DIMENSION || height > MAX_DIMENSION {
        return Err(EncodeError::DimensionTooLarge { width, height });
    }
    if !config.distance.is_finite() || config.distance <= 0.0 {
        return Err(EncodeError::InvalidDistance(config.distance));
    }

    if let Some(alpha) = config.alpha.as_ref() {
        let expected = match &alpha {
            AlphaPlane::U8(_) => checked_buffer_size::<u8>(width, height, 1)?,
            AlphaPlane::U16 { .. } => checked_buffer_size::<u16>(width, height, 1)?,
            AlphaPlane::F32(_) => checked_buffer_size::<f32>(width, height, 1)?,
        };
        if alpha.len() != expected {
            return Err(EncodeError::AlphaSizeMismatch {
                expected,
                actual: alpha.len(),
            });
        }
    }

    let distance = config.distance.max(MIN_DISTANCE);
    let mut w = BitWriter::new();
    w.write(8, 0xFF);
    w.write(8, CODESTREAM_MARKER as u64);
    write_size_header(width, height, &mut w);
    let coeff_shifts = progressive_schedule(
        config.progressive,
        config.progressive_passes,
        config.progressive_shifts.as_deref(),
    );
    // The frame first: a lossy modular frame of a non-XYB codestream changes
    // the declared bit depth.
    let mut frame = BitWriter::new();
    let lossy_modular_16 = encode_frame(
        ctx,
        scratch,
        distance,
        input,
        coded,
        config.grayscale,
        config.alpha.as_ref(),
        config.fill_invisible && !config.lossless && !config.black,
        &coeff_shifts,
        config.patches,
        !config.bits_per_sample.is_float(),
        &mut frame,
    )?;
    write_image_metadata(
        &ImageMetadataParams {
            tone_mapping: config.tone_mapping(),
            color_encoding: &config.color_encoding,
            alpha: config.alpha.as_ref(),
            black: config.black,
            icc_profile: config.icc_profile.as_deref(),
            bps: config.bits_per_sample,
            lossless: config.lossless,
            xyb_encoded: !config.lossless && ctx.coding.is_xyb(),
            xyb: &ctx.xyb,
            grayscale: config.grayscale,
            orientation: config.orientation,
            lossy_modular_16,
        },
        scratch,
        &mut w,
    );
    w.append(&frame);
    let codestream = w.into_bytes();
    let alpha_bits = config.alpha.as_ref().map(|a| a.bits() as u32).unwrap_or(0);
    finalize_container(
        codestream,
        config.exif.as_deref(),
        config.xmp.as_deref(),
        config.brotli_compression.as_deref(),
        needs_level_10(config.bits_per_sample.bits(), config.lossless, alpha_bits) || config.black,
        config.gain_map.as_ref(),
    )
}

pub(crate) trait AsSignedInt {
    fn to_signed_int(self, max_bp: u8) -> i32;
}

impl AsSignedInt for u8 {
    #[inline]
    fn to_signed_int(self, _: u8) -> i32 {
        self as i32
    }
}

impl AsSignedInt for u16 {
    #[inline]
    fn to_signed_int(self, max_bp: u8) -> i32 {
        let max_colors = ((1u32 << max_bp) - 1) as i32;
        (self as i32).min(max_colors)
    }
}

/// Encode a linear-light RGB `Image3F` with the supplied configuration.
pub(crate) fn encode_with_config_loseless<T: AsSignedInt + Copy>(
    input: &[T],
    width: usize,
    height: usize,
    has_alpha: bool,
    max_bp: u8,
    config: &EncodeConfigImpl,
) -> Result<Vec<u8>, EncodeError> {
    if width == 0 || height == 0 {
        return Err(EncodeError::EmptyImage);
    }
    let expected = checked_buffer_size::<T>(width, height, if has_alpha { 4 } else { 3 })?;
    if input.len() != expected {
        return Err(EncodeError::InputSizeMismatch {
            expected,
            actual: input.len(),
        });
    }

    if width > MAX_DIMENSION || height > MAX_DIMENSION {
        return Err(EncodeError::DimensionTooLarge { width, height });
    }
    if !config.distance.is_finite() || config.distance <= 0.0 {
        return Err(EncodeError::InvalidDistance(config.distance));
    }

    let mut image3s = Image3Si::new(width, height);
    let mut alpha_plane: Option<AlphaPlane> = None;

    if has_alpha {
        if max_bp > 8 {
            let mut new_alpha_plane = vec![0u16; width * height];
            for (y, (row, alpha_row)) in input
                .chunks_exact(width * 4)
                .zip(new_alpha_plane.chunks_exact_mut(width))
                .enumerate()
            {
                let [r_row, g_row, b_row] = image3s.all_plane_rows_mut(y);
                for ((((r, g), b), src), alpha) in r_row
                    .iter_mut()
                    .zip(g_row.iter_mut())
                    .zip(b_row.iter_mut())
                    .zip(row.as_chunks::<4>().0.iter())
                    .zip(alpha_row.iter_mut())
                {
                    let ycocg = forward_ycocg(
                        src[0].to_signed_int(max_bp),
                        src[1].to_signed_int(max_bp),
                        src[2].to_signed_int(max_bp),
                    );
                    *r = ycocg.0;
                    *g = ycocg.1;
                    *b = ycocg.2;
                    *alpha = src[3].to_signed_int(max_bp) as u16;
                }
            }

            alpha_plane = Some(AlphaPlane::U16 {
                data: new_alpha_plane,
                bits: max_bp,
            });
        } else {
            let mut new_alpha_plane = vec![0u8; width * height];
            for (y, (row, alpha_row)) in input
                .chunks_exact(width * 4)
                .zip(new_alpha_plane.chunks_exact_mut(width))
                .enumerate()
            {
                let [r_row, g_row, b_row] = image3s.all_plane_rows_mut(y);
                for ((((r, g), b), src), alpha) in r_row
                    .iter_mut()
                    .zip(g_row.iter_mut())
                    .zip(b_row.iter_mut())
                    .zip(row.as_chunks::<4>().0.iter())
                    .zip(alpha_row.iter_mut())
                {
                    let ycocg = forward_ycocg(
                        src[0].to_signed_int(max_bp),
                        src[1].to_signed_int(max_bp),
                        src[2].to_signed_int(max_bp),
                    );
                    *r = ycocg.0;
                    *g = ycocg.1;
                    *b = ycocg.2;
                    *alpha = src[3].to_signed_int(max_bp) as u8;
                }
            }
            alpha_plane = Some(AlphaPlane::U8(new_alpha_plane));
        }
    } else {
        for (y, row) in input.chunks_exact(width * 3).enumerate() {
            let [r_row, g_row, b_row] = image3s.all_plane_rows_mut(y);
            for (((r, g), b), src) in r_row
                .iter_mut()
                .zip(g_row.iter_mut())
                .zip(b_row.iter_mut())
                .zip(row.as_chunks::<3>().0.iter())
            {
                let ycocg = forward_ycocg(
                    src[0].to_signed_int(max_bp),
                    src[1].to_signed_int(max_bp),
                    src[2].to_signed_int(max_bp),
                );
                *r = ycocg.0;
                *g = ycocg.1;
                *b = ycocg.2;
            }
        }
    }

    encode_lossless_planes(&image3s, &alpha_plane, max_bp, config)
}

fn encode_lossless_planes(
    image3s: &Image3Si,
    alpha_plane: &Option<AlphaPlane>,
    max_bp: u8,
    config: &EncodeConfigImpl,
) -> Result<Vec<u8>, EncodeError> {
    let (width, height) = (image3s.xsize(), image3s.ysize());
    let mut w = BitWriter::new();
    w.write(8, 0xFF);
    w.write(8, CODESTREAM_MARKER as u64);
    write_size_header(width, height, &mut w);
    {
        let mut metadata_scratch = Box::new(CoderScratch::lossless());
        write_image_metadata(
            &ImageMetadataParams {
                tone_mapping: config.tone_mapping(),
                color_encoding: &config.color_encoding,
                alpha: alpha_plane.as_ref(),
                black: config.black,
                icc_profile: config.icc_profile.as_deref(),
                bps: config.bits_per_sample,
                lossless: config.lossless,
                xyb_encoded: !config.lossless,
                xyb: &XybMatrix::SPEC,
                grayscale: config.grayscale,
                orientation: config.orientation,
                lossy_modular_16: false,
            },
            &mut metadata_scratch,
            &mut w,
        );
    }
    let alpha_bits = alpha_plane.as_ref().map(|a| a.bits() as u32).unwrap_or(0);
    let eff_bits = (max_bp as u32).max(alpha_bits);
    let num_color = if config.grayscale { 1 } else { 3 };
    encode_frame_lossless(
        image3s,
        alpha_plane.as_ref(),
        eff_bits,
        config.progressive,
        config.patches,
        num_color,
        config.speed,
        config.decoding_speed,
        config.num_threads,
        &mut w,
    );
    let codestream = w.into_bytes();
    let alpha_bits = alpha_plane.as_ref().map(|a| a.bits() as u32).unwrap_or(0);
    finalize_container(
        codestream,
        config.exif.as_deref(),
        config.xmp.as_deref(),
        config.brotli_compression.as_deref(),
        needs_level_10(max_bp as u32, true, alpha_bits) || config.black,
        config.gain_map.as_ref(),
    )
}

/// Write a single dimension using JXL's 4-bucket variable-length encoding.
fn write_size(size: u32, w: &mut BitWriter) {
    let size_minus_one = size - 1;
    const BUCKET_BITS: [u32; 4] = [9, 13, 18, 30];
    for (selector, &bits) in BUCKET_BITS.iter().enumerate() {
        if size_minus_one < (1 << bits) {
            w.write(2, selector as u64);
            w.write(bits as usize, size_minus_one as u64);
            return;
        }
    }
    unreachable!("dimension was bounds-checked against MAX_DIMENSION");
}

fn write_size_header(xsize: usize, ysize: usize, w: &mut BitWriter) {
    assert!(
        xsize <= MAX_DIMENSION && ysize <= MAX_DIMENSION,
        "image too large: max dimension is {MAX_DIMENSION}"
    );
    w.write(1, 0); // small = false (use full dimension fields)
    write_size(ysize as u32, w);
    w.write(3, 0); // ratio = 0 (no fixed aspect)
    write_size(xsize as u32, w);
}

/// Whether the content requires codestream **level 10**: a modular channel
/// exceeding 16 bits. That happens for a 16-bit (or wider) alpha extra channel,
/// or for >=16-bit lossless (YCoCg-R color residuals are 17-bit). Level 5
/// (the implicit level of a bare codestream) caps modular at 16 bits, so such
/// files MUST be wrapped in a container declaring level 10 or a conformant
/// decoder rejects them.
pub(crate) fn needs_level_10(bits: u32, lossless: bool, alpha_bits: u32) -> bool {
    (lossless && bits >= 16) || alpha_bits >= 16
}

fn push_container_box(out: &mut Vec<u8>, kind: &[u8; 4], contents: &[u8]) {
    let size = 8u64 + contents.len() as u64;
    if size <= u32::MAX as u64 {
        out.extend_from_slice(&(size as u32).to_be_bytes());
        out.extend_from_slice(kind);
    } else {
        out.extend_from_slice(&1u32.to_be_bytes());
        out.extend_from_slice(kind);
        out.extend_from_slice(&(size + 8).to_be_bytes());
    }
    out.extend_from_slice(contents);
}

fn push_metadata_box(
    out: &mut Vec<u8>,
    kind: &[u8; 4],
    contents: &[u8],
    compressor: Option<&dyn BrotliCompression>,
) -> Result<(), EncodeError> {
    if let Some(compressor) = compressor {
        let compressed = compressor.compress(contents)?;
        let mut brob = Vec::with_capacity(4 + compressed.len());
        brob.extend_from_slice(kind);
        brob.extend_from_slice(&compressed);
        push_container_box(out, b"brob", &brob);
    } else {
        push_container_box(out, kind, contents);
    }
    Ok(())
}

/// Wrap a bare codestream in a minimal JXL (ISO BMFF) container that declares
/// `level` via a `jxll` box. Box order: signature, ftyp, jxll, jxlc, then the
/// optional `jhgm` gain map bundle and metadata boxes.
///
/// When `exif` is `Some`, an `Exif` box is appended after the codestream. Its
/// payload is a 4-byte big-endian TIFF-header offset (0) followed by the raw
/// EXIF/TIFF byte stream (the bytes that begin with the "II"/"MM" byte-order
/// mark — *not* the JPEG "Exif\0\0" APP1 prefix). `xmp`, when present, is
/// written as the payload of an `xml ` box. If `compressor` is supplied, EXIF
/// and XMP are instead wrapped in Brotli-compressed `brob` boxes.
pub(crate) fn wrap_jxl_container(
    codestream: Vec<u8>,
    level: u8,
    exif: Option<&[u8]>,
    xmp: Option<&[u8]>,
    compressor: Option<&dyn BrotliCompression>,
    gain_map: Option<&[u8]>,
) -> Result<Vec<u8>, EncodeError> {
    let exif_extra = exif.map(|e| e.len() + 12).unwrap_or(0);
    let xmp_extra = xmp.map(|x| x.len() + 8).unwrap_or(0);
    let gain_map_extra = gain_map.map(|g| g.len() + 8).unwrap_or(0);
    let mut out =
        Vec::with_capacity(codestream.len() + 41 + exif_extra + xmp_extra + gain_map_extra);
    // JXL signature box.
    out.extend_from_slice(&[
        0, 0, 0, 0x0C, b'J', b'X', b'L', b' ', 0x0D, 0x0A, 0x87, 0x0A,
    ]);
    // ftyp box (major brand "jxl ", minor 0, compatible "jxl ").
    out.extend_from_slice(&[
        0, 0, 0, 0x14, b'f', b't', b'y', b'p', b'j', b'x', b'l', b' ', 0, 0, 0, 0, b'j', b'x',
        b'l', b' ',
    ]);
    // jxll level box.
    out.extend_from_slice(&[0, 0, 0, 0x09, b'j', b'x', b'l', b'l', level]);
    push_container_box(&mut out, b"jxlc", &codestream);
    // Gain map bundle (`jhgm`), right after the codestream it belongs to.
    if let Some(g) = gain_map {
        push_container_box(&mut out, b"jhgm", g);
    }
    // Exif metadata box (after the codestream; libjxl convention).
    if let Some(e) = exif {
        let mut contents = Vec::with_capacity(4 + e.len());
        contents.extend_from_slice(&0u32.to_be_bytes()); // TIFF-header offset = 0
        contents.extend_from_slice(e);
        push_metadata_box(&mut out, b"Exif", &contents, compressor)?;
    }
    if let Some(x) = xmp {
        push_metadata_box(&mut out, b"xml ", x, compressor)?;
    }
    Ok(out)
}

/// Decide final output form: wrap in a container when level 10 is required or
/// when an EXIF/XMP/gain-map box must be carried (a bare codestream cannot
/// hold them).
fn finalize_container(
    codestream: Vec<u8>,
    exif: Option<&[u8]>,
    xmp: Option<&[u8]>,
    compressor: Option<&dyn BrotliCompression>,
    need_l10: bool,
    gain_map: Option<&EncodedGainMap>,
) -> Result<Vec<u8>, EncodeError> {
    // A level-10 gain map codestream raises the whole file's level.
    let need_l10 = need_l10 || gain_map.is_some_and(|g| g.needs_level_10);
    if need_l10 || exif.is_some() || xmp.is_some() || gain_map.is_some() {
        wrap_jxl_container(
            codestream,
            if need_l10 { 10 } else { 5 },
            exif,
            xmp,
            compressor,
            gain_map.map(|g| g.bundle.as_slice()),
        )
    } else {
        Ok(codestream)
    }
}

fn write_int_bit_depth(bits: u32, w: &mut BitWriter) {
    w.write(1, 0); // floating_point_sample = false
    match bits {
        8 => w.write(2, 0),
        10 => w.write(2, 1),
        12 => w.write(2, 2),
        _ => {
            w.write(2, 3); // selector 3 → BitsOffset(6, 1)
            w.write(6, (bits - 1) as u64);
        }
    }
}

/// Write a JXL `BitDepth` field for an **IEEE-754 float** sample.
///
/// Layout: `floating_point_sample` (1 bit, = 1) followed by
/// `U32(Val(32), Val(16), Val(24), BitsOffset(6, 1))` for the total bit width
/// (f32 → selector 0, f16 → selector 1), then 4 bits = `exp_bits - 1`
/// (f32: 8 → 7 = 0b0111; f16: 5 → 4 = 0b0100).
fn write_float_bit_depth(bits: u32, exp_bits: u32, w: &mut BitWriter) {
    w.write(1, 1); // floating_point_sample = true
    match bits {
        32 => w.write(2, 0),
        16 => w.write(2, 1),
        24 => w.write(2, 2),
        _ => {
            w.write(2, 3);
            w.write(6, (bits - 1) as u64);
        }
    }
    w.write(4, (exp_bits - 1) as u64);
}

/// The image-level fields `write_image_metadata` serializes.
#[derive(Clone, Copy)]
struct ImageMetadataParams<'a> {
    tone_mapping: ToneMappingParams,
    color_encoding: &'a ColorEncoding,
    /// The single extra channel: alpha, or K when `black`.
    alpha: Option<&'a AlphaPlane>,
    black: bool,
    icc_profile: Option<&'a [u8]>,
    bps: BitsPerSample,
    lossless: bool,
    xyb_encoded: bool,
    /// Opsin matrix of an XYB codestream; a non-default one is signaled.
    xyb: &'a XybMatrix,
    grayscale: bool,
    orientation: Orientation,
    /// The frame is a lossy modular frame on the 16-bit lattice: the image
    /// (and K) declare 16 bits whatever the input depth was.
    lossy_modular_16: bool,
}

fn write_image_metadata(
    params: &ImageMetadataParams<'_>,
    scratch: &mut CoderScratch,
    w: &mut BitWriter,
) {
    let ImageMetadataParams {
        tone_mapping: tm,
        color_encoding,
        alpha,
        black,
        icc_profile,
        bps,
        lossless,
        xyb_encoded,
        xyb,
        grayscale,
        orientation,
        lossy_modular_16,
    } = *params;
    let bps = if lossy_modular_16 {
        BitsPerSample::Sixteen
    } else {
        bps
    };
    w.write(1, 0); // all_default = false
    // tone_mapping (HDR luminance) is gated by extra_fields; a non-identity
    // orientation also lives in the extra_fields block, so either forces it on.
    let extra_fields = !tm.is_default() || orientation != Orientation::Normal;
    w.write(1, if extra_fields { 1 } else { 0 }); // extra_fields
    if extra_fields {
        w.write(3, orientation.to_u3()); // orientation: 1 + u(3)
        w.write(1, 0); // have_intrinsic_size = false
        w.write(1, 0); // have_preview = false
        w.write(1, 0); // have_animation = false
    }
    if bps.is_float() {
        write_float_bit_depth(bps.bits(), bps.exp_bits(), w);
    } else {
        write_int_bit_depth(bps.bits(), w);
    }
    // modular_16_bit_buffer_sufficient: a modular integer channel of N bits needs
    // N+1 signed buffer bits (libjxl enc_modular). So any 16-bit modular channel
    // needs 17 bits → 16-bit buffers are NOT sufficient. Modular channels here:
    //   * lossless: the color image (YCoCg-R residuals, 17-bit at 16-bit input);
    //   * lossy or lossless: a 16-bit alpha extra channel (values up to 65535).
    let alpha_bits = alpha.map(|a| a.bits() as u32).unwrap_or(0);
    let needs_32 = (lossless && bps.bits() >= 16) || alpha_bits >= 16 || lossy_modular_16;
    w.write(1, if needs_32 { 0 } else { 1 });

    if let Some(alpha) = alpha {
        w.write(2, 1); // num_extra_channels = 1
        // Alpha ECI bit depth MUST match the actual stored sample width.
        // - 8-bit alpha: U8 (all_default=true gives U8 inherently)
        // - 10-bit alpha: declare ECI as 10-bit explicitly
        // - 12-bit alpha: declare ECI as 12-bit explicitly
        //
        // Mismatches show as wrong opacity: e.g. declaring 10-bit while storing
        // u8 makes the decoder compute opacity = stored/1023 ≈ 0.25 for fully-
        // opaque pixels.
        match alpha.bits() {
            bits if black => {
                // kBlack: no all-default form (that one is 8-bit alpha) and
                // no type-specific fields. A lossy modular frame codes K on
                // the 16-bit lattice too.
                w.write(1, 0); // all_default = false
                w.write(2, 2); // ec_type: BitsOffset(4, 2) selector
                w.write(4, 4 - 2); // ec_type = Black (4)
                write_int_bit_depth(if lossy_modular_16 { 16 } else { bits as u32 }, w);
                w.write(2, 0); // dim_shift = 0
                w.write(2, 0); // name length = 0
            }
            8 => {
                w.write(1, 1); // all_default = true → U8 alpha
            }
            bits => {
                w.write(1, 0); // all_default = false
                w.write(2, 0); // ec_type = Alpha (selector 0)
                if alpha.is_float() {
                    write_float_bit_depth(32, 8, w); // f32 alpha bit depth
                } else {
                    write_int_bit_depth(bits as u32, w);
                }
                w.write(2, 0); // dim_shift = 0
                w.write(2, 0); // name length = 0
                w.write(1, 0); // alpha_associated = false
            }
        }
    } else {
        w.write(2, 0); // num_extra_channels = 0
    }

    // Lossy frames are XYB unless a non-XYB coding transform was chosen;
    // lossless modular carries un-transformed pixel values.
    w.write(1, u64::from(xyb_encoded)); // xyb_encoded
    let want_icc = icc_profile.is_some();
    write_color_encoding_with_icc(color_encoding, want_icc, grayscale, w);
    // tone_mapping bundle (gated by extra_fields). ToneMapping fields:
    // intensity_target (F16), min_nits (F16), relative_to_max_display (bool),
    // linear_below (F16). We signal intensity_target and leave the rest default.
    if extra_fields {
        // ToneMapping bundle, all fields explicit (all_default = false).
        w.write(1, 0);
        let it = tm.intensity_target.unwrap_or(255.0);
        w.write(16, crate::util::f32_to_f16_bits(it) as u64); // intensity_target
        w.write(16, crate::util::f32_to_f16_bits(tm.min_nits) as u64); // min_nits
        w.write(1, if tm.relative_to_max_display { 1 } else { 0 }); // relative_to_max_display
        w.write(16, crate::util::f32_to_f16_bits(tm.linear_below) as u64); // linear_below
    }
    w.write(2, 0); // extensions: U64 selector = 0 (no extensions)
    // End of ImageMetadata. Now CustomTransformData (part of FileHeader, but kept here for
    // backward-compatible bit alignment with the no-ICC path).
    if !xyb_encoded || xyb.is_decoder_default() {
        w.write(1, 1); // CustomTransformData.all_default = 1
    } else {
        // A non-spec forward opsin matrix needs its matching inverse in the
        // codestream, so the bundle is explicit. Layout: all_default,
        // [xyb_encoded] OpsinInverseMatrix, custom_weights_mask.
        w.write(1, 0); // CustomTransformData.all_default = 0
        w.write(1, 0); // OpsinInverseMatrix.all_default = 0
        for &v in &xyb.inv {
            w.write(16, crate::util::f32_to_f16_bits(v) as u64);
        }
        for _ in 0..3 {
            // Opsin biases (defaults; the forward bias is unchanged).
            w.write(16, crate::util::f32_to_f16_bits(-0.003_793_073_4) as u64);
        }
        // Per-channel quant biases + numerator. X/Y keep the libjxl defaults;
        // B's ±1 reconstruction is raised to a full step: the explicit bundle
        // is only written for the chroma-gated content classes, where the
        // dying ±1 B residuals are exactly the desaturating ones. Measured
        // free (+0.03..0.05 SS2 at byte-identical streams) on every class
        // probed — fractal, blue-rotated victim, smooth-yellow photos;
        // overshoot past 1.0 was noise. The RDOQ dequant model keeps the
        // shared Y bias (its mismatch grows 0.05→0.07, same scale as the
        // pre-existing X mismatch).
        for v in [1.0 - 0.054_650_075, 1.0 - 0.070_054_5, 1.0, 0.145] {
            w.write(16, crate::util::f32_to_f16_bits(v) as u64);
        }
        w.write(3, 0); // custom_weights_mask = 0 (default upsampling kernels)
    }
    // ICC stream goes AFTER FileHeader, before the zero-pad to byte boundary.
    if let Some(icc) = icc_profile {
        crate::icc_codec::write_icc_stream(icc, &mut scratch.huffman_pool, w);
    }
    w.zero_pad_to_byte();
}

#[cfg(test)]
mod tests {
    use super::*;

    fn close(a: f32, b: f32) -> bool {
        (a - b).abs() < 1e-4
    }

    #[test]
    fn quality_mapping_anchor_points() {
        assert!(close(distance_from_quality(100.0), 0.05));
        assert!(close(distance_from_quality(99.0), 0.1));
        assert!(close(distance_from_quality(90.0), 1.0));
        assert!(close(distance_from_quality(30.0), 6.4));
        // Below 30, the formula is quadratic-ish; q=25 must come in just above 6.4.
        let d25 = distance_from_quality(25.0);
        assert!(d25 > 6.4 && d25 < 7.0, "q=25 -> {d25}");
        // Far below 30, it climbs and clamps at 25.
        assert!(close(distance_from_quality(0.0), 25.0));
        assert!(close(distance_from_quality(-50.0), 25.0));
        // Above 100, clamped to the practical VarDCT endpoint.
        assert!(close(distance_from_quality(110.0), 0.05));
    }

    #[test]
    fn quality_mapping_monotone() {
        // Strictly decreasing in quality.
        let mut prev = distance_from_quality(0.0);
        for q in 1..=100 {
            let d = distance_from_quality(q as f32);
            assert!(d <= prev, "non-monotonic at q={q}: prev={prev}, d={d}");
            prev = d;
        }
    }

    #[test]
    fn default_speed_is_fast() {
        assert_eq!(Speed::default(), Speed::Fast);
        assert_eq!(EncodeConfig::default().speed, Speed::Fast);
    }

    #[test]
    fn invisible_fill_defaults_on_and_can_be_disabled() {
        assert!(EncodeConfig::default().fill_invisible);
        let config = EncodeConfig::default().with_fill_invisible(false);
        assert!(!config.fill_invisible);
        assert!(
            !EncodeConfigImpl::default()
                .with_progressive_from(&config)
                .fill_invisible
        );
    }

    #[test]
    fn srgb_linearization_uses_requested_threads() {
        use std::collections::HashSet;
        use std::sync::{Barrier, Mutex};

        let config = EncodeConfig::default().with_num_threads(4);
        let ctx = lossy_context(&config, 1.0, XybMatrix::SPEC, 1);
        let mut scratch = Box::<CoderScratch>::default();
        let mut image = Image3F::new(8, 4);
        let barrier = Barrier::new(4);
        let threads = Mutex::new(HashSet::new());

        for_each_linear_band(&mut image, &ctx, &mut scratch, |_start, _band| {
            threads.lock().unwrap().insert(std::thread::current().id());
            barrier.wait();
        });

        assert_eq!(threads.into_inner().unwrap().len(), 4);
    }

    #[test]
    #[should_panic(expected = "quality must not be NaN")]
    fn quality_nan_panics() {
        let _ = distance_from_quality(f32::NAN);
    }
}

#[cfg(test)]
mod encode_smoke_tests {
    use super::*;

    const W: usize = 16;
    const H: usize = 16;

    fn rgb8() -> Vec<u8> {
        (0..W * H * 3).map(|i| (i % 256) as u8).collect()
    }

    fn box_payload<'a>(container: &'a [u8], wanted: &[u8; 4]) -> Option<&'a [u8]> {
        let mut pos = 0usize;
        while pos + 8 <= container.len() {
            let small = u32::from_be_bytes(container[pos..pos + 4].try_into().unwrap()) as usize;
            let kind: &[u8; 4] = container[pos + 4..pos + 8].try_into().unwrap();
            let (header, size) = if small == 1 {
                if pos + 16 > container.len() {
                    return None;
                }
                (
                    16,
                    u64::from_be_bytes(container[pos + 8..pos + 16].try_into().unwrap()) as usize,
                )
            } else {
                (8, small)
            };
            if size < header || pos.checked_add(size)? > container.len() {
                return None;
            }
            if kind == wanted {
                return Some(&container[pos + header..pos + size]);
            }
            pos += size;
        }
        None
    }

    fn box_kinds(container: &[u8]) -> Vec<[u8; 4]> {
        let mut kinds = Vec::new();
        let mut pos = 0usize;
        while pos + 8 <= container.len() {
            let size = u32::from_be_bytes(container[pos..pos + 4].try_into().unwrap()) as usize;
            kinds.push(container[pos + 4..pos + 8].try_into().unwrap());
            assert!(size >= 8, "large boxes not expected in these tests");
            pos += size;
        }
        assert_eq!(pos, container.len());
        kinds
    }

    fn gain_map_metadata() -> crate::IsoGainMap {
        crate::IsoGainMap::from_floats(&crate::GainMapFloats {
            max: [2.0; 3],
            alternate_hdr_headroom: 2.0,
            ..crate::GainMapFloats::default()
        })
        .unwrap()
    }

    fn gray_gain_map(w: usize, h: usize) -> crate::GainMap {
        let gain: Vec<u8> = (0..w * h).map(|i| (i * 4) as u8).collect();
        crate::GainMap::gray8(gain, w, h, gain_map_metadata())
    }

    #[test]
    fn gain_map_is_written_to_a_jhgm_box_after_the_codestream() {
        let md = gain_map_metadata();
        let gm = gray_gain_map(8, 8)
            .with_lossless(true)
            .with_alternate_color_encoding(ColorEncoding::bt2020_pq());
        let encoded = encode_image(&rgb8(), W, H, &lossy().with_gain_map(gm)).unwrap();

        assert_eq!(
            box_kinds(&encoded),
            [*b"JXL ", *b"ftyp", *b"jxll", *b"jxlc", *b"jhgm"]
        );
        assert_eq!(box_payload(&encoded, b"jxll"), Some(&[5u8][..]));
        let jhgm = box_payload(&encoded, b"jhgm").expect("jhgm box");
        let p = crate::gain_map::parse_jhgm_bundle(jhgm).unwrap();
        assert_eq!(p.version, 0);
        assert_eq!(crate::IsoGainMap::from_metadata(p.metadata).unwrap(), md);
        assert!(!p.color_encoding.is_empty());
        assert!(p.alt_icc.is_empty());
        assert_eq!(&p.codestream[..2], &[0xFF, 0x0A]);
        // A naked codestream: no container signature inside the bundle.
        assert_ne!(&p.codestream[..4], &[0, 0, 0, 0x0C]);
    }

    #[test]
    fn gain_map_box_precedes_metadata_boxes() {
        let exif = vec![b'I', b'I', 42, 0, 8, 0, 0, 0];
        let encoded = encode_image(
            &rgb8(),
            W,
            H,
            &lossy()
                .with_exif(exif.clone())
                .with_xmp(b"<x/>".to_vec())
                .with_gain_map(gray_gain_map(4, 4)),
        )
        .unwrap();
        assert_eq!(
            box_kinds(&encoded),
            [
                *b"JXL ", *b"ftyp", *b"jxll", *b"jxlc", *b"jhgm", *b"Exif", *b"xml "
            ]
        );
        assert_eq!(box_payload(&encoded, b"xml "), Some(&b"<x/>"[..]));
    }

    #[test]
    fn level_10_gain_map_raises_the_file_level() {
        let gain: Vec<u16> = (0..4 * 4).map(|i| (i * 4000) as u16).collect();
        let gm = crate::GainMap::gray16(gain, 16, 4, 4, gain_map_metadata()).with_lossless(true);
        let encoded = encode_image(&rgb8(), W, H, &lossy().with_gain_map(gm)).unwrap();
        assert_eq!(box_payload(&encoded, b"jxll"), Some(&[10u8][..]));
        let jhgm = box_payload(&encoded, b"jhgm").unwrap();
        let p = crate::gain_map::parse_jhgm_bundle(jhgm).unwrap();
        assert_eq!(&p.codestream[..2], &[0xFF, 0x0A]);
    }

    #[test]
    fn gain_map_rides_along_every_primary_encoder_path() {
        let cfg = lossy().with_gain_map(
            crate::GainMap::rgb8(
                (0..4 * 4 * 3).map(|i| i as u8).collect(),
                4,
                4,
                gain_map_metadata(),
            )
            .with_distance(3.0),
        );
        let rgba: Vec<u8> = (0..W * H * 4).map(|i| i as u8).collect();
        let gray: Vec<u8> = (0..W * H).map(|i| i as u8).collect();
        let rgb16: Vec<u16> = (0..W * H * 3).map(|i| (i * 7) as u16).collect();
        let f32s: Vec<f32> = (0..W * H * 3).map(|i| (i % 255) as f32 / 255.0).collect();
        let outputs = [
            encode_image_with_alpha(&rgba, W, H, &cfg).unwrap(),
            encode_image_gray(&gray, W, H, &cfg).unwrap(),
            encode_image_16bit(&rgb16, W, H, &cfg).unwrap(),
            encode_image_f32(&f32s, W, H, &cfg).unwrap(),
            encode_image(
                &rgb8(),
                W,
                H,
                &lossless().with_gain_map(gray_gain_map(4, 4)),
            )
            .unwrap(),
            encode_image_16bit(&rgb16, W, H, &lossless().with_gain_map(gray_gain_map(4, 4)))
                .unwrap(),
            encode_image_f32(&f32s, W, H, &lossless().with_gain_map(gray_gain_map(4, 4))).unwrap(),
        ];
        for out in &outputs {
            let jhgm = box_payload(out, b"jhgm").expect("every path writes the jhgm box");
            let p = crate::gain_map::parse_jhgm_bundle(jhgm).unwrap();
            assert_eq!(&p.codestream[..2], &[0xFF, 0x0A]);
        }
    }

    #[test]
    fn invalid_gain_map_fails_the_encode() {
        let gm = crate::GainMap::gray8(vec![0; 15], 4, 4, gain_map_metadata());
        assert!(matches!(
            encode_image(&rgb8(), W, H, &lossy().with_gain_map(gm)),
            Err(EncodeError::GainMapSizeMismatch {
                expected: 16,
                actual: 15
            })
        ));
    }

    #[test]
    fn xmp_is_written_to_an_xml_box() {
        let xmp = b"<x:xmpmeta xmlns:x=\"adobe:ns:meta/\"/>";
        let encoded = encode_image(&rgb8(), W, H, &lossy().with_xmp(xmp.to_vec())).unwrap();
        assert_eq!(box_payload(&encoded, b"xml "), Some(xmp.as_slice()));
    }

    #[test]
    fn custom_brotli_writes_brob_metadata() {
        struct MarkerCompressor;
        impl BrotliCompression for MarkerCompressor {
            fn compress(&self, data: &[u8]) -> Result<Vec<u8>, EncodeError> {
                assert_eq!(data, b"<x:xmpmeta/>");
                Ok(vec![0xAA, 0xBB])
            }
        }

        let encoded = encode_image(
            &rgb8(),
            W,
            H,
            &lossy()
                .with_xmp(b"<x:xmpmeta/>".to_vec())
                .with_brotli_compression(Box::new(MarkerCompressor)),
        )
        .unwrap();
        assert_eq!(box_payload(&encoded, b"brob"), Some(&b"xml \xAA\xBB"[..]));
        assert!(box_payload(&encoded, b"xml ").is_none());
    }

    #[test]
    fn custom_brotli_error_is_returned() {
        struct FailingCompressor;
        impl BrotliCompression for FailingCompressor {
            fn compress(&self, _data: &[u8]) -> Result<Vec<u8>, EncodeError> {
                Err(EncodeError::Brotli("backend failed".into()))
            }
        }

        assert_eq!(
            encode_image(
                &rgb8(),
                W,
                H,
                &lossy()
                    .with_xmp(b"<x:xmpmeta/>".to_vec())
                    .with_brotli_compression(Box::new(FailingCompressor)),
            ),
            Err(EncodeError::Brotli("backend failed".into()))
        );
    }

    fn rgba8() -> Vec<u8> {
        (0..W * H * 4).map(|i| (i % 256) as u8).collect()
    }

    fn rgb16() -> Vec<u16> {
        (0..W * H * 3).map(|i| (i % 65536) as u16).collect()
    }

    fn rgba16() -> Vec<u16> {
        (0..W * H * 4).map(|i| (i % 65536) as u16).collect()
    }

    fn gray8() -> Vec<u8> {
        (0..W * H).map(|i| (i % 256) as u8).collect()
    }

    fn gray_alpha8() -> Vec<u8> {
        (0..W * H * 2).map(|i| (i % 256) as u8).collect()
    }

    fn gray16() -> Vec<u16> {
        (0..W * H).map(|i| (i % 65536) as u16).collect()
    }

    fn gray_alpha16() -> Vec<u16> {
        (0..W * H * 2).map(|i| (i % 65536) as u16).collect()
    }

    fn rgb10() -> Vec<u16> {
        (0..W * H * 3).map(|i| (i % 1024) as u16).collect()
    }

    fn rgba10() -> Vec<u16> {
        (0..W * H * 4).map(|i| (i % 1024) as u16).collect()
    }

    fn rgb12() -> Vec<u16> {
        (0..W * H * 3).map(|i| (i % 4096) as u16).collect()
    }

    fn rgba12() -> Vec<u16> {
        (0..W * H * 4).map(|i| (i % 4096) as u16).collect()
    }

    fn gray10() -> Vec<u16> {
        (0..W * H).map(|i| (i % 1024) as u16).collect()
    }

    fn gray_alpha10() -> Vec<u16> {
        (0..W * H * 2).map(|i| (i % 1024) as u16).collect()
    }

    fn gray12() -> Vec<u16> {
        (0..W * H).map(|i| (i % 4096) as u16).collect()
    }

    fn gray_alpha12() -> Vec<u16> {
        (0..W * H * 2).map(|i| (i % 4096) as u16).collect()
    }

    fn rgb_f32() -> Vec<f32> {
        (0..W * H * 3).map(|i| (i % 256) as f32 / 255.0).collect()
    }

    fn rgba_f32() -> Vec<f32> {
        (0..W * H * 4).map(|i| (i % 256) as f32 / 255.0).collect()
    }

    fn gray_f32() -> Vec<f32> {
        (0..W * H).map(|i| (i % 256) as f32 / 255.0).collect()
    }

    fn lossy() -> EncodeConfig {
        EncodeConfig::default().with_distance(1.0)
    }

    fn lossless() -> EncodeConfig {
        EncodeConfig::default().with_lossless(true)
    }

    fn ok(r: Result<Vec<u8>, EncodeError>) {
        let bytes = r.expect("encode failed");
        assert!(!bytes.is_empty(), "encoded output is empty");
    }

    // --- encode_image (RGB u8) ---

    #[test]
    fn rgb8_lossy() {
        ok(encode_image(&rgb8(), W, H, &lossy()));
    }

    #[test]
    fn progressive_dc_only_where_supported() {
        // 160x96 has a 20x12 DC image, large enough to squeeze.
        let (w, h) = (160, 96);
        let rgb: Vec<u8> = (0..w * h)
            .flat_map(|i| {
                let (x, y) = (i % w, i / w);
                [(x + y) as u8, (2 * x) as u8, ((x * y) % 251) as u8]
            })
            .collect();
        let rgba: Vec<u8> = rgb
            .as_chunks::<3>()
            .0
            .iter()
            .flat_map(|&[r, g, b]| [r, g, b, 200])
            .collect();
        for speed in [Speed::Fast, Speed::Slow] {
            let off = lossy().with_speed(speed).with_num_threads(1);
            let on = off.clone().with_progressive_dc(true);
            let full = encode_image(&rgb, w, h, &on).unwrap();
            assert_ne!(encode_image(&rgb, w, h, &off).unwrap(), full);
            // Level counts clamp to the 1..=2 this DC image allows.
            let levels = |n| encode_image(&rgb, w, h, &on.clone().with_progressive_dc_levels(n));
            assert_eq!(levels(99).unwrap(), full);
            assert_eq!(levels(0).unwrap(), levels(1).unwrap());
            assert_ne!(levels(1).unwrap(), full);
            // A 2x2 DC image cannot be squeezed; alpha frames keep their DC.
            assert_eq!(
                encode_image(&rgb8(), W, H, &off).unwrap(),
                encode_image(&rgb8(), W, H, &on).unwrap()
            );
            assert_eq!(
                encode_image_with_alpha(&rgba, w, h, &off).unwrap(),
                encode_image_with_alpha(&rgba, w, h, &on).unwrap()
            );
        }
    }

    #[test]
    fn invisible_fill_preserves_lossless_and_nontransparent_inputs() {
        let on = lossy().with_num_threads(1);
        let off = on.clone().with_fill_invisible(false);
        assert_eq!(
            encode_image(&rgb8(), W, H, &on).unwrap(),
            encode_image(&rgb8(), W, H, &off).unwrap()
        );
        let mut rgba = rgba8();
        for px in rgba.as_chunks_mut::<4>().0 {
            px[3] = 128; // Partial alpha must not be premultiplied or filled.
        }
        for coding in [
            CodingTransform::Xyb,
            CodingTransform::Rgb,
            CodingTransform::YCbCr,
        ] {
            let on = on.clone().with_coding_transform(coding);
            let off = off.clone().with_coding_transform(coding);
            assert_eq!(
                encode_image_with_alpha(&rgba, W, H, &on).unwrap(),
                encode_image_with_alpha(&rgba, W, H, &off).unwrap()
            );
        }
        let lossless_on = on.with_lossless(true);
        let lossless_off = off.with_lossless(true);
        assert_eq!(
            encode_image_with_alpha(&rgba8(), W, H, &lossless_on).unwrap(),
            encode_image_with_alpha(&rgba8(), W, H, &lossless_off).unwrap()
        );
    }

    #[test]
    fn public_lossy_paths_share_the_minimum_distance() {
        for speed in [Speed::Fast, Speed::Medium, Speed::Slow] {
            let at_floor = EncodeConfig::default()
                .with_speed(speed)
                .with_distance(0.05);
            for distance in [0.001, 0.03, 0.049] {
                let below = at_floor.clone().with_distance(distance);
                macro_rules! same_output {
                    ($encode:ident, $pixels:expr) => {
                        assert_eq!(
                            $encode(&$pixels, W, H, &below).unwrap(),
                            $encode(&$pixels, W, H, &at_floor).unwrap(),
                            "{}: speed={speed:?} d={distance}",
                            stringify!($encode)
                        );
                    };
                }
                same_output!(encode_image, rgb8());
                same_output!(encode_image_with_alpha, rgba8());
                same_output!(encode_image_16bit, rgb16());
                same_output!(encode_image_gray, gray8());
                same_output!(encode_image_gray_16bit, gray16());
                same_output!(encode_image_f32, rgb_f32());
                same_output!(encode_image_gray_f32, gray_f32());
            }
        }
    }

    /// Thin anti-aliased dark curves on a smooth gradient: the content class
    /// splines exist for.
    #[cfg(feature = "splines")]
    fn line_art(size: usize) -> Vec<u8> {
        let mut px = vec![0u8; size * size * 3];
        for y in 0..size {
            for x in 0..size {
                let mut v = 150.0 + 60.0 * (x + y) as f32 / (2 * size) as f32;
                for k in 0..6 {
                    let phase = k as f32 * 0.9;
                    let cy = size as f32 * (0.15 + 0.13 * k as f32)
                        + 18.0 * (x as f32 * 0.035 + phase).sin();
                    let d = (y as f32 - cy).abs();
                    v -= 120.0 * (-0.5 * (d / 0.8).powi(2)).exp();
                }
                let i = (y * size + x) * 3;
                px[i] = v.clamp(0.0, 255.0) as u8;
                px[i + 1] = (v * 0.92).clamp(0.0, 255.0) as u8;
                px[i + 2] = (v * 0.85).clamp(0.0, 255.0) as u8;
            }
        }
        px
    }

    #[cfg(feature = "splines")]
    fn slow_lossy(distance: f32) -> EncodeConfig {
        EncodeConfig::default()
            .with_distance(distance)
            .with_speed(Speed::Slow)
    }

    #[test]
    #[cfg(feature = "splines")]
    fn splines_reduce_thin_line_art() {
        const S: usize = 256;
        let pixels = line_art(S);
        let plain = encode_image(&pixels, S, S, &slow_lossy(3.0)).unwrap();
        let with = encode_image(&pixels, S, S, &slow_lossy(3.0).with_splines(true)).unwrap();
        assert!(
            with.len() * 100 < plain.len() * 90,
            "splines should win clearly on thin line art: {} vs {}",
            with.len(),
            plain.len()
        );
    }

    #[test]
    #[cfg(feature = "splines")]
    fn splines_join_crossed_grid_lines() {
        const S: usize = 256;
        let mut pixels = Vec::with_capacity(S * S * 3);
        for y in 0..S {
            for x in 0..S {
                let mut v = 170.0 + 70.0 * (x + y) as f32 / (2 * S) as f32;
                if (12..S - 12).contains(&x) && (12..S - 12).contains(&y) {
                    for axis in [x, y] {
                        let d = ((axis - 12 + 18) % 36) as f32 - 18.0;
                        v -= 65.0 * (-0.5 * (d / 0.65).powi(2)).exp();
                    }
                }
                pixels.extend([v as u8, (v * 0.95) as u8, (v * 0.9) as u8]);
            }
        }
        let config = slow_lossy(2.0).with_patches(false).with_num_threads(1);
        let plain = encode_image(&pixels, S, S, &config).unwrap();
        let config = config.with_splines(true);
        let joined = encode_image(&pixels, S, S, &config).unwrap();
        assert!(
            joined.len() * 100 < plain.len() * 80,
            "whole grid lines should save more than isolated fragments: {} vs {}",
            joined.len(),
            plain.len()
        );
        assert_eq!(
            joined,
            encode_image(&pixels, S, S, &config.with_num_threads(4)).unwrap()
        );
    }

    #[test]
    #[cfg(feature = "splines")]
    fn splines_are_inert_without_lines() {
        const S: usize = 128;
        let mut pixels = vec![0u8; S * S * 3];
        for y in 0..S {
            for x in 0..S {
                let i = (y * S + x) * 3;
                pixels[i] = (x * 2) as u8;
                pixels[i + 1] = (y * 2) as u8;
                pixels[i + 2] = (x + y) as u8;
            }
        }
        let plain = encode_image(&pixels, S, S, &slow_lossy(2.0)).unwrap();
        let with = encode_image(&pixels, S, S, &slow_lossy(2.0).with_splines(true)).unwrap();
        assert_eq!(plain, with);
    }

    /// Gaussian point sources on a dark, smooth sky: the content class dots
    /// exist for.
    #[cfg(feature = "splines")]
    fn star_field(size: usize) -> Vec<u8> {
        let mut state = 0x2545_f491_u32;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as f32 / u32::MAX as f32
        };
        let mut sky = vec![[0f32; 3]; size * size];
        for (i, p) in sky.iter_mut().enumerate() {
            let (x, y) = ((i % size) as f32, (i / size) as f32);
            *p = [8.0 + 0.03 * x, 10.0 + 0.02 * y, 22.0 + 0.04 * (x + y)];
        }
        for _ in 0..size * size / 120 {
            let (cx, cy) = (
                6.0 + next() * (size - 12) as f32,
                6.0 + next() * (size - 12) as f32,
            );
            let amp = 40.0 + 200.0 * next() * next();
            let sigma = 0.6 + 0.4 * next();
            let tint = [0.8 + 0.2 * next(), 0.9, 1.0];
            for y in cy as usize - 4..=cy as usize + 4 {
                for x in cx as usize - 4..=cx as usize + 4 {
                    let d2 = (x as f32 - cx).powi(2) + (y as f32 - cy).powi(2);
                    let v = amp * (-0.5 * d2 / (sigma * sigma)).exp();
                    for (c, t) in sky[y * size + x].iter_mut().zip(tint) {
                        *c += v * t;
                    }
                }
            }
        }
        sky.iter()
            .flat_map(|p| p.map(|c| c.clamp(0.0, 255.0) as u8))
            .collect()
    }

    #[test]
    #[cfg(feature = "splines")]
    fn dots_shrink_star_fields() {
        const S: usize = 256;
        let pixels = star_field(S);
        let config = slow_lossy(3.0).with_num_threads(1);
        let plain = encode_image(&pixels, S, S, &config).unwrap();
        let config = config.with_dots(true);
        let with = encode_image(&pixels, S, S, &config).unwrap();
        // The synthetic field's margin sits at ~5%; sparser fields flip on
        // how the nearly flat sky blocks quantize.
        assert!(
            with.len() < plain.len(),
            "dots should win on a star field: {} vs {}",
            with.len(),
            plain.len()
        );
        assert_eq!(
            with,
            encode_image(&pixels, S, S, &config.with_num_threads(4)).unwrap()
        );
    }

    #[test]
    #[cfg(feature = "splines")]
    fn dots_shrink_dark_spot_fields_and_are_thread_deterministic() {
        const S: usize = 256;
        let pixels: Vec<_> = star_field(S).into_iter().map(|v| 255 - v).collect();
        let config = slow_lossy(2.0).with_patches(false).with_num_threads(1);
        let plain = encode_image(&pixels, S, S, &config).unwrap();
        let config = config.with_dots(true);
        let with = encode_image(&pixels, S, S, &config).unwrap();
        assert!(
            with.len() < plain.len(),
            "dark spots: {} vs {}",
            with.len(),
            plain.len()
        );
        assert_eq!(
            with,
            encode_image(&pixels, S, S, &config.with_num_threads(4)).unwrap()
        );
    }

    #[test]
    #[cfg(feature = "splines")]
    fn dots_are_inert_without_points() {
        const S: usize = 128;
        let pixels = line_art(S);
        let config = slow_lossy(2.0).with_splines(true);
        assert_eq!(
            encode_image(&pixels, S, S, &config).unwrap(),
            encode_image(&pixels, S, S, &config.clone().with_dots(true)).unwrap()
        );
    }

    #[test]
    #[cfg(feature = "splines")]
    fn dots_with_alpha_are_thread_deterministic() {
        const S: usize = 256;
        let rgba: Vec<_> = star_field(S)
            .as_chunks::<3>()
            .0
            .iter()
            .enumerate()
            .flat_map(|(i, p)| [p[0], p[1], p[2], (64 + i % 192) as u8])
            .collect();
        let config = slow_lossy(3.0).with_num_threads(1).with_dots(true);
        let with = encode_image_with_alpha(&rgba, S, S, &config).unwrap();
        assert_eq!(
            with,
            encode_image_with_alpha(&rgba, S, S, &config.clone().with_num_threads(4)).unwrap()
        );
        assert_ne!(
            with,
            encode_image_with_alpha(&rgba, S, S, &config.with_dots(false)).unwrap()
        );
    }

    #[test]
    #[cfg(feature = "splines")]
    fn dots_only_run_at_slow_speed_and_default_decoding_speed() {
        const S: usize = 128;
        let pixels = star_field(S);
        for config in [
            EncodeConfig::default()
                .with_distance(3.0)
                .with_speed(Speed::Fast),
            slow_lossy(3.0).with_decoding_speed(DecodingSpeed::Fast),
        ] {
            assert_eq!(
                encode_image(&pixels, S, S, &config).unwrap(),
                encode_image(&pixels, S, S, &config.clone().with_dots(true)).unwrap()
            );
        }
    }

    #[test]
    #[cfg(feature = "splines")]
    fn splines_only_run_at_slow_speed_and_default_decoding_speed() {
        const S: usize = 256;
        let pixels = line_art(S);
        let fast = EncodeConfig::default()
            .with_distance(3.0)
            .with_speed(Speed::Fast);
        assert_eq!(
            encode_image(&pixels, S, S, &fast).unwrap(),
            encode_image(&pixels, S, S, &fast.clone().with_splines(true)).unwrap()
        );
        let quick_decode = slow_lossy(3.0).with_decoding_speed(DecodingSpeed::Fast);
        assert_eq!(
            encode_image(&pixels, S, S, &quick_decode).unwrap(),
            encode_image(&pixels, S, S, &quick_decode.clone().with_splines(true)).unwrap()
        );
    }

    #[test]
    #[cfg(feature = "splines")]
    fn splines_coexist_with_patches() {
        const S: usize = 256;
        let pixels = line_art(S);
        let both = slow_lossy(3.0).with_splines(true).with_patches(true);
        let plain = encode_image(&pixels, S, S, &slow_lossy(3.0).with_patches(true)).unwrap();
        let with = encode_image(&pixels, S, S, &both).unwrap();
        assert!(with.len() < plain.len());
    }

    #[test]
    #[cfg(feature = "splines")]
    fn splines_cross_repeated_tiles() {
        // Graph paper with a curve. The grid period does not divide the tile
        // size, so tiles repeat only here and there and every line crosses
        // some; the noise band keeps the glyph detector away.
        const S: usize = 256;
        const PERIOD: f32 = 12.3;
        let rule = |t: usize| {
            let d = ((t as f32 + PERIOD / 2.0) % PERIOD - PERIOD / 2.0).abs();
            (1.0 - d).max(0.0)
        };
        let mut pixels = vec![0u8; S * S * 3];
        let mut state = 0x1234_5678u32;
        for y in 0..S {
            for x in 0..S {
                let mut v = 236.0 - 46.0 * rule(x).max(rule(y));
                let cy = 48.0 + 30.0 * (x as f32 * 0.021).sin();
                v -= 170.0 * (-0.5 * ((y as f32 - cy) / 0.9).powi(2)).exp();
                if y >= 96 {
                    state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                    v = (state >> 24) as f32;
                }
                let i = (y * S + x) * 3;
                pixels[i] = (v * 0.35).clamp(0.0, 255.0) as u8;
                pixels[i + 1] = (v * 0.45).clamp(0.0, 255.0) as u8;
                pixels[i + 2] = v.clamp(0.0, 255.0) as u8;
            }
        }
        let patched = encode_image(&pixels, S, S, &slow_lossy(2.0).with_patches(true)).unwrap();
        let both = slow_lossy(2.0).with_splines(true).with_patches(true);
        let with = encode_image(&pixels, S, S, &both).unwrap();
        assert!(
            with.len() < patched.len(),
            "splines must survive next to tile patches: {} >= {}",
            with.len(),
            patched.len()
        );
    }

    #[test]
    fn lossy_patches_are_rate_safe() {
        let plain = encode_image(&rgb8(), W, H, &lossy()).unwrap();
        let checked = encode_image(&rgb8(), W, H, &lossy().with_patches(true)).unwrap();
        assert!(checked.len() <= plain.len());
    }

    #[test]
    fn fast_lossy_patches_are_rate_safe_on_unrepeated_ink() {
        // Saturated line drawings in separate 60-pixel tiles, each broken
        // by its own gaps: every tile is a singleton glyph, so the whole
        // image lands in the atlas, which below Slow is coded without a
        // palette or a learned tree.
        const SIZE: usize = 256;
        let mut pixels = vec![0u8; SIZE * SIZE * 3];
        for y in 0..SIZE {
            for x in 0..SIZE {
                if (x % 8 == 3 || y % 8 == 3) && x % 64 < 60 && y % 64 < 60 {
                    let blue = if (x / 64 + y / 64) % 2 == 0 { 254 } else { 0 };
                    pixels[(y * SIZE + x) * 3..][..3].copy_from_slice(&[252, 0, blue]);
                }
            }
        }
        let mut state = 0x2545_f491u32;
        let mut next = || {
            state ^= state << 13;
            state ^= state >> 17;
            state ^= state << 5;
            state as usize
        };
        for _ in 0..60 {
            let (x0, y0) = (next() % (SIZE - 8), next() % (SIZE - 8));
            let (w, h) = (2 + next() % 6, 1 + next() % 5);
            for y in y0..y0 + h {
                pixels[(y * SIZE + x0) * 3..][..w * 3].fill(0);
            }
        }
        for distance in [1.0f32, 3.0] {
            let plain = EncodeConfig::default().with_distance(distance);
            let patched = plain.clone().with_patches(true);
            let plain = encode_image(&pixels, SIZE, SIZE, &plain).unwrap();
            let patched = encode_image(&pixels, SIZE, SIZE, &patched).unwrap();
            assert!(
                patched.len() * 10 <= plain.len() * 11,
                "d={distance}: {} vs {}",
                patched.len(),
                plain.len()
            );
        }
    }

    #[test]
    fn lossy_patches_reduce_repeated_regions() {
        const PW: usize = 256;
        const PH: usize = 256;
        let mut state = 0x89ab_cdefu32;
        let mut pixels = vec![0u8; PW * PH * 3];
        for sample in &mut pixels {
            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            *sample = (state >> 24) as u8;
        }
        let tile: Vec<u8> = (0..16)
            .flat_map(|y| pixels[(y * PW * 3)..(y * PW * 3 + 48)].iter().copied())
            .collect();
        for ty in 0..16 {
            for tx in 0..16 {
                if (tx + ty) % 2 != 0 {
                    continue;
                }
                for y in 0..16 {
                    let dst = ((ty * 16 + y) * PW + tx * 16) * 3;
                    pixels[dst..dst + 48].copy_from_slice(&tile[y * 48..(y + 1) * 48]);
                }
            }
        }
        let plain = encode_image(&pixels, PW, PH, &lossy().with_patches(false)).unwrap();
        let patched = encode_image(&pixels, PW, PH, &lossy().with_patches(true)).unwrap();
        assert!(
            patched.len() < plain.len(),
            "lossy patches should win on repeated complex regions: {} >= {}",
            patched.len(),
            plain.len()
        );
    }

    #[test]
    fn rgb8_slow_low_quality_lossy() {
        const SIDE: usize = 64;
        let pixels: Vec<u8> = (0..SIDE * SIDE * 3).map(|i| (i % 251) as u8).collect();
        ok(encode_image(
            &pixels,
            SIDE,
            SIDE,
            &EncodeConfig::default()
                .with_distance(3.0)
                .with_speed(Speed::Slow),
        ));
    }

    #[test]
    fn rgb8_slow_low_quality_rect_merge_lossy() {
        let config = EncodeConfig::default()
            .with_distance(2.5)
            .with_speed(Speed::Slow);
        for (width, height) in [(32, 64), (64, 32)] {
            let pixels = vec![128u8; width * height * 3];
            ok(encode_image(&pixels, width, height, &config));
        }
    }

    #[test]
    fn lossy_output_is_independent_of_thread_count() {
        const WIDTH: usize = 257;
        const HEIGHT: usize = 65;
        let input: Vec<u8> = (0..WIDTH * HEIGHT * 3)
            .map(|i| i.wrapping_mul(37).wrapping_add((i / 7).wrapping_mul(13)) as u8)
            .collect();
        let config = lossy().with_speed(Speed::Slow);

        let single = encode_image(&input, WIDTH, HEIGHT, &config.clone().with_num_threads(1))
            .expect("single-threaded lossy encode failed");
        let threaded = encode_image(&input, WIDTH, HEIGHT, &config.with_num_threads(4))
            .expect("multi-threaded lossy encode failed");

        assert_eq!(single, threaded);
    }

    #[test]
    fn rgba_lossy_patches_reduce_repeated_regions() {
        const PW: usize = 256;
        const PH: usize = 256;
        let mut pixels = vec![0u8; PW * PH * 4];
        for (i, px) in pixels.as_chunks_mut::<4>().0.iter_mut().enumerate() {
            let (x, y) = (i % PW, i / PW);
            let (tx, ty) = (x % 16, y % 16);
            // Glyph-like repeated tiles on 3/4 of the grid, noise elsewhere.
            if (x / 16 + y / 16) % 4 != 0 {
                // Few distinct colors, so the tile is palette-friendly and the
                // routing sends it to the modular atlas.
                px[0] = ((tx / 4) * 40 + (ty / 4) * 17) as u8;
                px[1] = ((tx / 4) * 25 + (ty / 4) * 31) as u8;
                px[2] = ((tx / 4) * 11 + (ty / 4) * 45) as u8;
            } else {
                let s = (i as u32)
                    .wrapping_mul(1_664_525)
                    .wrapping_add(1_013_904_223);
                px[0] = (s >> 24) as u8;
                px[1] = (s >> 16) as u8;
                px[2] = (s >> 8) as u8;
            }
            px[3] = 255;
        }
        let cfg = |patches: bool| {
            EncodeConfig::default()
                .with_lossless(false)
                .with_distance(1.0)
                .with_patches(patches)
        };
        let plain = encode_image_with_alpha(&pixels, PW, PH, &cfg(false)).unwrap();
        let patched = encode_image_with_alpha(&pixels, PW, PH, &cfg(true)).unwrap();
        assert!(
            patched.len() < plain.len(),
            "alpha image patches should win: {} >= {}",
            patched.len(),
            plain.len()
        );
    }

    #[test]
    fn rgb8_lossless() {
        ok(encode_image(&rgb8(), W, H, &lossless()));
    }

    #[test]
    fn rgb8_lossless_patches_reduce_repeated_tiles() {
        const PW: usize = 96;
        const PH: usize = 64;
        let mut pixels = vec![0u8; PW * PH * 3];
        for y in 0..PH {
            for x in 0..PW {
                let tx = x % 16;
                let ty = y % 16;
                let p = (y * PW + x) * 3;
                pixels[p] = (tx * 13 + ty * 3) as u8;
                pixels[p + 1] = (tx * 5 + ty * 11) as u8;
                pixels[p + 2] = (tx * 7 + ty * 9) as u8;
            }
        }
        let plain = encode_image(&pixels, PW, PH, &lossless().with_patches(false)).unwrap();
        let patched = encode_image(&pixels, PW, PH, &lossless().with_patches(true)).unwrap();
        assert!(
            patched.len() < plain.len(),
            "patch dictionary should reduce a repeated-tile image: {} >= {}",
            patched.len(),
            plain.len()
        );
    }

    #[test]
    fn rgb8_lossless_patches_fall_back_when_rate_is_worse() {
        const PW: usize = 64;
        const PH: usize = 64;
        let mut state = 0x1234_5678u32;
        let mut pixels = vec![0u8; PW * PH * 3];
        for sample in &mut pixels {
            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
            *sample = (state >> 24) as u8;
        }
        for y in 0..16 {
            for x in 0..48 {
                let pixel = (y * PW + x) * 3;
                for sample in &mut pixels[pixel..pixel + 3] {
                    *sample = 0;
                }
            }
        }

        let plain = encode_image(&pixels, PW, PH, &lossless()).unwrap();
        let checked = encode_image(&pixels, PW, PH, &lossless().with_patches(true)).unwrap();
        assert_eq!(checked, plain, "a losing patch candidate must be discarded");
    }

    #[test]
    fn rgb8_lossless_slow_adaptive() {
        ok(encode_image(
            &rgb8(),
            W,
            H,
            &lossless().with_speed(Speed::Slow),
        ));
    }

    #[test]
    fn fastest_speed_encodes_dct8_only() {
        // A smooth gradient makes Fast/Slow merge into large transforms, so a
        // Fastest stream (all 8x8) must differ; both must be valid encodes.
        const WIDTH: usize = 128;
        const HEIGHT: usize = 128;
        let input: Vec<u8> = (0..WIDTH * HEIGHT * 3)
            .map(|i| (((i / 3) % WIDTH) / 2 + ((i / 3) / WIDTH) / 2) as u8)
            .collect();
        let config = lossy().with_distance(2.0);
        let fastest = encode_image(
            &input,
            WIDTH,
            HEIGHT,
            &config.clone().with_speed(Speed::Fastest),
        )
        .expect("Fastest encode failed");
        let fast = encode_image(
            &input,
            WIDTH,
            HEIGHT,
            &config.clone().with_speed(Speed::Fast),
        )
        .expect("Fast encode failed");
        assert!(!fastest.is_empty());
        assert_ne!(
            fastest, fast,
            "Fastest should skip the transform search Fast performs"
        );
    }

    /// A 4-pixel red checkerboard under a slow brightness drift.
    fn checkerboard_rgb(size: usize) -> Vec<u8> {
        let mut pixels = Vec::with_capacity(size * size * 3);
        for y in 0..size {
            for x in 0..size {
                let lit = (x / 4 + y / 4) % 2 == 1;
                let drift = (x * 24 / size + y * 12 / size) as u8;
                pixels.extend_from_slice(&if lit {
                    [210 - drift, 8, 6]
                } else {
                    [40 - drift.min(40), 0, 0]
                });
            }
        }
        pixels
    }

    fn learned_rate_lossy(distance: f32) -> EncodeConfig {
        EncodeConfig::default()
            .with_distance(distance)
            .with_speed(Speed::Slow)
            .with_patches(false)
            .with_learned_rate(true)
    }

    #[test]
    fn learned_rate_output_is_independent_of_thread_count() {
        const SIZE: usize = 272;
        let pixels = checkerboard_rgb(SIZE);
        for distance in [1.0f32, 2.0, 4.0] {
            let config = learned_rate_lossy(distance);
            let single = encode_image(&pixels, SIZE, SIZE, &config.clone().with_num_threads(1))
                .expect("single-threaded encode failed");
            for threads in [2, 8] {
                let threaded = encode_image(
                    &pixels,
                    SIZE,
                    SIZE,
                    &config.clone().with_num_threads(threads),
                )
                .expect("multi-threaded encode failed");
                assert_eq!(single, threaded, "d={distance} threads={threads}");
            }
        }
    }

    /// Two DC groups: the first is sampled by regions, the second is too
    /// narrow for that and is its own pilot.
    #[test]
    fn learned_rate_is_deterministic_across_dc_groups() {
        const WIDTH: usize = 2112;
        const HEIGHT: usize = 128;
        let mut pixels = Vec::with_capacity(WIDTH * HEIGHT * 3);
        for y in 0..HEIGHT {
            for x in 0..WIDTH {
                let lit = (x / 4 + y / 4) % 2 == 1;
                let ramp = (x * 97 / WIDTH) as u8;
                pixels.extend_from_slice(&if lit {
                    [200 - ramp, 30 + ramp, 12]
                } else {
                    [20 + ramp / 2, ramp, 90]
                });
            }
        }
        let config = learned_rate_lossy(2.0);
        let single = encode_image(&pixels, WIDTH, HEIGHT, &config.clone().with_num_threads(1))
            .expect("single-threaded encode failed");
        let threaded = encode_image(&pixels, WIDTH, HEIGHT, &config.with_num_threads(8))
            .expect("multi-threaded encode failed");
        assert_eq!(single, threaded);
    }

    #[test]
    fn learned_rate_encodes_images_smaller_than_a_region() {
        for size in [8usize, 40, 63, 100] {
            let pixels = checkerboard_rgb(size);
            for distance in [1.0f32, 3.0] {
                let bytes = encode_image(&pixels, size, size, &learned_rate_lossy(distance))
                    .expect("encode failed");
                assert!(!bytes.is_empty(), "{size} at d={distance}");
            }
        }
    }

    #[test]
    fn learned_rate_shrinks_a_block_periodic_pattern() {
        const SIZE: usize = 256;
        let pixels = checkerboard_rgb(SIZE);
        for distance in [2.0f32, 3.0] {
            let learned = learned_rate_lossy(distance).with_num_threads(1);
            let fixed = learned.clone().with_learned_rate(false);
            let learned = encode_image(&pixels, SIZE, SIZE, &learned).unwrap();
            let fixed = encode_image(&pixels, SIZE, SIZE, &fixed).unwrap();
            assert!(
                learned.len() * 10 < fixed.len() * 8,
                "d={distance}: {} vs {}",
                learned.len(),
                fixed.len()
            );
        }
    }

    #[test]
    fn learned_rate_prices_every_transform_of_a_small_image() {
        // Nine 64x64 positions: too few for a table by count, enough by
        // the blocks they cover. Left on the fixed model, the 64x64
        // transform undercuts the learned ones and takes the image.
        const SIZE: usize = 192;
        let pixels = checkerboard_rgb(SIZE);
        let learned = learned_rate_lossy(1.0).with_num_threads(1);
        let fixed = learned.clone().with_learned_rate(false);
        let learned = encode_image(&pixels, SIZE, SIZE, &learned).unwrap();
        let fixed = encode_image(&pixels, SIZE, SIZE, &fixed).unwrap();
        // The bug this guards took 2.6x the fixed size; a shared-DC saving
        // shrinks both sides equally, so the bound must not sit at the ratio.
        assert!(
            learned.len() < fixed.len() * 2,
            "{} vs {}",
            learned.len(),
            fixed.len()
        );
    }

    #[test]
    fn learned_rate_lets_fine_transforms_compete_with_merges() {
        // One-pixel lines on black every 8 pixels. IDENTITY codes them in
        // a few tokens per block; under the fixed model they are only
        // tried on the blocks the merges left.
        const SIZE: usize = 256;
        let mut pixels = Vec::with_capacity(SIZE * SIZE * 3);
        for y in 0..SIZE {
            for x in 0..SIZE {
                let ink = x % 8 == 3 || y % 8 == 3;
                let magenta = (x / 64 + y / 64) % 2 == 0;
                pixels.extend_from_slice(&match (ink, magenta) {
                    (false, _) => [0, 0, 0],
                    (true, true) => [252, 0, 254],
                    (true, false) => [252, 0, 0],
                });
            }
        }
        let learned = learned_rate_lossy(2.0).with_num_threads(1);
        let fixed = learned.clone().with_learned_rate(false);
        let learned = encode_image(&pixels, SIZE, SIZE, &learned).unwrap();
        let fixed = encode_image(&pixels, SIZE, SIZE, &fixed).unwrap();
        // The source-feature quant field already codes the lines well under
        // the fixed model (1.6 KB vs 4 KB on the flat field); the learned
        // prices still take a third off.
        assert!(
            learned.len() * 4 < fixed.len() * 3,
            "{} vs {}",
            learned.len(),
            fixed.len()
        );
    }

    #[test]
    fn learned_rate_is_a_slow_speed_tool() {
        const SIZE: usize = 128;
        let pixels = checkerboard_rgb(SIZE);
        for speed in [Speed::UltraFast, Speed::Fastest, Speed::Fast, Speed::Medium] {
            let base = EncodeConfig::default()
                .with_distance(2.0)
                .with_speed(speed)
                .with_learned_rate(false)
                .with_num_threads(1);
            assert_eq!(
                encode_image(&pixels, SIZE, SIZE, &base).unwrap(),
                encode_image(&pixels, SIZE, SIZE, &base.clone().with_learned_rate(true)).unwrap(),
                "{speed:?}"
            );
        }
    }

    #[test]
    fn rgb8_quality() {
        ok(encode_image(
            &rgb8(),
            W,
            H,
            &EncodeConfig::default().with_quality(85.0),
        ));
    }

    // --- encode_image_with_alpha (RGBA u8) ---

    #[test]
    fn rgba8_lossy() {
        ok(encode_image_with_alpha(&rgba8(), W, H, &lossy()));
    }

    #[test]
    fn rgba8_lossless() {
        ok(encode_image_with_alpha(&rgba8(), W, H, &lossless()));
    }

    // --- 16-bit RGB / RGBA ---

    #[test]
    fn rgb16_lossy() {
        ok(encode_image_16bit(&rgb16(), W, H, &lossy()));
    }

    #[test]
    fn rgb16_lossless() {
        ok(encode_image_16bit(&rgb16(), W, H, &lossless()));
    }

    #[test]
    fn rgba16_lossy() {
        ok(encode_image_with_alpha_16bit(&rgba16(), W, H, &lossy()));
    }

    #[test]
    fn rgba16_lossless() {
        ok(encode_image_with_alpha_16bit(&rgba16(), W, H, &lossless()));
    }

    // --- 10-bit RGB / RGBA ---

    #[test]
    fn rgb10_lossy() {
        ok(encode_image_10bit(&rgb10(), W, H, &lossy()));
    }

    #[test]
    fn rgb10_lossless() {
        ok(encode_image_10bit(&rgb10(), W, H, &lossless()));
    }

    #[test]
    fn rgba10_lossy() {
        ok(encode_image_with_alpha_10bit(&rgba10(), W, H, &lossy()));
    }

    #[test]
    fn rgba10_lossless() {
        ok(encode_image_with_alpha_10bit(&rgba10(), W, H, &lossless()));
    }

    // --- 12-bit RGB / RGBA ---

    #[test]
    fn rgb12_lossy() {
        ok(encode_image_12bit(&rgb12(), W, H, &lossy()));
    }

    #[test]
    fn rgb12_lossless() {
        ok(encode_image_12bit(&rgb12(), W, H, &lossless()));
    }

    #[test]
    fn rgba12_lossy() {
        ok(encode_image_with_alpha_12bit(&rgba12(), W, H, &lossy()));
    }

    #[test]
    fn rgba12_lossless() {
        ok(encode_image_with_alpha_12bit(&rgba12(), W, H, &lossless()));
    }

    // --- float RGB / RGBA ---

    #[test]
    fn rgb_f32_lossy() {
        ok(encode_image_f32(&rgb_f32(), W, H, &lossy()));
    }

    #[test]
    fn rgb_f16_lossy() {
        ok(encode_image_f16(&rgb_f32(), W, H, &lossy()));
    }

    #[test]
    fn rgba_f32_lossy() {
        ok(encode_image_with_alpha_f32(&rgba_f32(), W, H, &lossy()));
    }

    #[test]
    fn rgba_f16_lossy() {
        ok(encode_image_with_alpha_f16(&rgba_f32(), W, H, &lossy()));
    }

    // --- grayscale u8 ---

    #[test]
    fn gray8_lossy() {
        ok(encode_image_gray(&gray8(), W, H, &lossy()));
    }

    #[test]
    fn gray8_lossless() {
        ok(encode_image_gray(&gray8(), W, H, &lossless()));
    }

    #[test]
    fn gray_alpha8_lossy() {
        ok(encode_image_gray_alpha(&gray_alpha8(), W, H, &lossy()));
    }

    #[test]
    fn gray_alpha8_lossless() {
        ok(encode_image_gray_alpha(&gray_alpha8(), W, H, &lossless()));
    }

    // --- grayscale 10-bit ---

    #[test]
    fn gray10_lossy() {
        ok(encode_image_gray_10bit(&gray10(), W, H, &lossy()));
    }

    #[test]
    fn gray10_lossless() {
        ok(encode_image_gray_10bit(&gray10(), W, H, &lossless()));
    }

    #[test]
    fn gray_alpha10_lossy() {
        ok(encode_image_gray_alpha_10bit(
            &gray_alpha10(),
            W,
            H,
            &lossy(),
        ));
    }

    #[test]
    fn gray_alpha10_lossless() {
        ok(encode_image_gray_alpha_10bit(
            &gray_alpha10(),
            W,
            H,
            &lossless(),
        ));
    }

    // --- grayscale 12-bit ---

    #[test]
    fn gray12_lossy() {
        ok(encode_image_gray_12bit(&gray12(), W, H, &lossy()));
    }

    #[test]
    fn gray12_lossless() {
        ok(encode_image_gray_12bit(&gray12(), W, H, &lossless()));
    }

    #[test]
    fn gray_alpha12_lossy() {
        ok(encode_image_gray_alpha_12bit(
            &gray_alpha12(),
            W,
            H,
            &lossy(),
        ));
    }

    #[test]
    fn gray_alpha12_lossless() {
        ok(encode_image_gray_alpha_12bit(
            &gray_alpha12(),
            W,
            H,
            &lossless(),
        ));
    }

    // --- grayscale 16-bit ---

    #[test]
    fn gray16_lossy() {
        ok(encode_image_gray_16bit(&gray16(), W, H, &lossy()));
    }

    #[test]
    fn gray16_lossless() {
        ok(encode_image_gray_16bit(&gray16(), W, H, &lossless()));
    }

    #[test]
    fn gray_alpha16_lossy() {
        ok(encode_image_gray_alpha_16bit(
            &gray_alpha16(),
            W,
            H,
            &lossy(),
        ));
    }

    #[test]
    fn gray_alpha16_lossless() {
        ok(encode_image_gray_alpha_16bit(
            &gray_alpha16(),
            W,
            H,
            &lossless(),
        ));
    }

    // --- grayscale float ---

    #[test]
    fn gray_f32_lossy() {
        ok(encode_image_gray_f32(&gray_f32(), W, H, &lossy()));
    }

    #[test]
    fn gray_f16_lossy() {
        ok(encode_image_gray_f16(&gray_f32(), W, H, &lossy()));
    }

    // --- error paths ---

    #[test]
    fn empty_width_rejected() {
        assert!(matches!(
            encode_image(&[], 0, H, &lossy()),
            Err(EncodeError::EmptyImage)
        ));
    }

    #[test]
    fn empty_height_rejected() {
        assert!(matches!(
            encode_image(&[], W, 0, &lossy()),
            Err(EncodeError::EmptyImage)
        ));
    }

    #[test]
    fn wrong_buffer_size_rejected() {
        let short = vec![0u8; W * H]; // too short for RGB
        assert!(matches!(
            encode_image(&short, W, H, &lossy()),
            Err(EncodeError::InputSizeMismatch { .. })
        ));
    }

    #[test]
    fn invalid_distance_rejected() {
        assert!(matches!(
            encode_image(&rgb8(), W, H, &EncodeConfig::default().with_distance(-1.0)),
            Err(EncodeError::InvalidDistance(_))
        ));
    }

    #[test]
    fn dimension_too_large_rejected() {
        let huge = MAX_DIMENSION + 1;
        assert!(matches!(
            encode_image(&[], huge, H, &lossy()),
            Err(EncodeError::DimensionTooLarge { .. })
        ));
    }

    // --- 1x1 edge cases ---

    #[test]
    fn one_by_one_rgb8() {
        ok(encode_image(&[128u8, 64, 32], 1, 1, &lossy()));
    }

    #[test]
    fn one_by_one_rgba8_lossless() {
        ok(encode_image_with_alpha(
            &[128u8, 64, 32, 255],
            1,
            1,
            &lossless(),
        ));
    }

    #[test]
    fn one_by_one_gray8() {
        ok(encode_image_gray(&[200u8], 1, 1, &lossy()));
    }
}