exprim 0.4.0

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
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
//! CPU image rasterization (Phase 6 item C).
//!
//! An image occupies the unit square in user space; the CTM maps it to device
//! space. Rendering inverts that map: each device pixel in the image's device
//! bounds is projected back to `(u, v)` in the unit square, the source sample
//! is read (bpc unpack → `/Decode` → color-space conversion → `/SMask` alpha),
//! and composited source-over. Nearest and bilinear sampling are supported.
//!
//! Codec-encoded images (DCT/JPX/JBIG2/CCITT) carry no samples and never reach
//! here — the page's `NEEDS_*` feature routes them away at preflight.

use std::sync::{Arc, Mutex, Weak};

use crate::page_ir::{
    DeviceRect, ImageColorSpace, ImageMask, ImageSMask, InterpolationMode, Matrix, Point,
};
use crate::render_api::{CancellationToken, RenderError};

use crate::render_cpu::surface::{filled_arc, unique_arc_mut, zeroed_arc};

/// Document-scoped cache of source images converted to the RGB8 upload
/// vocabulary. The decoded-image cache retains compressed-codec output; this
/// companion cache retains only color-converted RGB and deliberately holds a
/// weak reference to the decoded samples so it does not pin both copies.
#[derive(Debug)]
pub(crate) struct SharedRgbImageCache {
    state: Mutex<RgbImageCacheState>,
    budget_bytes: usize,
}

#[derive(Debug, Default)]
struct RgbImageCacheState {
    entries: Vec<RgbImageCacheEntry>,
    bytes: usize,
    clock: u64,
}

#[derive(Debug)]
struct RgbImageCacheEntry {
    source: Weak<[u8]>,
    width: u32,
    height: u32,
    bpc: u8,
    color_space: ImageColorSpace,
    decode: Option<Arc<[[f32; 2]]>>,
    rgb: Arc<[u8]>,
    charge: usize,
    last_used: u64,
}

impl SharedRgbImageCache {
    /// Converted scan pages are commonly 3–20 MiB. This keeps a useful
    /// revisit/tile working set without duplicating the decoded cache's
    /// separate 96 MiB budget.
    const DEFAULT_BUDGET_BYTES: usize = crate::render_cpu::MAX_PREPARED_RGB_CONVERSION_BYTES;

    pub(crate) fn new(budget_bytes: usize) -> Self {
        Self {
            state: Mutex::new(RgbImageCacheState::default()),
            budget_bytes,
        }
    }

    pub(crate) fn get_or_convert(
        &self,
        image: &PreparedImage,
        cancellation: Option<&CancellationToken>,
    ) -> Result<Option<Arc<[u8]>>, RenderError> {
        if image.is_direct_rgb8() {
            return Ok(Some(Arc::clone(&image.samples)));
        }
        let Some(rgb_len) = image.rgb8_len() else {
            return Ok(None);
        };
        // Do not turn a small destination tile into an unbounded full-source
        // conversion. Oversized sources keep using the CPU renderer's
        // destination-driven sampler.
        if rgb_len > self.budget_bytes {
            return Ok(None);
        }

        if let Some(rgb) = self.lookup(image) {
            return Ok(Some(rgb));
        }

        let mut converted = zeroed_arc(rgb_len);
        let width = image.width as usize;
        let converted_data = unique_arc_mut(&mut converted);
        for row in 0..image.height {
            if row % 32 == 0 && cancellation.is_some_and(CancellationToken::is_cancelled) {
                return Err(RenderError::Cancelled);
            }
            for col in 0..image.width {
                let rgba = image
                    .source_pixel(col, row)
                    .ok_or(RenderError::Unsupported(
                        crate::page_ir::PageFeatures::IMAGES,
                    ))?;
                let offset = (row as usize * width + col as usize) * 3;
                converted_data[offset..offset + 3].copy_from_slice(&rgba[..3]);
            }
        }
        if cancellation.is_some_and(CancellationToken::is_cancelled) {
            return Err(RenderError::Cancelled);
        }
        // Another raster worker may have completed the same conversion while
        // this one was outside the mutex. Reuse its Arc so every caller also
        // converges on one GPU-upload-cache identity.
        if let Some(rgb) = self.lookup(image) {
            return Ok(Some(rgb));
        }
        self.insert(image, Arc::clone(&converted));
        Ok(Some(converted))
    }

    fn lookup(&self, image: &PreparedImage) -> Option<Arc<[u8]>> {
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        let mut hit = None;
        let mut removed_bytes = 0usize;
        state.entries.retain_mut(|entry| {
            let Some(source) = entry.source.upgrade() else {
                removed_bytes = removed_bytes.saturating_add(entry.charge);
                return false;
            };
            if hit.is_none()
                && Arc::ptr_eq(&source, &image.samples)
                && entry.width == image.width
                && entry.height == image.height
                && entry.bpc == image.bpc
                && entry.color_space == image.color_space
                && entry.decode == image.decode
            {
                entry.last_used = clock;
                hit = Some(Arc::clone(&entry.rgb));
            }
            true
        });
        state.bytes = state.bytes.saturating_sub(removed_bytes);
        hit
    }

    fn insert(&self, image: &PreparedImage, rgb: Arc<[u8]>) {
        let charge = rgb.len() + std::mem::size_of::<RgbImageCacheEntry>();
        let mut state = self.state.lock().unwrap_or_else(|e| e.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        state.entries.push(RgbImageCacheEntry {
            source: Arc::downgrade(&image.samples),
            width: image.width,
            height: image.height,
            bpc: image.bpc,
            color_space: image.color_space.clone(),
            decode: image.decode.clone(),
            rgb,
            charge,
            last_used: clock,
        });
        state.bytes += charge;
        while state.bytes > self.budget_bytes && state.entries.len() > 1 {
            let victim = state
                .entries
                .iter()
                .enumerate()
                .min_by_key(|(_, entry)| entry.last_used)
                .map(|(index, _)| index)
                .unwrap_or(0);
            let removed = state.entries.swap_remove(victim);
            state.bytes = state.bytes.saturating_sub(removed.charge);
        }
    }
}

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

/// Document-scoped cache of normalized alpha8 image masks used by the GPU
/// preparation seam. The source allocation remains weakly held so this cache
/// cannot pin a decoded mask after the document image cache releases it.
#[derive(Debug)]
pub(crate) struct SharedOpacityImageCache {
    state: Mutex<OpacityImageCacheState>,
    budget_bytes: usize,
}

#[derive(Debug, Default)]
struct OpacityImageCacheState {
    entries: Vec<OpacityImageCacheEntry>,
    bytes: usize,
    clock: u64,
}

#[derive(Debug)]
struct OpacityImageCacheEntry {
    source: Weak<[u8]>,
    width: u32,
    height: u32,
    bpc: u8,
    decode: Option<Arc<[[f32; 2]]>>,
    inverted: bool,
    components: u8,
    color_key: Option<Arc<[[u32; 2]]>>,
    alpha: Arc<[u8]>,
    charge: usize,
    last_used: u64,
}

impl SharedOpacityImageCache {
    pub(crate) fn new(budget_bytes: usize) -> Self {
        Self {
            state: Mutex::new(OpacityImageCacheState::default()),
            budget_bytes,
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn get_or_expand(
        &self,
        source: &Arc<[u8]>,
        width: u32,
        height: u32,
        bpc: u8,
        decode: Option<&Arc<[[f32; 2]]>>,
        inverted: bool,
        cancellation: Option<&CancellationToken>,
    ) -> Result<Option<Arc<[u8]>>, RenderError> {
        if !(1..=16).contains(&bpc) {
            return Ok(None);
        }
        let Some(alpha_len) = (width as usize).checked_mul(height as usize) else {
            return Ok(None);
        };
        if alpha_len == 0 || alpha_len > self.budget_bytes {
            return Ok(None);
        }
        if let Some(alpha) = self.lookup(source, width, height, bpc, decode, inverted, 1, None) {
            return Ok(Some(alpha));
        }

        let row_bits = (width as usize * bpc as usize).div_ceil(8) * 8;
        let max_value = ((1u64 << bpc) - 1) as f32;
        let decode_pair = decode.and_then(|pairs| pairs.first()).copied();
        let mut expanded = zeroed_arc(alpha_len);
        let expanded_data = unique_arc_mut(&mut expanded);
        for row in 0..height {
            if row % 32 == 0 && cancellation.is_some_and(CancellationToken::is_cancelled) {
                return Err(RenderError::Cancelled);
            }
            for column in 0..width {
                let bit = row as usize * row_bits + column as usize * bpc as usize;
                let raw = read_bits(source, bit, bpc as usize) as f32 / max_value;
                let decoded = match decode_pair {
                    Some([lo, hi]) => lo + raw * (hi - lo),
                    None => raw,
                }
                .clamp(0.0, 1.0);
                let opacity = if inverted { 1.0 - decoded } else { decoded };
                expanded_data[row as usize * width as usize + column as usize] = to_u8(opacity);
            }
        }
        if cancellation.is_some_and(CancellationToken::is_cancelled) {
            return Err(RenderError::Cancelled);
        }
        if let Some(alpha) = self.lookup(source, width, height, bpc, decode, inverted, 1, None) {
            return Ok(Some(alpha));
        }
        self.insert(
            source,
            width,
            height,
            bpc,
            decode.cloned(),
            inverted,
            1,
            None,
            Arc::clone(&expanded),
        );
        Ok(Some(expanded))
    }

    /// Expand a PDF colour-key `/Mask` into tight alpha8. The ranges apply to
    /// the base image's raw components before `/Decode`; a pixel is transparent
    /// only when every component lies inside its corresponding range.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn get_or_expand_color_key(
        &self,
        source: &Arc<[u8]>,
        width: u32,
        height: u32,
        bpc: u8,
        components: usize,
        ranges: &Arc<[[u32; 2]]>,
        cancellation: Option<&CancellationToken>,
    ) -> Result<Option<Arc<[u8]>>, RenderError> {
        if !(1..=16).contains(&bpc)
            || components == 0
            || components > u8::MAX as usize
            || ranges.len() != components
        {
            return Ok(None);
        }
        let Some(alpha_len) = (width as usize).checked_mul(height as usize) else {
            return Ok(None);
        };
        if alpha_len == 0 || alpha_len > self.budget_bytes {
            return Ok(None);
        }
        let components = components as u8;
        if let Some(alpha) = self.lookup(
            source,
            width,
            height,
            bpc,
            None,
            false,
            components,
            Some(ranges),
        ) {
            return Ok(Some(alpha));
        }

        let Some(row_sample_bits) = (width as usize)
            .checked_mul(components as usize)
            .and_then(|samples| samples.checked_mul(bpc as usize))
        else {
            return Ok(None);
        };
        let row_bits = row_sample_bits.div_ceil(8) * 8;
        let Some(source_bytes) = row_bits
            .checked_div(8)
            .and_then(|bytes| bytes.checked_mul(height as usize))
        else {
            return Ok(None);
        };
        if source.len() < source_bytes {
            return Ok(None);
        }

        let mut expanded = filled_arc(alpha_len, 255);
        let expanded_data = unique_arc_mut(&mut expanded);
        for row in 0..height {
            if row % 32 == 0 && cancellation.is_some_and(CancellationToken::is_cancelled) {
                return Err(RenderError::Cancelled);
            }
            for column in 0..width {
                let pixel_bit =
                    row as usize * row_bits + column as usize * components as usize * bpc as usize;
                let masked = ranges.iter().enumerate().all(|(component, &[lo, hi])| {
                    let bit = pixel_bit + component * bpc as usize;
                    let raw = read_bits(source, bit, bpc as usize);
                    raw >= lo && raw <= hi
                });
                if masked {
                    expanded_data[row as usize * width as usize + column as usize] = 0;
                }
            }
        }
        if cancellation.is_some_and(CancellationToken::is_cancelled) {
            return Err(RenderError::Cancelled);
        }

        if let Some(alpha) = self.lookup(
            source,
            width,
            height,
            bpc,
            None,
            false,
            components,
            Some(ranges),
        ) {
            return Ok(Some(alpha));
        }
        self.insert(
            source,
            width,
            height,
            bpc,
            None,
            false,
            components,
            Some(Arc::clone(ranges)),
            Arc::clone(&expanded),
        );
        Ok(Some(expanded))
    }

    #[allow(clippy::too_many_arguments)]
    fn lookup(
        &self,
        source: &Arc<[u8]>,
        width: u32,
        height: u32,
        bpc: u8,
        decode: Option<&Arc<[[f32; 2]]>>,
        inverted: bool,
        components: u8,
        color_key: Option<&Arc<[[u32; 2]]>>,
    ) -> Option<Arc<[u8]>> {
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        let mut hit = None;
        let mut removed_bytes = 0usize;
        state.entries.retain_mut(|entry| {
            let Some(cached_source) = entry.source.upgrade() else {
                removed_bytes = removed_bytes.saturating_add(entry.charge);
                return false;
            };
            if hit.is_none()
                && Arc::ptr_eq(&cached_source, source)
                && entry.width == width
                && entry.height == height
                && entry.bpc == bpc
                && entry.decode.as_ref() == decode
                && entry.inverted == inverted
                && entry.components == components
                && entry.color_key.as_ref() == color_key
            {
                entry.last_used = clock;
                hit = Some(Arc::clone(&entry.alpha));
            }
            true
        });
        state.bytes = state.bytes.saturating_sub(removed_bytes);
        hit
    }

    #[allow(clippy::too_many_arguments)]
    fn insert(
        &self,
        source: &Arc<[u8]>,
        width: u32,
        height: u32,
        bpc: u8,
        decode: Option<Arc<[[f32; 2]]>>,
        inverted: bool,
        components: u8,
        color_key: Option<Arc<[[u32; 2]]>>,
        alpha: Arc<[u8]>,
    ) {
        let charge = alpha.len() + std::mem::size_of::<OpacityImageCacheEntry>();
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        state.entries.push(OpacityImageCacheEntry {
            source: Arc::downgrade(source),
            width,
            height,
            bpc,
            decode,
            inverted,
            components,
            color_key,
            alpha,
            charge,
            last_used: clock,
        });
        state.bytes += charge;
        while state.bytes > self.budget_bytes && state.entries.len() > 1 {
            let victim = state
                .entries
                .iter()
                .enumerate()
                .min_by_key(|(_, entry)| entry.last_used)
                .map(|(index, _)| index)
                .unwrap_or(0);
            let removed = state.entries.swap_remove(victim);
            state.bytes = state.bytes.saturating_sub(removed.charge);
        }
    }
}

impl Default for SharedOpacityImageCache {
    fn default() -> Self {
        Self::new(crate::render_cpu::MAX_PREPARED_OPACITY_CONVERSION_BYTES)
    }
}

/// An image prepared for one render request.
#[derive(Debug, Clone)]
pub struct PreparedImage {
    /// Diagnostic attribution only: the containing construct this operation
    /// came from. Never read while painting — see
    /// [`crate::render_cpu::attribution`].
    pub origin: crate::page_ir::PaintOrigin,
    pub bounds: DeviceRect,
    pub clip: Option<u32>,
    pub clip_has_mask: bool,
    /// Device → unit-square transform (inverse of the image CTM).
    pub inv: Matrix,
    pub width: u32,
    pub height: u32,
    pub bpc: u8,
    pub color_space: ImageColorSpace,
    pub decode: Option<Arc<[[f32; 2]]>>,
    pub samples: Arc<[u8]>,
    /// Predecoded colors for low-bit-depth single-component images. This
    /// sample. This hoists `/Decode`, Indexed/Tint lookup, and color conversion
    /// out of the per-destination-pixel sampling loop.
    pub sample_lut: Option<Arc<[[u8; 4]]>>,
    pub smask: Option<Arc<ImageSMask>>,
    /// Explicit hard `/Mask` (color-key or stencil). Applied per source texel
    /// as an all-or-nothing cut-out; independent of `smask` (only one is ever
    /// set — `/SMask` wins at build time).
    pub mask: Option<ImageMask>,
    pub interpolation: InterpolationMode,
    /// Source texels one device pixel covers, per axis. Above 1 the image is
    /// being *minified* and one sample per pixel throws information away.
    pub footprint: [f64; 2],
    /// `/ImageMask` stencil painted with `stencil_rgb`.
    pub is_stencil: bool,
    pub stencil_rgb: [u8; 3],
    pub alpha: u8,
    pub blend: crate::page_ir::BlendMode,
}

impl PreparedImage {
    /// Source samples per pixel.
    fn components(&self) -> usize {
        if self.is_stencil {
            1
        } else {
            self.color_space.components()
        }
    }

    /// Row stride in bits (rows are byte-aligned).
    fn row_bits(&self) -> usize {
        let bits = self.width as usize * self.components() * self.bpc as usize;
        bits.div_ceil(8) * 8
    }

    fn rgb8_len(&self) -> Option<usize> {
        if self.is_stencil || !(1..=16).contains(&self.bpc) {
            return None;
        }
        let source_bytes = self
            .row_bits()
            .checked_mul(self.height as usize)?
            .checked_div(8)?;
        if self.samples.len() < source_bytes {
            return None;
        }
        (self.width as usize)
            .checked_mul(self.height as usize)?
            .checked_mul(3)
    }

    fn is_direct_rgb8(&self) -> bool {
        self.bpc == 8
            && self.decode.is_none()
            && matches!(self.color_space, ImageColorSpace::Rgb)
            && self.rgb8_len().is_some()
    }

    fn source_pixel(&self, col: u32, row: u32) -> Option<[u8; 4]> {
        self.pixel(col, row)
    }

    /// Whether this image can use the executor's prepared axis-aligned
    /// bilevel box-filter path.
    pub(crate) fn is_binary_box_filterable(&self) -> bool {
        !self.is_stencil
            && self.bpc == 1
            && self.sample_lut.as_ref().is_some_and(|lut| lut.len() >= 2)
            && self.smask.is_none()
            && self.mask.is_none()
            && (self.footprint[0] > 1.0 || self.footprint[1] > 1.0)
            && self.inv.b.abs() < 1e-12
            && self.inv.c.abs() < 1e-12
    }

    /// The lookup table of a 1-, 2- or 4-bit single-component image whose
    /// every entry is opaque, for the executor's axis-aligned nearest fast
    /// path. `pixel()` resolves such an image as `lut[read_bits(..)]`, so the
    /// table must be complete (one entry per sample value, else a value with
    /// no entry would paint nothing) and the sample data must cover every
    /// packed row (else `read_bits` reads the missing bytes as zero). `None`
    /// sends the draw down the generic path.
    pub(crate) fn lut_nearest_opaque(&self) -> Option<&[[u8; 4]]> {
        if self.is_stencil || !matches!(self.bpc, 1 | 2 | 4) || self.components() != 1 {
            return None;
        }
        let lut = self.sample_lut.as_ref()?;
        if lut.len() != 1usize << self.bpc || lut.iter().any(|c| c[3] != 255) {
            return None;
        }
        let needed = (self.row_bits() / 8).checked_mul(self.height as usize)?;
        (self.samples.len() >= needed).then_some(&lut[..])
    }

    /// The two prepared RGBA entries (zero-bit, one-bit) of a bilevel image's
    /// lookup table, for the executor's summed-area box-filter path.
    pub(crate) fn binary_box_lut(&self) -> Option<([u8; 4], [u8; 4])> {
        let lut = self.sample_lut.as_ref()?;
        let zero = lut.first().copied().unwrap_or([0, 0, 0, 255]);
        let one = lut.get(1).copied().unwrap_or(zero);
        Some((zero, one))
    }

    /// Whether an `/ImageMask` stencil's `/Decode` is `[1 0]`, which makes a
    /// sample of 1 paint instead of mask.
    fn stencil_decode_inverted(&self) -> bool {
        self.decode
            .as_ref()
            .map(|d| d.first().map(|p| p[0] > p[1]).unwrap_or(false))
            .unwrap_or(false)
    }

    /// The two-entry (zero-bit, one-bit) table of a one-bit `/ImageMask`
    /// stencil, for the executor's bilevel fast paths: the painting bit is
    /// `[stencil_rgb, 255]` and the masking bit `[stencil_rgb, 0]`, so the
    /// bilevel box filter's two-entry mix reproduces the generic stencil
    /// average exactly (`(rgb·W + W/2) / W == rgb` keeps the paint colour, and
    /// the alpha is the same rounded weighted coverage `area_average` takes),
    /// and a masked texel paints nothing.
    ///
    /// `None` (keep the generic sampler) unless this is a 1 bpc stencil with
    /// no resource mask and sample data covering every packed row. `pixel()`
    /// reads missing bytes as zero, which the fast paths do not reproduce
    /// (they index the rows directly), so a truncated JBIG2 or CCITT stream
    /// stays generic.
    pub(crate) fn stencil_bilevel_lut(&self) -> Option<([u8; 4], [u8; 4])> {
        if !self.is_stencil
            || self.bpc != 1
            || self.width == 0
            || self.height == 0
            || self.smask.is_some()
            || self.mask.is_some()
        {
            return None;
        }
        let needed = (self.row_bits() / 8).checked_mul(self.height as usize)?;
        if self.samples.len() < needed {
            return None;
        }
        let [r, g, b] = self.stencil_rgb;
        let (paint, masked) = ([r, g, b, 255], [r, g, b, 0]);
        Some(if self.stencil_decode_inverted() {
            (masked, paint)
        } else {
            (paint, masked)
        })
    }

    /// Packed row stride in bits (rows are byte-aligned), for the executor's
    /// summed-area box-filter path.
    pub(crate) fn packed_row_bits(&self) -> usize {
        self.row_bits()
    }

    /// A one-bit stencil `/Mask` that this draw *minifies*, re-expressed as the
    /// equivalent one-bit `/SMask`: the same bits, with the polarity carried
    /// by the soft mask's `/Decode` (a stencil sample of 1 hides, so alpha is
    /// `1 - raw`; a stencil `/Decode [1 0]` paints on 1, so alpha is `raw`).
    ///
    /// Point-sampling a hard mask all-or-nothing is what the spec describes
    /// at device resolution, but when several mask texels fall in one device
    /// pixel it keeps an arbitrary one of them: on MRC scans (a JPX
    /// foreground cut out by a 300-600 dpi JBIG2 text layer) drawn at 72 dpi
    /// it rendered aliased text with dropped hairlines and thin strokes, and
    /// disagreed with PDFium, MuPDF and Hayro, which all average the mask's
    /// coverage when minifying. The soft-mask sampler box-filters a one-bit
    /// mask by coverage when it minifies and point-samples the very texel
    /// [`stencil_col`]/[`stencil_row`] pick when it does not, so this only
    /// changes minified draws.
    ///
    /// `None` when the image has no such mask or the draw does not minify it.
    pub(crate) fn minified_stencil_as_coverage(&self) -> Option<PreparedImage> {
        if self.smask.is_some() {
            return None;
        }
        let Some(ImageMask::Stencil(sm)) = self.mask.as_ref() else {
            return None;
        };
        if sm.bits_per_component != 1 || sm.width == 0 || sm.height == 0 {
            return None;
        }
        let row_bytes = (sm.width as usize).div_ceil(8);
        if sm.samples.len() < row_bytes.checked_mul(sm.height as usize)? {
            return None;
        }
        let footprint = self.smask_footprint(sm);
        if !(footprint[0] > 1.0 || footprint[1] > 1.0) {
            return None;
        }
        let inverted = sm
            .decode
            .as_ref()
            .and_then(|d| d.first())
            .is_some_and(|p| p[0] > p[1]);
        let decode: [f32; 2] = if inverted { [0.0, 1.0] } else { [1.0, 0.0] };
        Some(PreparedImage {
            smask: Some(Arc::new(ImageSMask {
                decode: Some(Arc::from([decode])),
                ..(**sm).clone()
            })),
            mask: None,
            ..self.clone()
        })
    }

    /// An 8-bit gray image re-expressed as RGB8: the same texels with each
    /// gray byte tripled and the colour space marked RGB. `pixel()` answers
    /// `[g, g, g, 255]` for such a gray texel and `[r, g, b, 255]` for an
    /// RGB8 one, so sampling the promoted image is byte-identical to sampling
    /// the original by construction. What the promotion buys is eligibility
    /// for the executor's axis-aligned RGB8 fast paths, which read three
    /// bytes per texel: scanned books and MRC pages are 8-bit gray
    /// almost without exception, and without this every one of their page
    /// draws took the generic per-pixel sampler.
    ///
    /// `None` when the image is not exactly that shape or too large to expand
    /// (then the generic path runs, unchanged). That includes a colour-key
    /// `/Mask`: the key is one `[min, max]` pair tested against the *raw*
    /// gray sample, and after promotion the image has three components, so
    /// `color_key_hit` would read the key as malformed and never hide a texel.
    pub(crate) fn gray8_promoted_to_rgb8(&self) -> Option<PreparedImage> {
        // 64 Mpx -> 192 MiB of RGB8, the same ceiling as the CMYK conversion.
        const MAX_PROMOTE_PIXELS: usize = 64 * 1024 * 1024;
        if self.is_stencil
            || self.bpc != 8
            || self.decode.is_some()
            || self.sample_lut.is_some()
            || matches!(self.mask, Some(ImageMask::ColorKey(_)))
            || !matches!(self.color_space, ImageColorSpace::Gray)
        {
            return None;
        }
        let n = (self.width as usize).checked_mul(self.height as usize)?;
        if n == 0 || n > MAX_PROMOTE_PIXELS || self.samples.len() < n {
            return None;
        }
        // Written straight into the shared allocation: building a `Vec` and
        // converting it with `Arc::from` allocated and copied the 3n bytes
        // twice per draw (two 6.3 MB allocations for a 300-dpi page scan).
        let mut rgb = zeroed_arc(n * 3);
        for (&g, dst) in self.samples[..n]
            .iter()
            .zip(unique_arc_mut(&mut rgb).chunks_exact_mut(3))
        {
            dst.copy_from_slice(&[g, g, g]);
        }
        Some(PreparedImage {
            color_space: ImageColorSpace::Rgb,
            samples: rgb,
            ..self.clone()
        })
    }

    /// Images whose texels resolve through a per-pixel colour transform — a
    /// non-sRGB `/ICCBased` RGB profile, an ICC CMYK lookup transform,
    /// `/Lab`, or a pre-resolved `/Separation` / `/DeviceN` tint table — have
    /// no fast path of their own: every tap of every draw ran the transform
    /// (a 1317×882 ICC scan cost ~60 ns per source texel per draw). Each
    /// texel's result is a pure function of that texel's own samples, so the
    /// whole image can be resolved to RGB8 *once* (and, in `prepared.rs`,
    /// cached by content across renders), after which the RGB8 fast paths
    /// apply and the output is byte-identical: the box average, the bilinear
    /// lerp and the nearest fetch all consume exactly the per-texel RGB that
    /// `pixel()` yields, whether it is computed on the fly or stored.
    ///
    /// Only the shapes `pixel()` resolves without `None` qualify: 8- or 16-bit
    /// samples, not a stencil, no colour-key mask (that tests the *raw*
    /// samples), no prepared LUT, complete sample data, at most 64 Mpx.
    pub(crate) fn generic_promotion_eligible(&self) -> bool {
        // 64 Mpx -> 192 MiB of RGB8, the same ceiling as the other promotions.
        const MAX_PROMOTE_PIXELS: usize = 64 * 1024 * 1024;
        if self.is_stencil
            || !matches!(self.bpc, 8 | 16)
            || self.sample_lut.is_some()
            || matches!(self.mask, Some(ImageMask::ColorKey(_)))
            || !(matches!(
                self.color_space,
                ImageColorSpace::IccRgb { .. }
                    | ImageColorSpace::IccCmyk { .. }
                    | ImageColorSpace::Lab { .. }
                    | ImageColorSpace::TintLut { .. }
                    | ImageColorSpace::TintLut2 { .. }
            ) || self.is_sixteen_bit_device_family())
        {
            return false;
        }
        let Some(n) = (self.width as usize).checked_mul(self.height as usize) else {
            return false;
        };
        n > 0
            && n <= MAX_PROMOTE_PIXELS
            && self.samples.len() >= self.row_bits() / 8 * self.height as usize
    }

    /// A 16-bit `DeviceGray` / `DeviceRGB` / `DeviceCMYK` image. The 8-bit
    /// members of the family have dedicated fast paths; the 16-bit ones used
    /// to run the generic per-tap loop at every draw (30-250 ns per texel).
    /// They promote through `pixel()`, which reads the 16-bit samples, applies
    /// `/Decode` and converts, so the promoted texel is what the generic loop
    /// computes. Promotion moves such an image onto the RGB8 fast paths, which
    /// paint an unmasked opaque image's border ring by pixel centre rather than
    /// by A10 edge coverage; the caller in `prepared.rs` therefore promotes
    /// these only where that cannot differ (see `ring_unchanged_by_promotion`).
    pub(crate) fn is_sixteen_bit_device_family(&self) -> bool {
        self.bpc == 16
            && matches!(
                self.color_space,
                ImageColorSpace::Gray | ImageColorSpace::Rgb | ImageColorSpace::Cmyk
            )
    }

    /// The image with its samples resolved to RGB8 (see
    /// [`Self::generic_promotion_eligible`]); `None` when not eligible.
    #[cfg(test)]
    pub(crate) fn generic_promoted_to_rgb8(&self) -> Option<PreparedImage> {
        let samples = self.generic_source_as_rgb8()?;
        Some(self.with_rgb8_samples(samples))
    }

    /// `self` re-described over resolved RGB8 samples: colour space `Rgb`,
    /// 8 bits, no `/Decode` (already applied), no LUT. Everything else — the
    /// placement, the masks, interpolation, alpha — is unchanged.
    pub(crate) fn with_rgb8_samples(&self, samples: Arc<[u8]>) -> PreparedImage {
        PreparedImage {
            color_space: ImageColorSpace::Rgb,
            bpc: 8,
            decode: None,
            sample_lut: None,
            samples,
            ..self.clone()
        }
    }

    /// Resolve every texel through the path `pixel()` takes and pack the RGB
    /// triples. The 8-bit `/ICCBased` RGB image without `/Decode` (the
    /// scanned-page shape) calls the profile transform on the byte triple
    /// directly — the identical computation `pixel()` performs once its
    /// generic bit reads and absent `/Decode` reduce to `byte / 255`; every
    /// other shape goes through `pixel()` itself.
    pub(crate) fn generic_source_as_rgb8(&self) -> Option<Arc<[u8]>> {
        if !self.generic_promotion_eligible() {
            return None;
        }
        let (w, h) = (self.width as usize, self.height as usize);
        let n = w * h;
        let mut out = zeroed_arc(n * 3);
        let dst = unique_arc_mut(&mut out);
        if let ImageColorSpace::IccRgb { trc, matrix } = &self.color_space
            && self.bpc == 8
            && self.decode.is_none()
        {
            for (src, px) in self.samples[..n * 3]
                .chunks_exact(3)
                .zip(dst.chunks_exact_mut(3))
            {
                let rgb = crate::color::icc::to_srgb_with(
                    trc,
                    matrix,
                    [
                        src[0] as f32 / 255.0,
                        src[1] as f32 / 255.0,
                        src[2] as f32 / 255.0,
                    ],
                );
                px[0] = to_u8(rgb[0]);
                px[1] = to_u8(rgb[1]);
                px[2] = to_u8(rgb[2]);
            }
            return Some(out);
        }
        for row in 0..h {
            for col in 0..w {
                let p = self.pixel(col as u32, row as u32)?;
                let o = (row * w + col) * 3;
                dst[o..o + 3].copy_from_slice(&p[..3]);
            }
        }
        Some(out)
    }

    /// Convert an opaque 8-bit CMYK source to a packed RGB8 buffer, one pixel
    /// through exactly the value `pixel()` yields. Box-averaging this buffer is
    /// byte-identical to the generic path's convert-each-tap-then-average,
    /// because each source pixel yields the identical RGB triple either way.
    ///
    /// `pixel()` normalises each byte to `[0, 1]` (through `/Decode` if
    /// present), calls `cmyk_to_rgb`, then rounds back to bytes. The entry and
    /// exit float round trips are the identity on bytes
    /// (`crate::color::cmyk::tests::byte_components_round_trip_exactly`), so the
    /// byte table is called directly; a `/Decode` array only remaps each
    /// channel byte, which a 256-entry table per channel precomputes with the
    /// same expression `pixel()` evaluates.
    ///
    /// `None` if the image is not that shape or exceeds the size cap (then the
    /// generic path runs, unchanged).
    pub(crate) fn cmyk_source_as_rgb8(&self) -> Option<Vec<u8>> {
        // 64 Mpx -> 192 MiB of RGB8; above this the generic per-tap path (whose
        // work is bounded by the footprint, not the source area) is preferred.
        const MAX_CONVERT_PIXELS: usize = 64 * 1024 * 1024;
        if self.is_stencil || self.bpc != 8 || !matches!(self.color_space, ImageColorSpace::Cmyk) {
            return None;
        }
        let luts = match self.decode.as_deref() {
            None => None,
            Some(d) if d.len() >= 4 => Some(std::array::from_fn::<[u8; 256], 4, _>(|c| {
                let [lo, hi] = d[c];
                std::array::from_fn(|b| {
                    crate::color::cmyk::cmyk_component_to_u8(lo + (b as f32 / 255.0) * (hi - lo))
                })
            })),
            // A short `/Decode` leaves later channels at the default in
            // `pixel()`; that shape stays on the generic path.
            Some(_) => return None,
        };
        let n = (self.width as usize).checked_mul(self.height as usize)?;
        if n == 0 || n > MAX_CONVERT_PIXELS || self.samples.len() < n * 4 {
            return None;
        }
        let mut out = vec![0u8; n * 3];
        for (cmyk, rgb) in self.samples[..n * 4]
            .chunks_exact(4)
            .zip(out.chunks_exact_mut(3))
        {
            let [c, m, y, k] = match &luts {
                None => [cmyk[0], cmyk[1], cmyk[2], cmyk[3]],
                Some(l) => [
                    l[0][cmyk[0] as usize],
                    l[1][cmyk[1] as usize],
                    l[2][cmyk[2] as usize],
                    l[3][cmyk[3] as usize],
                ],
            };
            rgb.copy_from_slice(&crate::color::cmyk::adobe_cmyk_to_srgb_u8(c, m, y, k));
        }
        Some(out)
    }

    /// The palette entry a raw Indexed sample selects: `/Decode` (when
    /// present) remaps the normalised sample into index units, then rounds and
    /// clamps to `hival`; otherwise the raw sample is the index. This is the
    /// single definition `pixel()` and [`Self::indexed_source_as_rgb8`] share.
    #[inline]
    fn indexed_palette_index(&self, raw: u32, hival: u32) -> usize {
        if self.decode.is_some() {
            let maxv = ((1u64 << self.bpc.min(16)) - 1).max(1) as f32;
            let normalized = raw as f32 / maxv;
            let decoded = match self.decode.as_ref().and_then(|d| d.first()) {
                Some([lo, hi]) => lo + normalized * (hi - lo),
                None => normalized,
            };
            decoded.round().clamp(0.0, hival as f32) as u32 as usize
        } else {
            raw.min(hival) as usize
        }
    }

    /// An Indexed (palette) image re-expressed as RGB8: the palette is resolved
    /// once into a `2^bpc`-entry table through the *exact* same index
    /// resolution (`/Decode` included) and base-space conversion `pixel()`
    /// uses, then every sample becomes a table lookup. `pixel()` on the
    /// promoted image answers the identical `[r, g, b, 255]` for every texel,
    /// so sampling it — nearest, bilinear, or box-averaged, with or without a
    /// soft mask — is byte-identical to sampling the original by construction,
    /// whether the original's path read the prepared `sample_lut` (2/4 bpc) or
    /// resolved each tap through `pixel()` (8 bpc). What the promotion buys is
    /// eligibility for the executor's axis-aligned RGB8 fast paths, and the
    /// RGB8 byte-sum branch of the generic sampler elsewhere: an 8-bit Indexed
    /// cover minified onto a page resolved its palette entry through `pixel()`
    /// for every one of millions of taps.
    ///
    /// Colour-key masks test the *raw* samples (palette indices) and are not
    /// promoted; that is the caller's check. `None` if the image is not that
    /// shape (stencil, 1 or 16 bpc, or not Indexed) or exceeds the size cap;
    /// then the generic path runs unchanged. One-bit Indexed images are
    /// served by the bilevel summed-area path and are deliberately excluded.
    pub(crate) fn indexed_promoted_to_rgb8(&self) -> Option<PreparedImage> {
        let samples = self.indexed_source_as_rgb8()?;
        Some(PreparedImage {
            color_space: ImageColorSpace::Rgb,
            bpc: 8,
            decode: None,
            sample_lut: None,
            samples,
            ..self.clone()
        })
    }

    /// Whether [`Self::indexed_source_as_rgb8`] expands this image, and the
    /// draw may therefore be served the expansion in its place: an Indexed
    /// image of 2, 4 or 8 bpc, not a stencil, with complete sample data, at
    /// most 64 Mpx, and without a colour-key mask (that tests the *raw*
    /// palette indices, which the expansion discards).
    pub(crate) fn indexed_promotion_eligible(&self) -> bool {
        // 64 Mpx -> 192 MiB of RGB8, the same ceiling as the CMYK conversion.
        const MAX_EXPAND_PIXELS: usize = 64 * 1024 * 1024;
        if !matches!(self.color_space, ImageColorSpace::Indexed { .. })
            || self.is_stencil
            || !matches!(self.bpc, 2 | 4 | 8)
            || matches!(self.mask, Some(ImageMask::ColorKey(_)))
        {
            return false;
        }
        let (w, h) = (self.width as usize, self.height as usize);
        let Some(n) = w.checked_mul(h) else {
            return false;
        };
        let Some(source_bits) = self.row_bits().checked_mul(h) else {
            return false;
        };
        n > 0 && n <= MAX_EXPAND_PIXELS && self.samples.len() >= source_bits / 8
    }

    /// The packed RGB8 expansion behind [`Self::indexed_promoted_to_rgb8`];
    /// `None` unless [`Self::indexed_promotion_eligible`].
    pub(crate) fn indexed_source_as_rgb8(&self) -> Option<Arc<[u8]>> {
        if !self.indexed_promotion_eligible() {
            return None;
        }
        let ImageColorSpace::Indexed {
            base,
            hival,
            lookup,
        } = &self.color_space
        else {
            return None;
        };
        let (w, h) = (self.width as usize, self.height as usize);
        let n = w * h;
        let row_bits = self.row_bits();
        let entries = 1usize << self.bpc;
        let palette: Vec<[u8; 3]> = (0..entries as u32)
            .map(|raw| {
                let rgb = indexed_rgb(
                    base,
                    *hival,
                    lookup,
                    self.indexed_palette_index(raw, *hival),
                );
                [to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2])]
            })
            .collect();
        let mut out_arc = zeroed_arc(n * 3);
        let out = unique_arc_mut(&mut out_arc);
        if self.bpc == 8 {
            // Rows are byte-aligned already (stride == width).
            for (&raw, rgb) in self.samples[..n].iter().zip(out.chunks_exact_mut(3)) {
                rgb.copy_from_slice(&palette[raw as usize]);
            }
        } else {
            let bpc = self.bpc as usize;
            let mask = (entries - 1) as u8;
            let per_byte = 8 / bpc;
            let row_bytes = row_bits / 8;
            for (row, out_row) in out.chunks_exact_mut(w * 3).enumerate() {
                let src_row = &self.samples[row * row_bytes..row * row_bytes + row_bytes];
                for (col, rgb) in out_row.chunks_exact_mut(3).enumerate() {
                    // MSB-first packing, as `read_bits` unpacks it.
                    let byte = src_row[col / per_byte];
                    let shift = 8 - bpc * (col % per_byte + 1);
                    let raw = (byte >> shift) & mask;
                    rgb.copy_from_slice(&palette[raw as usize]);
                }
            }
        }
        Some(out_arc)
    }

    /// Weighted box average of a prepared one-bit image over one destination
    /// pixel's fractional source footprint.
    ///
    /// The executor prepares the per-axis tap ranges (with fractional edge
    /// weights) once per destination column/row. This method therefore
    /// performs only packed-bit population counts, the fractional edge-tap
    /// corrections, and the two-entry color-table mix in the pixel loop.
    #[cfg(test)]
    pub(crate) fn binary_box_average(
        &self,
        cols: &AxisTaps,
        rows: &AxisTaps,
    ) -> Option<([u8; 4], u64)> {
        self.binary_box_average_with(self.binary_box_lut()?, cols, rows)
    }

    /// [`Self::binary_box_average`] through an explicit two-entry table, so a
    /// stencil (which has no `sample_lut`) can use it with
    /// [`Self::stencil_bilevel_lut`].
    pub(crate) fn binary_box_average_with(
        &self,
        (zero, one): ([u8; 4], [u8; 4]),
        cols: &AxisTaps,
        rows: &AxisTaps,
    ) -> Option<([u8; 4], u64)> {
        let weight = cols.total.checked_mul(rows.total)?;
        if weight == 0 {
            return None;
        }

        let row_bits = self.row_bits();
        let mut ones_w = 0u64;
        for source_y in rows.lo..=rows.hi {
            let base = source_y as usize * row_bits;
            let row_ones = self.weighted_row_ones(base, cols);
            let wy = rows.weight_at(source_y);
            ones_w += wy * row_ones;
        }
        let taps = (cols.hi - cols.lo + 1) as u64 * (rows.hi - rows.lo + 1) as u64;
        Some((mix_bilevel(zero, one, ones_w, weight), taps))
    }

    /// Weighted set-bit count of one packed source row over an axis range:
    /// fractional first/last taps, full interior taps via popcount. Result
    /// is scaled by `AXIS_TAP_SCALE`.
    fn weighted_row_ones(&self, base_bit: usize, cols: &AxisTaps) -> u64 {
        weighted_row_ones_in(&self.samples, base_bit, cols)
    }

    /// Straight RGBA at device point `(dx, dy)`, or `None` when the point is
    /// outside the unit square (or a stencil's transparent sample).
    pub fn shade(&self, dx: f64, dy: f64) -> Option<[u8; 4]> {
        self.shade_with_taps(dx, dy).0
    }

    /// Profiling variant that also returns base-image source texels sampled.
    #[cfg(feature = "profiling")]
    pub fn shade_profiled(&self, dx: f64, dy: f64) -> (Option<[u8; 4]>, u64) {
        self.shade_with_taps(dx, dy)
    }

    /// Sample for an *edge* device pixel whose center may fall outside the
    /// image quad: the sample point is clamped to the nearest in-quad point,
    /// so the partial-coverage sliver takes the nearest edge texel's color
    /// (A10 image-edge anti-aliasing; PDFium's edge behavior analog).
    pub(crate) fn shade_clamped(&self, dx: f64, dy: f64) -> Option<[u8; 4]> {
        let p = self.inv.apply(Point { x: dx, y: dy });
        let ux = p.x.clamp(0.0, 1.0 - 1e-9);
        let uy = p.y.clamp(0.0, 1.0 - 1e-9);
        self.shade_uv(ux, uy).0
    }

    /// Coverage (0..=255) of the device pixel whose center is `(dx, dy)` by
    /// the image's device-space quad.
    ///
    /// `None` means the pixel square is provably interior — the caller paints
    /// at full weight, byte-identical to the pre-A10 behavior. `Some(0)`
    /// means not painted.
    ///
    /// An axis-aligned placement (`inv.b == inv.c == 0` exactly, mirrors
    /// included) takes the pixel-centre rule at its outer edge, as the
    /// axis-aligned opaque fast paths do: a border pixel is covered fully
    /// (`Some(255)`) when its centre maps into `[0, 1)²` — the same half-open
    /// test `shade()` and those fast paths apply — and not at all otherwise.
    /// Masks still apply per sampled pixel; only the geometric edge is
    /// all-or-nothing. PDFium is all-or-nothing too, but paints every pixel
    /// the rectangle touches (it stretches the image over the outward-rounded
    /// rectangle), so a border pixel covered less than half differs; see the
    /// scoping note `masked-image-ring-20261108.md`.
    ///
    /// Rotated and sheared placements keep A10's fractional coverage: the
    /// pixel square maps under `inv` to a parallelogram in unit-image space,
    /// which is clipped against `[0,1]²` (Sutherland–Hodgman); the coverage
    /// is the clipped area over the parallelogram's area.
    pub(crate) fn edge_coverage(&self, dx: f64, dy: f64) -> Option<u16> {
        // Half-extent of the mapped pixel square per uv axis (bbox bound).
        let mu = 0.5 * (self.inv.a.abs() + self.inv.c.abs());
        let mv = 0.5 * (self.inv.b.abs() + self.inv.d.abs());
        let p = self.inv.apply(Point { x: dx, y: dy });
        if p.x >= mu && p.x <= 1.0 - mu && p.y >= mv && p.y <= 1.0 - mv {
            return None; // fully interior — full weight, untouched path
        }
        let full = (self.inv.a * self.inv.d - self.inv.b * self.inv.c).abs();
        if full <= 1e-18 {
            return Some(0);
        }
        if self.inv.b == 0.0 && self.inv.c == 0.0 {
            // Axis-aligned: whole pixels by centre (see the doc comment).
            let inside = (0.0..1.0).contains(&p.x) && (0.0..1.0).contains(&p.y);
            return Some(if inside { 255 } else { 0 });
        }
        // The pixel square's corners in uv space.
        let mut poly: [[f64; 2]; 8] = [[0.0; 2]; 8];
        let mut n = 4usize;
        for (i, (cx, cy)) in [(-0.5, -0.5), (0.5, -0.5), (0.5, 0.5), (-0.5, 0.5)]
            .into_iter()
            .enumerate()
        {
            poly[i] = [
                p.x + cx * self.inv.a + cy * self.inv.c,
                p.y + cx * self.inv.b + cy * self.inv.d,
            ];
        }
        // Clip against u≥0, u≤1, v≥0, v≤1.
        let mut scratch: [[f64; 2]; 8] = [[0.0; 2]; 8];
        for (axis, keep_ge, bound) in [
            (0, true, 0.0),
            (0, false, 1.0),
            (1, true, 0.0),
            (1, false, 1.0),
        ] {
            let mut m = 0usize;
            for i in 0..n {
                let a = poly[i];
                let b = poly[(i + 1) % n];
                let da = if keep_ge {
                    a[axis] - bound
                } else {
                    bound - a[axis]
                };
                let db = if keep_ge {
                    b[axis] - bound
                } else {
                    bound - b[axis]
                };
                if da >= 0.0 {
                    scratch[m] = a;
                    m += 1;
                }
                if (da >= 0.0) != (db >= 0.0) {
                    let t = da / (da - db);
                    scratch[m] = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];
                    m += 1;
                }
                if m >= scratch.len() {
                    break; // numeric degeneracy guard; polygon is convex ≤ 8
                }
            }
            poly[..m].copy_from_slice(&scratch[..m]);
            n = m;
            if n == 0 {
                return Some(0);
            }
        }
        // Shoelace area of the clipped polygon.
        let mut area2 = 0.0f64;
        for i in 0..n {
            let a = poly[i];
            let b = poly[(i + 1) % n];
            area2 += a[0] * b[1] - b[0] * a[1];
        }
        let cov = (area2.abs() * 0.5 / full).clamp(0.0, 1.0);
        Some((cov * 255.0 + 0.5) as u16)
    }

    fn shade_with_taps(&self, dx: f64, dy: f64) -> (Option<[u8; 4]>, u64) {
        let p = self.inv.apply(Point { x: dx, y: dy });
        if p.x < 0.0 || p.x >= 1.0 || p.y < 0.0 || p.y >= 1.0 {
            return (None, 0);
        }
        self.shade_uv(p.x, p.y)
    }

    /// The sampling body shared by [`Self::shade_with_taps`] (in-range
    /// centers) and [`Self::shade_clamped`] (edge pixels): `(px, py)` is a
    /// point inside the unit image square.
    fn shade_uv(&self, px: f64, py: f64) -> (Option<[u8; 4]>, u64) {
        let p = Point { x: px, y: py };
        // Column increases with u; row increases downward (row 0 at the top).
        let fx = p.x * self.width as f64 - 0.5;
        let fy = (1.0 - p.y) * self.height as f64 - 0.5;

        // Minification: average the source texels this device pixel covers.
        // Point-sampling a 300dpi scan onto a screen keeps one texel in nine
        // and discards the rest, which breaks strokes and drops thin glyphs.
        // PDFium area-averages here regardless of `/Interpolate`, and so do
        // we — the flag chooses the *magnification* filter, not whether to
        // throw away detail (ISO 32000-1 §8.9.5.2 calls it a quality hint).
        let (rgba, taps) = if self.footprint[0] > 1.0 || self.footprint[1] > 1.0 {
            let Some((rgba, taps)) = self.area_average(fx, fy) else {
                return (None, 0);
            };
            (rgba, taps as u64)
        } else {
            match self.interpolation {
                InterpolationMode::Nearest => {
                    let col = clampi(fx.round() as i64, self.width);
                    let row = clampi(fy.round() as i64, self.height);
                    let Some(rgba) = self.pixel(col, row) else {
                        return (None, 1);
                    };
                    (rgba, 1)
                }
                InterpolationMode::Bilinear => {
                    let Some(rgba) = self.bilinear(fx, fy) else {
                        return (None, 4);
                    };
                    (rgba, 4)
                }
            }
        };
        // An explicit hard `/Mask` cuts the texel out entirely (the reverse
        // polarity of a soft mask). Tested per source texel at the sample
        // point, independent of the soft-mask path.
        if let Some(mask) = &self.mask
            && self.mask_hides(mask, fx, fy, p.x, p.y)
        {
            return (None, taps);
        }
        // The soft mask (sampled in the unit square) scales alpha.
        let a = match &self.smask {
            Some(sm) => {
                // The mask has independent sample dimensions but shares the
                // base image's unit-square placement. Derive its own source
                // texels-per-device-pixel footprint from the image inverse;
                // MRC pages commonly attach a 300–500 dpi bilevel mask to a
                // foreground that is then rendered at screen resolution.
                let mask_footprint = self.smask_footprint(sm);
                let sa = sample_smask(sm, p.x, p.y, mask_footprint);
                (rgba[3] as f32 * sa) as u8
            }
            None => rgba[3],
        };
        if a == 0 {
            return (None, taps);
        }
        (Some([rgba[0], rgba[1], rgba[2], a]), taps)
    }

    /// Per-axis fractional box taps for this destination pixel's footprint
    /// (see [`axis_box_taps`]).
    pub(crate) fn box_taps_x(&self, fx: f64) -> Option<AxisTaps> {
        axis_box_taps(fx, (self.footprint[0] * 0.5).max(0.5), self.width)
    }

    /// See [`Self::box_taps_x`].
    pub(crate) fn box_taps_y(&self, fy: f64) -> Option<AxisTaps> {
        axis_box_taps(fy, (self.footprint[1] * 0.5).max(0.5), self.height)
    }

    /// This draw's soft-mask footprint in *mask* texels per device pixel.
    ///
    /// The mask has independent sample dimensions but shares the base image's
    /// unit-square placement, so its footprint comes from the image inverse
    /// scaled by the mask's own size. MRC pages commonly attach a 300–500 dpi
    /// bilevel mask to a foreground rendered at screen resolution.
    pub(crate) fn smask_footprint(&self, sm: &ImageSMask) -> [f64; 2] {
        [
            (self.inv.a.abs() + self.inv.c.abs()) * sm.width as f64,
            (self.inv.b.abs() + self.inv.d.abs()) * sm.height as f64,
        ]
    }

    /// Per-axis box taps for the soft mask at mask-texel coordinate `mfx`,
    /// given the footprint from [`Self::smask_footprint`]. Mirrors the halving
    /// and 0.5 floor [`sample_smask`] applies.
    pub(crate) fn smask_box_taps(f: f64, half_footprint: f64, len: u32) -> Option<AxisTaps> {
        axis_box_taps(f, (half_footprint * 0.5).max(0.5), len)
    }

    /// Area-weighted average of the source texels inside this device pixel's
    /// footprint (box filter with fractional-tap weights, PDFium
    /// `CStretchEngine` analog): every texel contributes proportionally to
    /// its overlap with the footprint, so a texel half inside the box counts
    /// half — uniform whole-texel counting rendered minified stencils and
    /// scans measurably bolder than PDFium.
    ///
    /// A stencil averages *coverage* into alpha, which is what gives a
    /// downscaled `/ImageMask` smooth edges instead of a ragged bitmap.
    fn area_average(&self, fx: f64, fy: f64) -> Option<([u8; 4], u32)> {
        // Preserve the separable fixed-point path for ordinary axis-aligned
        // draws (including quarter turns). For a genuinely rotated or sheared
        // draw, the mapped device pixel is a parallelogram: averaging its
        // enclosing rectangle includes texels the pixel never covers and
        // visibly over-blurs diagonal detail.
        if !self.has_axis_aligned_footprint() {
            return self.parallelogram_average(fx, fy);
        }

        let tx = self.box_taps_x(fx)?;
        let ty = self.box_taps_y(fy)?;
        let weight = tx.total.checked_mul(ty.total)?;
        if weight == 0 {
            return None;
        }
        let taps = (tx.hi - tx.lo + 1) * (ty.hi - ty.lo + 1);

        let mut acc = [0u64; 4];

        // Decoded JPEG/JPX RGB8 is already in the exact output component
        // representation. Summing those bytes directly avoids three generic
        // bit reads, normalization, color-space dispatch, and float-to-byte
        // conversions for every source tap.
        if !self.is_stencil
            && self.bpc == 8
            && self.decode.is_none()
            && matches!(self.color_space, ImageColorSpace::Rgb)
            && self.samples.len() >= self.width as usize * self.height as usize * 3
        {
            let stride = self.width as usize * 3;
            for row in ty.lo..=ty.hi {
                let wy = ty.weight_at(row);
                let start = row as usize * stride + tx.lo as usize * 3;
                let end = row as usize * stride + (tx.hi as usize + 1) * 3;
                let src = self.samples.get(start..end)?;
                for (col, rgb) in (tx.lo..).zip(src.chunks_exact(3)) {
                    let w = wy * tx.weight_at(col);
                    acc[0] += w * rgb[0] as u64;
                    acc[1] += w * rgb[1] as u64;
                    acc[2] += w * rgb[2] as u64;
                    acc[3] += w * 255;
                }
            }
            return weighted_average_rgba(acc, weight).map(|rgba| (rgba, taps));
        }

        // Gray/Indexed/Tint images have one raw component. The prepared LUT
        // resolves that component to RGBA once, rather than repeating color
        // conversion for every tap in every destination pixel.
        if let Some(lut) = &self.sample_lut {
            let row_bits = self.row_bits();
            if self.bpc == 1 {
                let zero = lut.first().copied().unwrap_or([0, 0, 0, 255]);
                let one = lut.get(1).copied().unwrap_or(zero);
                let mut ones_w = 0u64;
                for row in ty.lo..=ty.hi {
                    let base = row as usize * row_bits;
                    ones_w += ty.weight_at(row) * self.weighted_row_ones(base, &tx);
                }
                return Some((mix_bilevel(zero, one, ones_w, weight), taps));
            }
            for row in ty.lo..=ty.hi {
                let wy = ty.weight_at(row);
                for col in tx.lo..=tx.hi {
                    let w = wy * tx.weight_at(col);
                    let bit = row as usize * row_bits + col as usize * self.bpc as usize;
                    let raw = read_bits(&self.samples, bit, self.bpc as usize) as usize;
                    let p = lut.get(raw).copied().unwrap_or([0, 0, 0, 255]);
                    for c in 0..4 {
                        acc[c] += w * p[c] as u64;
                    }
                }
            }
            return weighted_average_rgba(acc, weight).map(|rgba| (rgba, taps));
        }

        for row in ty.lo..=ty.hi {
            let wy = ty.weight_at(row);
            for col in tx.lo..=tx.hi {
                // A masked-out stencil texel contributes nothing, which is
                // exactly its zero coverage — but its weight still counts
                // toward the divisor, or the average would ignore the gaps.
                if let Some(p) = self.pixel(col, row) {
                    let w = wy * tx.weight_at(col);
                    for c in 0..4 {
                        acc[c] += w * p[c] as u64;
                    }
                }
            }
        }
        let out = weighted_average_rgba(acc, weight)?;
        // A stencil's colour is constant; only its coverage varies, so keep
        // the paint colour and let the averaged alpha carry the edge.
        if self.is_stencil {
            return Some((
                [
                    self.stencil_rgb[0],
                    self.stencil_rgb[1],
                    self.stencil_rgb[2],
                    out[3],
                ],
                taps,
            ));
        }
        Some((out, taps))
    }

    /// The two source-texel vectors spanned by one device pixel.
    ///
    /// `inv` maps device coordinates to the image unit square. Source rows
    /// increase downward, hence the sign inversion on the Y components.
    fn source_footprint_basis(&self) -> ([f64; 2], [f64; 2]) {
        (
            [
                self.inv.a * self.width as f64,
                -self.inv.b * self.height as f64,
            ],
            [
                self.inv.c * self.width as f64,
                -self.inv.d * self.height as f64,
            ],
        )
    }

    /// True when the footprint is already an axis-aligned rectangle in source
    /// space. The second case covers 90°/270° rotations, where the device axes
    /// are swapped but the texel footprint is still separable.
    fn has_axis_aligned_footprint(&self) -> bool {
        let (dx, dy) = self.source_footprint_basis();
        const EPS: f64 = 1e-9;
        (dx[1].abs() <= EPS && dy[0].abs() <= EPS) || (dx[0].abs() <= EPS && dy[1].abs() <= EPS)
    }

    /// Area-average over the exact source-space parallelogram covered by one
    /// device pixel. Each candidate texel receives its polygon-overlap area as
    /// a fixed-point weight; clipping against individual texel squares also
    /// clips the footprint to the image at its outer boundary.
    fn parallelogram_average(&self, fx: f64, fy: f64) -> Option<([u8; 4], u32)> {
        const WEIGHT_SCALE: f64 = 1_048_576.0;

        let (dx, dy) = self.source_footprint_basis();
        let hx = [dx[0] * 0.5, dx[1] * 0.5];
        let hy = [dy[0] * 0.5, dy[1] * 0.5];
        let footprint = ConvexQuad::new([
            [fx - hx[0] - hy[0], fy - hx[1] - hy[1]],
            [fx + hx[0] - hy[0], fy + hx[1] - hy[1]],
            [fx + hx[0] + hy[0], fy + hx[1] + hy[1]],
            [fx - hx[0] + hy[0], fy - hx[1] + hy[1]],
        ])?;

        // A texel centred at integer `i` occupies [i-.5, i+.5]. Including a
        // zero-area boundary neighbour is harmless; the overlap test drops it.
        let lo_x = clampi((footprint.bounds[0] + 0.5).floor() as i64, self.width);
        let hi_x = clampi((footprint.bounds[2] + 0.5).floor() as i64, self.width).max(lo_x);
        let lo_y = clampi((footprint.bounds[1] + 0.5).floor() as i64, self.height);
        let hi_y = clampi((footprint.bounds[3] + 0.5).floor() as i64, self.height).max(lo_y);

        let direct_rgb = !self.is_stencil
            && self.bpc == 8
            && self.decode.is_none()
            && matches!(self.color_space, ImageColorSpace::Rgb)
            && self.samples.len() >= self.width as usize * self.height as usize * 3;
        let mut acc = [0u64; 4];
        let mut total_weight = 0u64;
        let mut taps = 0u32;

        for row in lo_y..=hi_y {
            for col in lo_x..=hi_x {
                let area = footprint.rect_overlap_area(
                    col as f64 - 0.5,
                    col as f64 + 0.5,
                    row as f64 - 0.5,
                    row as f64 + 0.5,
                );
                if area <= f64::EPSILON {
                    continue;
                }
                // Keep a genuine but sub-quantum sliver represented, matching
                // the axis tap path's minimum non-zero edge weight.
                let weight = ((area * WEIGHT_SCALE).round() as u64).max(1);
                total_weight = total_weight.checked_add(weight)?;
                taps = taps.saturating_add(1);

                let pixel = if direct_rgb {
                    let offset =
                        (row as usize * self.width as usize + col as usize).checked_mul(3)?;
                    let rgb = self.samples.get(offset..offset + 3)?;
                    Some([rgb[0], rgb[1], rgb[2], 255])
                } else {
                    self.pixel(col, row)
                };
                // Transparent stencil texels contribute zero coverage, but
                // their area remains in the denominator.
                if let Some(pixel) = pixel {
                    for channel in 0..4 {
                        acc[channel] += weight * pixel[channel] as u64;
                    }
                }
            }
        }

        let mut out = weighted_average_rgba(acc, total_weight)?;
        if self.is_stencil {
            out[..3].copy_from_slice(&self.stencil_rgb);
        }
        Some((out, taps))
    }

    /// Bilinearly interpolate the four source pixels around `(fx, fy)`.
    fn bilinear(&self, fx: f64, fy: f64) -> Option<[u8; 4]> {
        let x0 = fx.floor();
        let y0 = fy.floor();
        let tx = (fx - x0) as f32;
        let ty = (fy - y0) as f32;
        let c = |ix: i64, iy: i64| self.pixel(clampi(ix, self.width), clampi(iy, self.height));
        let p00 = c(x0 as i64, y0 as i64)?;
        let p10 = c(x0 as i64 + 1, y0 as i64)?;
        let p01 = c(x0 as i64, y0 as i64 + 1)?;
        let p11 = c(x0 as i64 + 1, y0 as i64 + 1)?;
        let mut out = [0u8; 4];
        for ch in 0..4 {
            let top = p00[ch] as f32 * (1.0 - tx) + p10[ch] as f32 * tx;
            let bot = p01[ch] as f32 * (1.0 - tx) + p11[ch] as f32 * tx;
            // PDFium/MuPDF's fixed-point image stretch truncates the
            // interpolated channel. Rounding to nearest adds a repeatable
            // one-level bright bias over scan-sized images.
            out[ch] = (top * (1.0 - ty) + bot * ty).clamp(0.0, 255.0) as u8;
        }
        // Four equal alphas blend to that alpha exactly, but the f32 weights
        // `(1 - t) + t` can sum to just under one, and truncation then made
        // an opaque image 254/255 (the magnified bilinear fast path keeps
        // it opaque). Colour channels keep the truncating blend.
        if p00[3] == p10[3] && p00[3] == p01[3] && p00[3] == p11[3] {
            out[3] = p00[3];
        }
        Some(out)
    }

    /// One source pixel as straight RGBA, or `None` for a transparent stencil
    /// sample.
    fn pixel(&self, col: u32, row: u32) -> Option<[u8; 4]> {
        let ncomp = self.components();
        let row_bits = self.row_bits();
        let maxv = ((1u64 << self.bpc.min(16)) - 1).max(1) as f32;
        let read = |c: usize| -> u32 {
            let bit = row as usize * row_bits + (col as usize * ncomp + c) * self.bpc as usize;
            read_bits(&self.samples, bit, self.bpc as usize)
        };

        if self.is_stencil {
            // 1 = masked (default), 0 = paint; /Decode [1 0] inverts.
            let mut v = read(0);
            if self.stencil_decode_inverted() {
                v = 1 - v;
            }
            if v == 0 {
                return Some([
                    self.stencil_rgb[0],
                    self.stencil_rgb[1],
                    self.stencil_rgb[2],
                    255,
                ]);
            }
            return None;
        }

        if let Some(lut) = &self.sample_lut {
            return lut.get(read(0) as usize).copied();
        }

        // The common decoded JPEG/JPX formats need no `/Decode` transform.
        // Return their bytes directly instead of round-tripping through f32.
        if self.bpc == 8
            && self.decode.is_none()
            && self.samples.len() >= self.width as usize * self.height as usize * self.components()
        {
            let pixel = row as usize * self.width as usize + col as usize;
            match self.color_space {
                ImageColorSpace::Rgb => {
                    let offset = pixel * 3;
                    let rgb = self.samples.get(offset..offset + 3)?;
                    return Some([rgb[0], rgb[1], rgb[2], 255]);
                }
                ImageColorSpace::Gray => {
                    let g = *self.samples.get(pixel)?;
                    return Some([g, g, g, 255]);
                }
                _ => {}
            }
        }

        // Normalize each component with the /Decode remap (default [0,1]).
        let comp = |c: usize| -> f32 {
            let raw = read(c) as f32 / maxv;
            match self.decode.as_ref().and_then(|d| d.get(c)) {
                Some([lo, hi]) => lo + raw * (hi - lo),
                None => raw,
            }
        };

        let rgb = match &self.color_space {
            ImageColorSpace::Gray => {
                let g = comp(0).clamp(0.0, 1.0);
                [g, g, g]
            }
            ImageColorSpace::Rgb => [
                comp(0).clamp(0.0, 1.0),
                comp(1).clamp(0.0, 1.0),
                comp(2).clamp(0.0, 1.0),
            ],
            ImageColorSpace::Cmyk => crate::color::cmyk_to_rgb(
                comp(0).clamp(0.0, 1.0),
                comp(1).clamp(0.0, 1.0),
                comp(2).clamp(0.0, 1.0),
                comp(3).clamp(0.0, 1.0),
            ),
            // Samples arrive normalised to 0..1; Lab's axes are not. Map them
            // onto the space's own ranges before converting — L* over 0..100
            // and a*/b* over `/Range` — which is exactly the default `/Decode`
            // for a Lab image (ISO 32000-1 Table 89).
            ImageColorSpace::Lab { white_point, range } => {
                let axis = |v: f32, lo: f32, hi: f32| lo + v.clamp(0.0, 1.0) * (hi - lo);
                crate::color::lab_to_rgb(
                    axis(comp(0), 0.0, 100.0),
                    axis(comp(1), range[0], range[1]),
                    axis(comp(2), range[2], range[3]),
                    *white_point,
                    *range,
                )
            }
            ImageColorSpace::Indexed {
                base,
                hival,
                lookup,
            } => {
                // `/Decode` remaps the sample to a palette *index* (default is
                // identity `[0, 2^bpc-1]`). When present — e.g. `[0 255]` on a
                // 1-bit image, where sample 1 must select index 255, not 1 —
                // the remap yields the index directly (its units are index
                // units here); ignoring it reads the wrong palette entry and
                // inverts bilevel scans. Shared with the executor's one-shot
                // palette expansion so both resolve a raw sample identically.
                let idx = self.indexed_palette_index(read(0), *hival);
                indexed_rgb(base, *hival, lookup, idx)
            }
            ImageColorSpace::TintLut { rgb } => tint_lut_rgb(rgb, comp(0)),
            ImageColorSpace::TintLut2 { rgb } => tint_lut2_rgb(rgb, comp(0), comp(1)),
            ImageColorSpace::IccRgb { trc, matrix } => {
                crate::color::icc::to_srgb_with(trc, matrix, [comp(0), comp(1), comp(2)])
            }
            ImageColorSpace::IccCmyk { transform } => crate::color::icc::cmyk_to_srgb_with(
                transform.grid as usize,
                [
                    &transform.input_tables[0],
                    &transform.input_tables[1],
                    &transform.input_tables[2],
                    &transform.input_tables[3],
                ],
                &transform.clut,
                [
                    &transform.output_tables[0],
                    &transform.output_tables[1],
                    &transform.output_tables[2],
                ],
                [comp(0), comp(1), comp(2), comp(3)],
            ),
        };
        Some([to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2]), 255])
    }

    /// True when the explicit `/Mask` makes the texel at `(fx, fy)` fully
    /// transparent. `(fx, fy)` is the base-image texel coordinate; `(u, v)` is
    /// the unit-square point used to resample an independent stencil.
    fn mask_hides(&self, mask: &ImageMask, fx: f64, fy: f64, u: f64, v: f64) -> bool {
        match mask {
            ImageMask::ColorKey(ranges) => {
                let col = clampi(fx.round() as i64, self.width);
                let row = clampi(fy.round() as i64, self.height);
                self.color_key_hit(ranges, col, row)
            }
            ImageMask::Stencil(sm) => stencil_hides(sm, u, v),
        }
    }

    /// Color-key test: every component's RAW sample (before `/Decode`) must lie
    /// within its `[min, max]`. A range count that disagrees with the component
    /// count means a malformed mask — treat as no mask (never hide).
    fn color_key_hit(&self, ranges: &[[u32; 2]], col: u32, row: u32) -> bool {
        let ncomp = self.components();
        if ranges.len() != ncomp {
            return false;
        }
        let row_bits = self.row_bits();
        for (c, &[lo, hi]) in ranges.iter().enumerate() {
            let bit = row as usize * row_bits + (col as usize * ncomp + c) * self.bpc as usize;
            let raw = read_bits(&self.samples, bit, self.bpc as usize);
            if raw < lo || raw > hi {
                return false;
            }
        }
        true
    }
}

/// One mapped device-pixel footprint, with its inward edge equations and
/// bounds prepared once for all candidate source texels.
struct ConvexQuad {
    vertices: [[f64; 2]; 4],
    /// Inward half-plane equations `a*x + b*y + c >= 0`.
    edges: [[f64; 3]; 4],
    /// `[min_x, min_y, max_x, max_y]`.
    bounds: [f64; 4],
    area: f64,
}

impl ConvexQuad {
    fn new(vertices: [[f64; 2]; 4]) -> Option<Self> {
        let mut twice_area = 0.0;
        for index in 0..4 {
            let a = vertices[index];
            let b = vertices[(index + 1) % 4];
            twice_area += a[0] * b[1] - b[0] * a[1];
        }
        if !twice_area.is_finite() || twice_area.abs() <= f64::EPSILON {
            return None;
        }
        let orientation = twice_area.signum();
        let mut edges = [[0.0; 3]; 4];
        for index in 0..4 {
            let a = vertices[index];
            let b = vertices[(index + 1) % 4];
            let ex = b[0] - a[0];
            let ey = b[1] - a[1];
            edges[index] = [
                -orientation * ey,
                orientation * ex,
                orientation * (ey * a[0] - ex * a[1]),
            ];
        }
        let min_x = vertices.iter().map(|p| p[0]).fold(f64::INFINITY, f64::min);
        let max_x = vertices
            .iter()
            .map(|p| p[0])
            .fold(f64::NEG_INFINITY, f64::max);
        let min_y = vertices.iter().map(|p| p[1]).fold(f64::INFINITY, f64::min);
        let max_y = vertices
            .iter()
            .map(|p| p[1])
            .fold(f64::NEG_INFINITY, f64::max);
        Some(Self {
            vertices,
            edges,
            bounds: [min_x, min_y, max_x, max_y],
            area: twice_area.abs() * 0.5,
        })
    }

    /// Exact overlap with one texel square. Interior and disjoint texels are
    /// classified from the precomputed half planes; only boundary texels pay
    /// for polygon clipping.
    fn rect_overlap_area(&self, x0: f64, x1: f64, y0: f64, y1: f64) -> f64 {
        if x1 <= self.bounds[0]
            || x0 >= self.bounds[2]
            || y1 <= self.bounds[1]
            || y0 >= self.bounds[3]
        {
            return 0.0;
        }
        let corners = [[x0, y0], [x1, y0], [x1, y1], [x0, y1]];
        let mut rect_inside = true;
        for &[a, b, c] in &self.edges {
            let mut inside = 0u8;
            for point in corners {
                inside += (a * point[0] + b * point[1] + c >= -1e-12) as u8;
            }
            if inside == 0 {
                return 0.0;
            }
            rect_inside &= inside == 4;
        }
        if rect_inside {
            return 1.0;
        }
        if self.vertices.iter().all(|p| {
            p[0] >= x0 - 1e-12 && p[0] <= x1 + 1e-12 && p[1] >= y0 - 1e-12 && p[1] <= y1 + 1e-12
        }) {
            return self.area.clamp(0.0, 1.0);
        }
        polygon_rect_overlap_area_clipped(&self.vertices, x0, x1, y0, y1)
    }
}

/// Slow boundary case for [`ConvexQuad::rect_overlap_area`]. Successive
/// half-plane clips can add at most one vertex each, so twelve stack slots are
/// ample and avoid allocating in the rotated-image pixel loop.
fn polygon_rect_overlap_area_clipped(
    quad: &[[f64; 2]; 4],
    x0: f64,
    x1: f64,
    y0: f64,
    y1: f64,
) -> f64 {
    let mut polygon = [[0.0; 2]; 12];
    polygon[..4].copy_from_slice(quad);
    let mut count = 4usize;
    let mut scratch = [[0.0; 2]; 12];

    for (axis, keep_greater, bound) in [
        (0usize, true, x0),
        (0usize, false, x1),
        (1usize, true, y0),
        (1usize, false, y1),
    ] {
        let mut next_count = 0usize;
        for index in 0..count {
            let a = polygon[index];
            let b = polygon[(index + 1) % count];
            let da = if keep_greater {
                a[axis] - bound
            } else {
                bound - a[axis]
            };
            let db = if keep_greater {
                b[axis] - bound
            } else {
                bound - b[axis]
            };
            if da >= 0.0 {
                scratch[next_count] = a;
                next_count += 1;
            }
            if (da >= 0.0) != (db >= 0.0) {
                let t = da / (da - db);
                scratch[next_count] = [a[0] + t * (b[0] - a[0]), a[1] + t * (b[1] - a[1])];
                next_count += 1;
            }
        }
        if next_count == 0 {
            return 0.0;
        }
        polygon[..next_count].copy_from_slice(&scratch[..next_count]);
        count = next_count;
    }

    let mut twice_area = 0.0;
    for index in 0..count {
        let a = polygon[index];
        let b = polygon[(index + 1) % count];
        twice_area += a[0] * b[1] - b[0] * a[1];
    }
    (twice_area.abs() * 0.5).clamp(0.0, 1.0)
}

/// Build a raw-sample-to-RGBA table for low-bit-depth single-component images.
/// Restricting this to 1/2/4 bpc keeps preparation cheap for documents with
/// many ordinary 8-bit grayscale images while covering bilevel/Indexed scans,
/// where generic per-tap color conversion is disproportionately expensive.
pub(crate) fn build_sample_lut(
    bits_per_component: u8,
    color_space: &ImageColorSpace,
    decode: Option<&[[f32; 2]]>,
    is_stencil: bool,
) -> Option<Arc<[[u8; 4]]>> {
    if is_stencil || bits_per_component == 0 || bits_per_component > 4 {
        return None;
    }
    if color_space.components() != 1 {
        return None;
    }

    let entries = 1usize << bits_per_component;
    let maxv = (entries - 1).max(1) as f32;
    let mut lut = Vec::with_capacity(entries);
    for raw in 0..entries {
        let normalized = raw as f32 / maxv;
        let decoded = match decode.and_then(|d| d.first()) {
            Some([lo, hi]) => lo + normalized * (hi - lo),
            None => normalized,
        };
        let rgb = match color_space {
            ImageColorSpace::Gray => {
                let g = decoded.clamp(0.0, 1.0);
                [g, g, g]
            }
            ImageColorSpace::Indexed {
                base,
                hival,
                lookup,
            } => {
                let idx = if decode.is_some() {
                    decoded.round().clamp(0.0, *hival as f32) as usize
                } else {
                    raw.min(*hival as usize)
                };
                indexed_rgb(base, *hival, lookup, idx)
            }
            ImageColorSpace::TintLut { rgb } => tint_lut_rgb(rgb, decoded),
            // Multi-component spaces have no single-sample LUT.
            ImageColorSpace::Rgb
            | ImageColorSpace::Cmyk
            | ImageColorSpace::Lab { .. }
            | ImageColorSpace::TintLut2 { .. }
            | ImageColorSpace::IccRgb { .. }
            | ImageColorSpace::IccCmyk { .. } => {
                return None;
            }
        };
        lut.push([to_u8(rgb[0]), to_u8(rgb[1]), to_u8(rgb[2]), 255]);
    }
    Some(lut.into())
}

/// Fixed-point scale for fractional box-filter tap weights. 4096 keeps the
/// arithmetic integral (deterministic and memoizable) while resolving an
/// edge tap's overlap to 1/4096 of a texel.
pub(crate) const AXIS_TAP_SCALE: u64 = 4096;

/// One axis of a destination pixel's source footprint: the inclusive texel
/// range `[lo, hi]` plus fractional first/last weights in `AXIS_TAP_SCALE`
/// units (interior taps weigh a full `AXIS_TAP_SCALE`). `total` is the sum
/// of all tap weights along the axis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct AxisTaps {
    pub lo: u32,
    pub hi: u32,
    pub w_lo: u64,
    pub w_hi: u64,
    pub total: u64,
}

impl AxisTaps {
    /// Weight of texel `i` (must be within `lo..=hi`).
    #[inline]
    pub(crate) fn weight_at(&self, i: u32) -> u64 {
        if i == self.lo {
            self.w_lo
        } else if i == self.hi {
            self.w_hi
        } else {
            AXIS_TAP_SCALE
        }
    }
}

/// Compute one axis's box-filter taps: the footprint `[f − half, f + half]`
/// (texel-center coordinates around `f`) is intersected with each texel, and
/// each texel's weight is its overlap fraction. Texels the box only grazes
/// therefore contribute proportionally instead of counting whole — the
/// area-correct minification weighting (PDFium `CStretchEngine` analog).
///
/// The box is clipped to the image, so edge-of-image pixels normalize over
/// the in-image weight only. `None` when the clipped box is empty.
pub(crate) fn axis_box_taps(f: f64, half: f64, len: u32) -> Option<AxisTaps> {
    if len == 0 || !f.is_finite() {
        return None;
    }
    // Texel j covers [j, j+1) in edge coordinates; the pixel center `f` sits
    // at edge coordinate f + 0.5.
    let left = (f + 0.5 - half).max(0.0);
    let right = (f + 0.5 + half).min(len as f64);
    if right <= left {
        // Footprint entirely off-image: take the nearest edge texel whole
        // (matches the previous clamped behavior for callers that sample
        // slightly outside).
        let nearest = clampi(f.round() as i64, len);
        return Some(AxisTaps {
            lo: nearest,
            hi: nearest,
            w_lo: AXIS_TAP_SCALE,
            w_hi: AXIS_TAP_SCALE,
            total: AXIS_TAP_SCALE,
        });
    }
    let lo = clampi(left.floor() as i64, len);
    let hi = clampi((right.ceil() - 1.0) as i64, len).max(lo);
    let scale = AXIS_TAP_SCALE as f64;
    if lo == hi {
        let w = (((right - left).min(1.0) * scale).round() as u64).max(1);
        return Some(AxisTaps {
            lo,
            hi,
            w_lo: w,
            w_hi: w,
            total: w,
        });
    }
    let w_lo = ((((lo + 1) as f64 - left).clamp(0.0, 1.0) * scale).round() as u64).max(1);
    let w_hi = (((right - hi as f64).clamp(0.0, 1.0) * scale).round() as u64).max(1);
    let interior = (hi - lo).saturating_sub(1) as u64;
    Some(AxisTaps {
        lo,
        hi,
        w_lo,
        w_hi,
        total: w_lo + w_hi + interior * AXIS_TAP_SCALE,
    })
}

/// Mix a bilevel image's two LUT colors by the weighted ones fraction
/// (`ones_w / weight`), rounding to nearest.
#[inline]
pub(crate) fn mix_bilevel(zero: [u8; 4], one: [u8; 4], ones_w: u64, weight: u64) -> [u8; 4] {
    if ones_w == 0 {
        return zero;
    }
    if ones_w >= weight {
        return one;
    }
    let zeros_w = weight - ones_w;
    let mut out = [0u8; 4];
    for c in 0..4 {
        let acc = zero[c] as u64 * zeros_w + one[c] as u64 * ones_w;
        out[c] = ((acc + weight / 2) / weight) as u8;
    }
    out
}

#[inline]
fn weighted_average_rgba(acc: [u64; 4], weight: u64) -> Option<[u8; 4]> {
    (weight != 0).then(|| {
        [
            ((acc[0] + weight / 2) / weight).min(255) as u8,
            ((acc[1] + weight / 2) / weight).min(255) as u8,
            ((acc[2] + weight / 2) / weight).min(255) as u8,
            ((acc[3] + weight / 2) / weight).min(255) as u8,
        ]
    })
}

/// Stencil `/Mask` test at unit-square `(u, v)`: sample the 1-bit mask (its own
/// geometry) and return whether the base pixel is masked out. A mask sample of
/// 1 (after the mask's `/Decode`, default `[0 1]`) hides; 0 paints — the
/// reverse of an `/SMask` luminosity.
fn stencil_hides(sm: &ImageSMask, u: f64, v: f64) -> bool {
    if sm.width == 0 || sm.height == 0 {
        return false;
    }
    stencil_hides_at(sm, stencil_col(sm, u), stencil_row(sm, v))
}

/// The stencil texel column a unit-square `u` point-samples. Depends only on
/// `u`, so an axis-aligned draw can prepare it once per destination column.
pub(crate) fn stencil_col(sm: &ImageSMask, u: f64) -> u32 {
    clampi((u * sm.width as f64) as i64, sm.width)
}

/// See [`stencil_col`]; rows increase downward, hence the `1 - v`.
pub(crate) fn stencil_row(sm: &ImageSMask, v: f64) -> u32 {
    clampi(((1.0 - v) * sm.height as f64) as i64, sm.height)
}

/// The body of [`stencil_hides`] once the texel has been located.
pub(crate) fn stencil_hides_at(sm: &ImageSMask, col: u32, row: u32) -> bool {
    let (col, row) = (col as usize, row as usize);
    let bpc = sm.bits_per_component.max(1) as usize;
    let row_bits = (sm.width as usize * bpc).div_ceil(8) * 8;
    let bit = row * row_bits + col * bpc;
    let raw = read_bits(&sm.samples, bit, bpc);
    // `/Decode [1 0]` swaps the polarity.
    let inverted = sm
        .decode
        .as_ref()
        .and_then(|d| d.first())
        .map(|p| p[0] > p[1])
        .unwrap_or(false);
    if inverted { raw == 0 } else { raw != 0 }
}

/// Look up an Indexed palette entry and convert it through the base space.
fn indexed_rgb(base: &ImageColorSpace, _hival: u32, lookup: &[u8], idx: usize) -> [f32; 3] {
    let bn = base.components();
    let off = idx * bn;
    let get = |c: usize| {
        lookup
            .get(off + c)
            .map(|b| *b as f32 / 255.0)
            .unwrap_or(0.0)
    };
    match base {
        ImageColorSpace::Gray => {
            let g = get(0);
            [g, g, g]
        }
        ImageColorSpace::Rgb => [get(0), get(1), get(2)],
        ImageColorSpace::Cmyk => crate::color::cmyk_to_rgb(get(0), get(1), get(2), get(3)),
        // A Lab palette entry: bytes are the normalised axes (the Indexed
        // lookup is always 8-bit), so map them onto the space's ranges.
        ImageColorSpace::Lab { white_point, range } => {
            let axis = |v: f32, lo: f32, hi: f32| lo + v * (hi - lo);
            crate::color::lab_to_rgb(
                axis(get(0), 0.0, 100.0),
                axis(get(1), range[0], range[1]),
                axis(get(2), range[2], range[3]),
                *white_point,
                *range,
            )
        }
        // Nested Indexed is not valid; treat as gray.
        ImageColorSpace::Indexed { .. } => {
            let g = get(0);
            [g, g, g]
        }
        // An Indexed palette over a Separation base: each palette entry is a
        // tint; route it through the baked LUT.
        ImageColorSpace::TintLut { rgb } => tint_lut_rgb(rgb, get(0)),
        ImageColorSpace::TintLut2 { rgb } => tint_lut2_rgb(rgb, get(0), get(1)),
        ImageColorSpace::IccRgb { trc, matrix } => {
            crate::color::icc::to_srgb_with(trc, matrix, [get(0), get(1), get(2)])
        }
        ImageColorSpace::IccCmyk { transform } => crate::color::icc::cmyk_to_srgb_with(
            transform.grid as usize,
            [
                &transform.input_tables[0],
                &transform.input_tables[1],
                &transform.input_tables[2],
                &transform.input_tables[3],
            ],
            &transform.clut,
            [
                &transform.output_tables[0],
                &transform.output_tables[1],
                &transform.output_tables[2],
            ],
            [get(0), get(1), get(2), get(3)],
        ),
    }
}

/// Map a normalized tint (`0..1`, `/Decode` already applied) through a baked
/// 256-entry sample→sRGB `/Separation` table.
/// Map a normalised pair of tints through a baked `256 x 256 x 3` table.
fn tint_lut2_rgb(rgb: &[u8], a: f32, b: f32) -> [f32; 3] {
    let ia = ((a.clamp(0.0, 1.0) * 255.0).round() as usize).min(255);
    let ib = ((b.clamp(0.0, 1.0) * 255.0).round() as usize).min(255);
    let o = (ia * 256 + ib) * 3;
    match rgb.get(o..o + 3) {
        Some(p) => [
            p[0] as f32 / 255.0,
            p[1] as f32 / 255.0,
            p[2] as f32 / 255.0,
        ],
        None => [0.0, 0.0, 0.0],
    }
}

fn tint_lut_rgb(rgb: &[u8], tint: f32) -> [f32; 3] {
    let idx = ((tint.clamp(0.0, 1.0) * 255.0).round() as usize).min(255);
    let o = idx * 3;
    match rgb.get(o..o + 3) {
        Some(p) => [
            p[0] as f32 / 255.0,
            p[1] as f32 / 255.0,
            p[2] as f32 / 255.0,
        ],
        None => [0.0, 0.0, 0.0],
    }
}

/// Sample a grayscale soft mask at unit-square `(u, v)` → alpha in `[0, 1]`.
///
/// Minified masks are box-filtered over the destination pixel's fractional
/// source footprint, exactly like their base image. Point-sampling a 1-bit MRC
/// mask otherwise keeps one source bit in ten or twenty and turns a smooth
/// coverage edge into an arbitrary opaque/transparent choice.
/// Packed row stride, in bits, of a soft mask's samples (rows are byte-aligned).
pub(crate) fn smask_row_bits(sm: &ImageSMask) -> usize {
    (sm.width as usize * sm.bits_per_component as usize).div_ceil(8) * 8
}

/// Fractional set-bit coverage of a **one-bit** soft mask over one destination
/// pixel's prepared per-axis tap boxes, in `0..=1`.
///
/// Shared by [`sample_smask`], which derives the taps per pixel, and the
/// executor's axis-aligned MRC fast path, which hoists them per destination
/// column and row — both then produce the identical alpha byte.
pub(crate) fn bilevel_smask_coverage(sm: &ImageSMask, tx: &AxisTaps, ty: &AxisTaps) -> f32 {
    let row_bits = smask_row_bits(sm);
    let weight = tx.total.saturating_mul(ty.total).max(1);
    let mut ones_w = 0u64;
    for row in ty.lo..=ty.hi {
        let row_ones = weighted_row_ones_in(&sm.samples, row as usize * row_bits, tx);
        ones_w = ones_w.saturating_add(ty.weight_at(row).saturating_mul(row_ones));
    }
    ones_w as f32 / weight as f32
}

/// Box-filtered coverage of an 8-bit `/SMask` over the prepared tap ranges:
/// the arithmetic of [`sample_smask`]'s multi-bit branch term for term — each
/// tap's `(wy * wx) * sample` accumulated in f64 in row-major order, divided
/// by the total weight, narrowed to f32 — so the executor's prepared masked
/// path paints the same alpha the generic per-pixel sampler does. `sm.samples`
/// must hold `width * height` bytes (the caller's eligibility check).
pub(crate) fn gray8_smask_coverage(sm: &ImageSMask, tx: &AxisTaps, ty: &AxisTaps) -> f32 {
    let row_bytes = smask_row_bits(sm) / 8;
    let weight = tx.total.saturating_mul(ty.total).max(1);
    let maxv = 255.0f64;
    let mut acc = 0.0f64;
    for row in ty.lo..=ty.hi {
        let wy = ty.weight_at(row) as f64;
        let base = row as usize * row_bytes;
        let texels = &sm.samples[base + tx.lo as usize..=base + tx.hi as usize];
        for (col, &texel) in (tx.lo..).zip(texels) {
            let sample = texel as f64 / maxv;
            acc += wy * tx.weight_at(col) as f64 * sample;
        }
    }
    (acc / weight as f64) as f32
}

/// Apply a soft mask's `/Decode` remap to a normalised sample.
pub(crate) fn apply_smask_decode(sm: &ImageSMask, raw: f32) -> f32 {
    match sm.decode.as_ref().and_then(|d| d.first()) {
        Some([lo, hi]) => (lo + raw * (hi - lo)).clamp(0.0, 1.0),
        None => raw,
    }
}

fn sample_smask(sm: &ImageSMask, u: f64, v: f64, footprint: [f64; 2]) -> f32 {
    if sm.width == 0 || sm.height == 0 {
        return 1.0;
    }
    let row_bits = smask_row_bits(sm);
    let maxv = ((1u64 << sm.bits_per_component.min(16)) - 1).max(1) as f32;
    let fx = u * sm.width as f64 - 0.5;
    let fy = (1.0 - v) * sm.height as f64 - 0.5;

    let raw = if footprint[0] > 1.0 || footprint[1] > 1.0 {
        let Some(tx) = PreparedImage::smask_box_taps(fx, footprint[0], sm.width) else {
            return 1.0;
        };
        let Some(ty) = PreparedImage::smask_box_taps(fy, footprint[1], sm.height) else {
            return 1.0;
        };
        let weight = tx.total.saturating_mul(ty.total).max(1);
        if sm.bits_per_component == 1 {
            bilevel_smask_coverage(sm, &tx, &ty)
        } else {
            let bpc = sm.bits_per_component as usize;
            let mut acc = 0.0f64;
            for row in ty.lo..=ty.hi {
                let wy = ty.weight_at(row) as f64;
                for col in tx.lo..=tx.hi {
                    let bit = row as usize * row_bits + col as usize * bpc;
                    let sample = read_bits(&sm.samples, bit, bpc) as f64 / maxv as f64;
                    acc += wy * tx.weight_at(col) as f64 * sample;
                }
            }
            (acc / weight as f64) as f32
        }
    } else {
        let col = clampi((u * sm.width as f64) as i64, sm.width) as usize;
        let row = clampi(((1.0 - v) * sm.height as f64) as i64, sm.height) as usize;
        let bit = row * row_bits + col * sm.bits_per_component as usize;
        read_bits(&sm.samples, bit, sm.bits_per_component as usize) as f32 / maxv
    };
    apply_smask_decode(sm, raw)
}

/// Read a big-endian `bits`-wide field starting at bit offset `bit`.
fn read_bits(data: &[u8], bit: usize, bits: usize) -> u32 {
    // The byte-aligned widths are the overwhelming majority of real images and
    // are where the sampler's time goes: the minification filter reads every
    // texel of a device pixel's footprint, so a bit-at-a-time loop costs ~24
    // bounds-checked reads per 8-bit RGB texel. Take them whole.
    if bit.is_multiple_of(8) {
        match bits {
            8 => return data.get(bit / 8).copied().unwrap_or(0) as u32,
            16 => {
                let i = bit / 8;
                let hi = data.get(i).copied().unwrap_or(0) as u32;
                let lo = data.get(i + 1).copied().unwrap_or(0) as u32;
                return (hi << 8) | lo;
            }
            _ => {}
        }
    }
    // 1/2/4 bpc, or an unaligned start: walk the bits.
    let mut v: u32 = 0;
    for i in 0..bits {
        let b = bit + i;
        let byte = b / 8;
        let shift = 7 - (b % 8);
        let bitval = data.get(byte).map(|x| (x >> shift) & 1).unwrap_or(0);
        v = (v << 1) | bitval as u32;
    }
    v
}

/// Count set bits in an arbitrary MSB-first bit range. Full source bytes use
/// `count_ones`; only the two boundary fragments are masked individually.
fn count_one_bits(data: &[u8], start_bit: usize, bit_len: usize) -> u32 {
    if bit_len == 0 {
        return 0;
    }

    let mut bit = start_bit;
    let end = start_bit.saturating_add(bit_len);
    let mut count = 0u32;

    if !bit.is_multiple_of(8) {
        let take = (8 - bit % 8).min(end - bit);
        let offset = bit % 8;
        let mask = (0xffu8 >> offset) & (0xffu8 << (8 - offset - take));
        count += (data.get(bit / 8).copied().unwrap_or(0) & mask).count_ones();
        bit += take;
    }

    while bit + 8 <= end {
        count += data.get(bit / 8).copied().unwrap_or(0).count_ones();
        bit += 8;
    }

    if bit < end {
        let take = end - bit;
        let mask = 0xffu8 << (8 - take);
        count += (data.get(bit / 8).copied().unwrap_or(0) & mask).count_ones();
    }
    count
}

/// Weighted set-bit count for an arbitrary packed row and horizontal tap
/// range. Full interior bytes use [`count_one_bits`]; only the fractional edge
/// texels are read individually.
pub(crate) fn weighted_row_ones_in(data: &[u8], base_bit: usize, cols: &AxisTaps) -> u64 {
    let bit_at = |x: u32| -> u64 {
        let b = base_bit + x as usize;
        let byte = data.get(b / 8).copied().unwrap_or(0);
        ((byte >> (7 - (b % 8))) & 1) as u64
    };
    if cols.lo == cols.hi {
        return cols.w_lo * bit_at(cols.lo);
    }
    let mut ones = cols.w_lo * bit_at(cols.lo) + cols.w_hi * bit_at(cols.hi);
    if cols.hi - cols.lo >= 2 {
        let interior = count_one_bits(
            data,
            base_bit + cols.lo as usize + 1,
            (cols.hi - cols.lo - 1) as usize,
        ) as u64;
        ones += AXIS_TAP_SCALE * interior;
    }
    ones
}

#[inline]
fn clampi(v: i64, len: u32) -> u32 {
    // `.max(0)` keeps this total for `len == 0` (i64::clamp panics when
    // min > max); lowering rejects zero-dimension images, this is the backstop.
    v.clamp(0, (len as i64 - 1).max(0)) as u32
}

#[inline]
fn to_u8(v: f32) -> u8 {
    (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;
    use crate::page_ir::{BlendMode, DeviceRect};

    /// A minimal `PreparedImage` with an identity device→unit-square map, so a
    /// device point `(dx, dy)` in `[0,1)` samples directly. Nearest, no
    /// minification (footprint 1), no soft mask.
    fn img(
        width: u32,
        height: u32,
        color_space: ImageColorSpace,
        samples: Vec<u8>,
        mask: Option<ImageMask>,
    ) -> PreparedImage {
        let sample_lut = build_sample_lut(8, &color_space, None, false);
        PreparedImage {
            origin: crate::page_ir::PaintOrigin::PageContent,
            bounds: DeviceRect {
                x: 0,
                y: 0,
                width,
                height,
            },
            clip: None,
            clip_has_mask: false,
            inv: Matrix::IDENTITY,
            width,
            height,
            bpc: 8,
            color_space,
            decode: None,
            samples: Arc::from(samples),
            sample_lut,
            smask: None,
            mask,
            interpolation: InterpolationMode::Nearest,
            footprint: [1.0, 1.0],
            is_stencil: false,
            stencil_rgb: [0, 0, 0],
            alpha: 255,
            blend: BlendMode::Normal,
        }
    }

    /// A 1-bit stencil `/Mask` payload of `width x height` from packed bytes.
    fn stencil(width: u32, height: u32, samples: Vec<u8>, decode: Option<[f32; 2]>) -> ImageMask {
        ImageMask::Stencil(Arc::new(ImageSMask {
            width,
            height,
            bits_per_component: 1,
            decode: decode.map(|d| Arc::from(vec![d])),
            samples: Arc::from(samples),
            codec: None,
            codec_data: None,
            codec_parms: None,
        }))
    }

    /// `cmyk_source_as_rgb8` (direct byte table, per-channel `/Decode` tables)
    /// yields, for every texel, exactly the RGB `pixel()` computes through
    /// the f32 path. The texels cover all 256 values on every channel.
    #[test]
    fn cmyk_rgb8_conversion_matches_pixel_with_and_without_decode() {
        let (w, h) = (64u32, 64u32);
        let mut samples = Vec::new();
        let mut x = 0x2545_F491_4F6C_DD1Du64;
        for i in 0..(w * h) {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            let r = x.to_le_bytes();
            // Texel i walks every byte value on one channel at a time and is
            // pseudo-random on the others.
            let v = (i % 256) as u8;
            let px = match i / 256 % 4 {
                0 => [v, r[1], r[2], r[3]],
                1 => [r[0], v, r[2], r[3]],
                2 => [r[0], r[1], v, r[3]],
                _ => [r[0], r[1], r[2], v],
            };
            samples.extend_from_slice(&px);
        }
        let decodes: [Option<Vec<[f32; 2]>>; 4] = [
            None,
            Some(vec![[1.0, 0.0]; 4]),
            Some(vec![[0.1, 0.9], [0.0, 2.0], [-1.0, 1.0], [0.5, 0.5]]),
            Some(vec![[0.0, 1.0]; 4]),
        ];
        for decode in decodes {
            let mut image = img(w, h, ImageColorSpace::Cmyk, samples.clone(), None);
            image.decode = decode.map(Arc::from);
            let rgb = image.cmyk_source_as_rgb8().expect("convertible");
            for row in 0..h {
                for col in 0..w {
                    let want = image.pixel(col, row).unwrap();
                    let o = (row * w + col) as usize * 3;
                    assert_eq!(
                        &rgb[o..o + 3],
                        &want[..3],
                        "({col},{row}) decode {:?}",
                        image.decode
                    );
                }
            }
        }
    }

    /// 16-bit DeviceGray / DeviceRGB / DeviceCMYK images promote to RGB8 and
    /// every promoted texel equals what the generic loop's `pixel()` yields on
    /// the 16-bit source (with and without `/Decode`). 8-bit members of the
    /// family are not claimed by the generic promotion.
    #[test]
    fn sixteen_bit_device_images_promote_exactly() {
        let (w, h) = (24u32, 20u32);
        let mut x = 0x1234_5678_9ABC_DEF1u64;
        let mut next = move || {
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            x
        };
        for (space, comps) in [
            (ImageColorSpace::Gray, 1usize),
            (ImageColorSpace::Rgb, 3),
            (ImageColorSpace::Cmyk, 4),
        ] {
            let mut samples = Vec::new();
            for _ in 0..(w * h) as usize * comps {
                let v = (next() >> 16) as u16;
                samples.extend_from_slice(&v.to_be_bytes());
            }
            // Pin the extremes so 0 and 65535 are exercised.
            samples[..2].copy_from_slice(&0u16.to_be_bytes());
            samples[2..4].copy_from_slice(&u16::MAX.to_be_bytes());
            let decodes: [Option<Vec<[f32; 2]>>; 3] = [
                None,
                Some(vec![[1.0, 0.0]; comps]),
                Some(vec![[0.2, 0.7]; comps]),
            ];
            for decode in decodes {
                let mut image = img(w, h, space.clone(), samples.clone(), None);
                image.bpc = 16;
                image.sample_lut = None;
                image.decode = decode.map(Arc::from);
                assert!(image.generic_promotion_eligible(), "{space:?}");
                let promoted = image.generic_promoted_to_rgb8().expect("promotes");
                assert_eq!(promoted.bpc, 8);
                for row in 0..h {
                    for col in 0..w {
                        let want = image.pixel(col, row).unwrap();
                        let got = promoted.pixel(col, row).unwrap();
                        assert_eq!(
                            got[..3],
                            want[..3],
                            "{space:?} ({col},{row}) {:?}",
                            image.decode
                        );
                    }
                }
                // The same family at 8 bits keeps its dedicated paths.
                let mut eight = image.clone();
                eight.bpc = 8;
                assert!(!eight.generic_promotion_eligible());
            }
        }
    }

    // 2x1 RGB: left texel red, right texel blue.
    fn rgb_2x1() -> Vec<u8> {
        vec![255, 0, 0, 0, 0, 255]
    }

    #[test]
    fn color_key_hides_in_range_texel_paints_out_of_range() {
        // Key exactly the red texel's raw samples (255, 0, 0).
        let mask = ImageMask::ColorKey(Arc::from(vec![[255, 255], [0, 0], [0, 0]]));
        let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
        // Left (red) is in range → fully transparent.
        assert_eq!(im.shade(0.25, 0.5), None, "in-range texel is masked out");
        // Right (blue) is out of range → paints opaque blue.
        let blue = im.shade(0.75, 0.5).expect("out-of-range texel paints");
        assert_eq!(&blue[0..3], &[0, 0, 255]);
        assert_eq!(blue[3], 255);
    }

    #[test]
    fn color_key_all_components_must_match() {
        // Range covers red's R and G but not its B (B must be in [10,20], is 0).
        let mask = ImageMask::ColorKey(Arc::from(vec![[255, 255], [0, 0], [10, 20]]));
        let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
        // Not every component in range → NOT masked; red paints.
        let red = im.shade(0.25, 0.5).expect("partial match does not mask");
        assert_eq!(&red[0..3], &[255, 0, 0]);
    }

    #[test]
    fn malformed_color_key_is_ignored() {
        // Two ranges for a 3-component image: the sampler must ignore it.
        let mask = ImageMask::ColorKey(Arc::from(vec![[0, 255], [0, 255]]));
        let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
        let red = im
            .shade(0.25, 0.5)
            .expect("malformed mask ignored, texel paints");
        assert_eq!(&red[0..3], &[255, 0, 0]);
    }

    #[test]
    fn stencil_one_masks_zero_paints() {
        // 2x1 stencil: left bit 1 (masked), right bit 0 (paint) → 0b1000_0000.
        let mask = stencil(2, 1, vec![0x80], None);
        let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
        assert_eq!(im.shade(0.25, 0.5), None, "mask sample 1 → transparent");
        let blue = im.shade(0.75, 0.5).expect("mask sample 0 → paints");
        assert_eq!(&blue[0..3], &[0, 0, 255]);
    }

    #[test]
    fn minified_stencil_averages_coverage() {
        // One red texel drawn into one device pixel, cut out by an 8x1
        // stencil whose first three bits hide: a point sample would paint
        // all or nothing, coverage averaging paints 5/8 of it.
        let mask = stencil(8, 1, vec![0b1110_0000], None);
        let im = img(1, 1, ImageColorSpace::Rgb, vec![255, 0, 0], Some(mask));
        let cov = im.minified_stencil_as_coverage().expect("mask minifies 8x");
        assert!(cov.mask.is_none() && cov.smask.is_some());
        let px = cov.shade(0.5, 0.5).expect("partly covered pixel paints");
        assert_eq!(&px[0..3], &[255, 0, 0]);
        assert!((px[3] as i32 - 159).abs() <= 1, "alpha {} != 5/8", px[3]);

        // `/Decode [1 0]`: the three set bits now paint.
        let mask = stencil(8, 1, vec![0b1110_0000], Some([1.0, 0.0]));
        let im = img(1, 1, ImageColorSpace::Rgb, vec![255, 0, 0], Some(mask));
        let px = im
            .minified_stencil_as_coverage()
            .unwrap()
            .shade(0.5, 0.5)
            .unwrap();
        assert!((px[3] as i32 - 96).abs() <= 1, "alpha {} != 3/8", px[3]);

        // Not minified (one mask texel per device pixel): left alone.
        // (The helper maps the whole unit square onto one device pixel.)
        let mask = stencil(1, 1, vec![0x80], None);
        let im = img(1, 1, ImageColorSpace::Rgb, vec![255, 0, 0], Some(mask));
        assert!(im.minified_stencil_as_coverage().is_none());
    }

    #[test]
    fn stencil_decode_inverts_polarity() {
        // Same bits, but /Decode [1 0] swaps: bit 1 → paint, bit 0 → masked.
        let mask = stencil(2, 1, vec![0x80], Some([1.0, 0.0]));
        let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), Some(mask));
        let red = im
            .shade(0.25, 0.5)
            .expect("inverted: mask sample 1 → paints");
        assert_eq!(&red[0..3], &[255, 0, 0]);
        assert_eq!(
            im.shade(0.75, 0.5),
            None,
            "inverted: mask sample 0 → transparent"
        );
    }

    /// The generic bilinear sampler keeps an opaque image opaque: its f32
    /// tap weights can sum to just under one (the guard below finds such a
    /// point), which used to truncate the alpha to 254.
    #[test]
    fn bilinear_keeps_an_opaque_image_opaque() {
        let samples: Vec<u8> = (0..4 * 3 * 3).map(|i| (i * 37 % 256) as u8).collect();
        let im = img(4, 3, ImageColorSpace::Rgb, samples, None);
        let mut short_of_one = 0;
        for i in 0..400 {
            for j in 0..300 {
                let (fx, fy) = (i as f64 / 133.0, j as f64 / 151.0);
                let (tx, ty) = ((fx - fx.floor()) as f32, (fy - fy.floor()) as f32);
                let top = 255.0 * (1.0 - tx) + 255.0 * tx;
                if ((top * (1.0 - ty) + top * ty) as u8) < 255 {
                    short_of_one += 1;
                }
                assert_eq!(im.bilinear(fx, fy).unwrap()[3], 255, "at ({fx}, {fy})");
            }
        }
        assert!(short_of_one > 0, "the f32 blend never fell short of one");
    }

    #[test]
    fn no_mask_paints_normally() {
        let im = img(2, 1, ImageColorSpace::Rgb, rgb_2x1(), None);
        assert!(im.shade(0.25, 0.5).is_some());
        assert!(im.shade(0.75, 0.5).is_some());
    }

    #[test]
    fn prepared_quad_overlap_matches_full_polygon_clipping() {
        let footprints = [
            [[0.2, 0.3], [2.8, 0.6], [3.4, 2.1], [0.7, 1.8]],
            // Clockwise input exercises orientation-independent half planes.
            [[0.7, 1.8], [3.4, 2.1], [2.8, 0.6], [0.2, 0.3]],
            // Entirely contained by one texel.
            [[1.2, 1.2], [1.7, 1.3], [1.6, 1.8], [1.1, 1.7]],
            // Axis-aligned edges and source-boundary crossings.
            [[-0.25, 0.25], [2.25, 0.25], [2.25, 1.75], [-0.25, 1.75]],
        ];

        for vertices in footprints {
            let prepared = ConvexQuad::new(vertices).expect("non-degenerate footprint");
            for y in -2..5 {
                for x in -2..6 {
                    let x0 = f64::from(x);
                    let y0 = f64::from(y);
                    let fast = prepared.rect_overlap_area(x0, x0 + 1.0, y0, y0 + 1.0);
                    let clipped =
                        polygon_rect_overlap_area_clipped(&vertices, x0, x0 + 1.0, y0, y0 + 1.0);
                    assert!(
                        (fast - clipped).abs() <= 1e-12,
                        "footprint={vertices:?} texel=({x},{y}) fast={fast} clipped={clipped}"
                    );
                }
            }
        }
    }

    #[test]
    fn sheared_minification_uses_the_parallelogram_not_its_bounding_box() {
        // One mapped device pixel is a slanted strip of area 2:
        //
        //   (0.5,1.5)──(2.5,1.5)
        //       ╲             ╲
        //        (1.5,2.5)──(3.5,2.5)
        //
        // It overlaps source-row texels 1/2/3 with weights .5/1/.5. Only the
        // middle texel is white, so the exact result is half white (128).
        // The old 3×1 bounding box weighted all three equally and returned 85.
        let mut samples = vec![0u8; 5 * 5 * 3];
        let white = (2 * 5 + 2) * 3;
        samples[white..white + 3].fill(255);
        let mut im = img(5, 5, ImageColorSpace::Rgb, samples, None);
        im.inv = Matrix {
            a: 0.4,
            b: 0.0,
            c: 0.2,
            d: -0.2,
            e: 0.0,
            f: 0.0,
        };
        im.footprint = [3.0, 1.0];

        let (rgba, taps) = im.area_average(2.0, 2.0).expect("covered texels");
        assert_eq!(rgba, [128, 128, 128, 255]);
        assert_eq!(taps, 3);
    }

    #[test]
    fn sheared_stencil_minification_averages_exact_coverage() {
        // Same .5/1/.5 strip as above. Stencil sample 0 paints and 1 is
        // transparent, so only the middle texel contributes: 1 / 2 coverage.
        let mut im = img(5, 5, ImageColorSpace::Gray, vec![0; 25], None);
        im.inv = Matrix {
            a: 0.4,
            b: 0.0,
            c: 0.2,
            d: -0.2,
            e: 0.0,
            f: 0.0,
        };
        im.footprint = [3.0, 1.0];
        im.bpc = 1;
        im.is_stencil = true;
        im.samples = Arc::from(vec![0xf8, 0xf8, 0xd8, 0xf8, 0xf8]);
        im.sample_lut = None;
        im.stencil_rgb = [10, 20, 30];

        let (rgba, taps) = im.area_average(2.0, 2.0).expect("covered texels");
        assert_eq!(rgba, [10, 20, 30, 128]);
        assert_eq!(taps, 3);
    }

    #[test]
    fn axis_box_taps_weight_edge_texels_by_overlap() {
        // Footprint [0.5, 2.5] over a 4-texel axis: half of texel 0, all of
        // texel 1, half of texel 2.
        let t = axis_box_taps(1.0, 1.0, 4).unwrap();
        assert_eq!((t.lo, t.hi), (0, 2));
        assert_eq!(t.w_lo, AXIS_TAP_SCALE / 2);
        assert_eq!(t.w_hi, AXIS_TAP_SCALE / 2);
        assert_eq!(t.total, 2 * AXIS_TAP_SCALE);
        assert_eq!(t.weight_at(1), AXIS_TAP_SCALE);
    }

    #[test]
    fn axis_box_taps_clip_to_the_image_and_renormalize() {
        // Footprint [-0.5, 1.5] clips to [0, 1.5]: texel 0 whole + half of 1.
        let t = axis_box_taps(0.0, 1.0, 4).unwrap();
        assert_eq!((t.lo, t.hi), (0, 1));
        assert_eq!(t.w_lo, AXIS_TAP_SCALE);
        assert_eq!(t.w_hi, AXIS_TAP_SCALE / 2);
        assert_eq!(t.total, AXIS_TAP_SCALE + AXIS_TAP_SCALE / 2);
    }

    #[test]
    fn area_average_weights_partial_edge_texels() {
        // 3×1 gray [0, 255, 0], footprint 2: the box [0.5, 2.5] takes half of
        // each dark edge texel → (255·1)/(0.5+1+0.5) = 127.5 → 128. Uniform
        // whole-texel counting (the old weighting) would say 255/3 = 85.
        let mut im = img(3, 1, ImageColorSpace::Gray, vec![0, 255, 0], None);
        im.footprint = [2.0, 1.0];
        assert_eq!(im.shade(0.5, 0.5), Some([128, 128, 128, 255]));
    }

    #[test]
    fn one_bit_minified_average_weights_edges_fractionally() {
        // Same geometry through the packed-bit LUT path: bits [0, 1, 0].
        let color_space = ImageColorSpace::Gray;
        let mut im = img(3, 1, color_space.clone(), vec![0b0100_0000], None);
        im.bpc = 1;
        im.sample_lut = build_sample_lut(1, &color_space, None, false);
        im.footprint = [2.0, 1.0];
        assert_eq!(im.shade(0.5, 0.5), Some([128, 128, 128, 255]));
    }

    #[test]
    fn minified_bilevel_soft_mask_averages_coverage_and_applies_decode() {
        // Bits [1, 0, 0], sampled at the middle texel with a two-texel
        // footprint: half of bit 1 plus all of bit 0 plus half of bit 0 gives
        // raw coverage 0.25. `/Decode [1 0]` inverts that to alpha 0.75.
        // Nearest sampling would read the middle zero and incorrectly return
        // fully opaque alpha 1.0.
        let sm = ImageSMask {
            width: 3,
            height: 1,
            bits_per_component: 1,
            decode: Some(Arc::from(vec![[1.0, 0.0]])),
            samples: Arc::from(vec![0b1000_0000]),
            codec: None,
            codec_data: None,
            codec_parms: None,
        };
        let filtered = sample_smask(&sm, 0.5, 0.5, [2.0, 1.0]);
        let nearest = sample_smask(&sm, 0.5, 0.5, [1.0, 1.0]);
        assert!((filtered - 0.75).abs() < 1e-6, "{filtered}");
        assert_eq!(nearest, 1.0);
    }

    #[test]
    fn one_bit_range_count_handles_partial_and_full_bytes() {
        let data = [0b1011_0010, 0b1110_0001, 0b0101_0101];
        for start in 0..24 {
            for len in 0..=24 - start {
                let expected = (start..start + len)
                    .map(|bit| ((data[bit / 8] >> (7 - bit % 8)) & 1) as u32)
                    .sum();
                assert_eq!(
                    count_one_bits(&data, start, len),
                    expected,
                    "start={start} len={len}"
                );
            }
        }
    }
}