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
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
//! The region executor: walk a [`CpuPreparedPage`]'s compact commands in
//! painter order and paint them into a [`Surface`] via span dispatch.
//!
//! Per command: apply the clip (rectangular envelope by arithmetic, non-rect
//! clips by a lazily-built `Alpha8` mask), generate analytic coverage, then
//! for each contiguous span pick a kernel **once** — opaque full spans
//! overwrite, partial-alpha full spans use the constant-alpha blend, and
//! anti-aliased/masked runs use the per-pixel mask blend (advice §4, §5, §8).
//! No allocation, `Arc` indexing, or transform work happens here.

#[cfg(feature = "profiling")]
use std::time::Instant;

use crate::render_cpu::kernels::{
    BlendFn, KernelSet, NonSepBlendFn, blend_span, blend_span_nonsep, composite_px, mul_div_255,
    nonseparable_blend, separable_blend,
};

/// The blend path chosen once per command (never per pixel).
#[derive(Clone, Copy)]
enum BlendChoice {
    Normal,
    Separable(BlendFn),
    NonSeparable(NonSepBlendFn),
}

fn choose_blend(mode: crate::page_ir::BlendMode) -> BlendChoice {
    if let Some(f) = separable_blend(mode) {
        BlendChoice::Separable(f)
    } else if let Some(f) = nonseparable_blend(mode) {
        BlendChoice::NonSeparable(f)
    } else {
        BlendChoice::Normal
    }
}
use crate::page_ir::DeviceRect;
use crate::render_cpu::mask::{ClipGeom, ClipMask, build_clip_mask_cancellable};

use crate::render_cpu::prepared::{
    CpuPreparedPage, DrawClass, PreparedCommand, PreparedGlyphRun, PreparedOp,
};
use crate::render_cpu::raster::{CovRun, RasterKernel};
use crate::render_cpu::stats::RenderStats;
use crate::render_cpu::surface::{Surface, unique_arc_mut, zeroed_arc};
use rayon::prelude::*;

/// Per-worker scratch: the coverage kernel and the kernel-set table. Reusable
/// geometry buffers live on the prepared page and the kernel; nothing here
/// allocates per command after warm-up (advice §13).
#[derive(Debug)]
pub struct CpuWorkerContext {
    raster: RasterKernel,
    kernels: KernelSet,
    pub(crate) fonts: crate::render_cpu::prepared::FontProgramCache,
    /// The previous render's page buffer, kept so the next render of the same
    /// geometry repaints resident memory instead of faulting in a fresh
    /// mapping. At most one buffer, always the most recent page's size, and
    /// only ever handed back out when its consumer has dropped it — so this
    /// retains no more than the one page surface the worker was already sized
    /// for, and nothing at all until a page has been rendered.
    pub(crate) surface_buffer: Option<std::sync::Arc<[u8]>>,
}

impl Default for CpuWorkerContext {
    fn default() -> Self {
        Self {
            raster: RasterKernel::default(),
            kernels: KernelSet::select(),
            fonts: crate::render_cpu::prepared::FontProgramCache::default(),
            surface_buffer: None,
        }
    }
}

impl CpuWorkerContext {
    pub fn new() -> Self {
        Self::default()
    }

    /// Choose how much timing profiled renders on this worker collect (see
    /// [`crate::profiling::ProfileDetail`]). Counters are unaffected.
    #[cfg(feature = "profiling")]
    pub fn set_profile_detail(&mut self, detail: crate::profiling::ProfileDetail) {
        use crate::profiling::ProfileDetail;
        self.raster.prof.time_fills = matches!(detail, ProfileDetail::Fill | ProfileDetail::Row);
        self.raster.prof.time_rows = matches!(detail, ProfileDetail::Row);
    }
}

/// Execute a page into `surface`, rendering transparency groups into bounded
/// offscreen surfaces that composite back (advice §9).
pub fn execute(
    page: &CpuPreparedPage,
    surface: &mut Surface,
    ctx: &mut CpuWorkerContext,
    stats: &mut RenderStats,
) {
    #[cfg(feature = "profiling")]
    let start = Instant::now();
    let _in_flight = PageInFlight::enter();
    let CpuWorkerContext {
        raster, kernels, ..
    } = ctx;
    // Region-local clip masks, built once per page and indexed by dense
    // ClipId (advice §8 — no hash map in the draw loop).
    let mut masks: Vec<Option<ClipMask>> = (0..page.clips.len()).map(|_| None).collect();
    #[cfg(feature = "profiling")]
    let mut lap = crate::profiling::Lap::start();
    #[cfg(feature = "profiling")]
    {
        stats.hot.time_nested = raster.prof.time_fills;
    }
    // Clip-dense pages (basin maps, music notation) spend nearly all their time
    // rasterizing hundreds of large independent path-clip masks. Each mask is a
    // pure function of the page and is byte-identical regardless of build order,
    // so pre-build every consumed mask across the rayon pool before the serial
    // draw loop. The draw loop then finds them cached. Peak memory is unchanged
    // (every consumed mask is cached by page end anyway); this only front-loads
    // and parallelizes the build.
    prebuild_masks(
        page,
        &mut masks,
        #[cfg(feature = "profiling")]
        &mut raster.prof,
    );
    #[cfg(feature = "profiling")]
    {
        stats.hot.ns_prebuild_masks += lap.lap_ns();
        stats.hot.n_clip_mask_prebuilt += masks.iter().flatten().count() as u64;
        stats.hot.clip_mask_bytes += masks
            .iter()
            .flatten()
            .map(|mask| mask.data.len() as u64)
            .sum::<u64>();
    }
    // Active soft masks (top = current); `None` entry = /SMask /None.
    let mut soft: Vec<Option<ClipMask>> = Vec::new();
    run_ops(
        page,
        0,
        page.ops.len(),
        surface,
        raster,
        kernels,
        &mut masks,
        &mut soft,
        stats,
    );
    #[cfg(feature = "profiling")]
    {
        stats.hot.ns_run_ops += lap.lap_ns();
        stats.hot.clock_reads += 3;
        stats.hot.flush_into(&mut stats.profile);
        raster.prof.drain_into(&mut stats.profile);
        stats.raster += start.elapsed();
    }
}

/// Derive every top-level page soft mask once for the experimental image-page
/// preparation seam. Mask content still runs through the normative CPU
/// executor, including nested masks, groups, clips, `/BC`, and `/TR`; callers
/// can then attach the resulting device-space coverage plane to GPU image
/// draws without teaching the GPU backend how to paint arbitrary mask content.
///
/// The returned vector is indexed like `page.ops`; only `PushSoftMask` slots
/// are populated. `None` for the whole result means cooperative cancellation.
pub(crate) fn prepare_soft_masks(page: &CpuPreparedPage) -> Option<Vec<Option<ClipMask>>> {
    let mut prepared: Vec<Option<ClipMask>> = std::iter::repeat_with(|| None)
        .take(page.ops.len())
        .collect();
    let mut raster = RasterKernel::default();
    let kernels = KernelSet::select();
    let mut masks: Vec<Option<ClipMask>> = (0..page.clips.len()).map(|_| None).collect();
    let mut stats = RenderStats::default();
    let mut i = 0;

    while i < page.ops.len() {
        if let Some(cancel) = &page.decode_limits.should_cancel
            && cancel()
        {
            return None;
        }
        match &page.ops[i] {
            PreparedOp::PushSoftMask {
                kind,
                transfer,
                content_end,
                bounds,
            } => {
                let content_end = *content_end as usize;
                prepared[i] = Some(render_soft_mask(
                    page,
                    i + 1,
                    content_end,
                    *kind,
                    transfer.as_deref(),
                    *bounds,
                    &mut raster,
                    &kernels,
                    &mut masks,
                    &mut stats,
                ));
                if stats.cancelled {
                    return None;
                }
                i = content_end;
            }
            _ => i += 1,
        }
    }

    Some(prepared)
}

/// Rasterize one patterned `/ImageMask` brush without its page-level alpha or
/// blend. The resulting bounded plane is straight RGB plus independent alpha,
/// ready for the experimental GPU image compositor to apply painter-order
/// state. `None` means cancellation or a degraded nested pattern-cell draw;
/// callers then route the complete request through the normative CPU backend
/// so diagnostics cannot disappear at the GPU seam.
pub(crate) fn prepare_patterned_stencil(
    page: &CpuPreparedPage,
    tiling: &crate::render_cpu::prepared::PreparedTiling,
) -> Option<crate::render_cpu::PreparedPatternedStencil> {
    tiling.stencil.as_ref()?;
    let mut normalized = tiling.clone();
    normalized.alpha = 255;
    normalized.blend = crate::page_ir::BlendMode::Normal;

    let mut surface = Surface::offscreen(normalized.bounds);
    let mut raster = RasterKernel::default();
    let kernels = KernelSet::select();
    let mut masks: Vec<Option<ClipMask>> = (0..page.clips.len()).map(|_| None).collect();
    let mut stats = RenderStats::default();
    render_tiling(
        page,
        &normalized,
        &mut surface,
        &mut raster,
        &kernels,
        &mut masks,
        &mut stats,
    );
    if stats.cancelled || stats.degraded_draws > 0 {
        return None;
    }

    let (_, rgba) = surface.into_output(crate::render_api::OutputFormat::Rgba8PremultipliedSrgb);
    let pixels = normalized.bounds.width as usize * normalized.bounds.height as usize;
    let mut samples = zeroed_arc(pixels * 3);
    let mut opacity = zeroed_arc(pixels);
    let samples_data = unique_arc_mut(&mut samples);
    let opacity_data = unique_arc_mut(&mut opacity);
    for (index, pixel) in rgba.chunks_exact(4).enumerate() {
        let alpha = u16::from(pixel[3]);
        opacity_data[index] = pixel[3];
        let sample = &mut samples_data[index * 3..index * 3 + 3];
        if alpha == 0 {
            sample.fill(0);
        } else {
            for (dst, &channel) in sample.iter_mut().zip(&pixel[..3]) {
                *dst = ((u16::from(channel) * 255 + alpha / 2) / alpha).min(255) as u8;
            }
        }
    }
    Some(crate::render_cpu::PreparedPatternedStencil {
        bounds: normalized.bounds,
        samples,
        opacity,
    })
}

/// Pre-build every clip mask the ops will consume, across the rayon pool, so the
/// serial draw loop finds them cached. Each mask is a pure function of `page`
/// and byte-identical regardless of build order, so this is safe to parallelize
/// and never changes output. Engaged only past a threshold where the fan-out
/// pays for itself; below it the draw loop builds the few masks lazily.
fn prebuild_masks(
    page: &CpuPreparedPage,
    masks: &mut [Option<ClipMask>],
    #[cfg(feature = "profiling")] prof: &mut crate::render_cpu::raster::RasterProf,
) {
    // Cooperative cancellation: skip the (bounded) pre-pass if already cancelled.
    if let Some(cancel) = &page.decode_limits.should_cancel
        && cancel()
    {
        return;
    }
    // The distinct mask-source clips actually drawn under (a mask pushed but
    // never consumed is never built — matching the lazy loop's behavior).
    let mut wanted = vec![false; page.clips.len()];
    for op in &page.ops {
        let clip = match op {
            PreparedOp::Draw(c) if c.clip_has_mask => c.clip,
            PreparedOp::GlyphRun(g) if g.clip_has_mask => g.clip,
            PreparedOp::Image(i) if i.clip_has_mask => i.clip,
            PreparedOp::TiledFill(t) if t.clip_has_mask => t.clip,
            _ => None,
        };
        if let Some(cid) = clip
            && let Some(src) = page.clips[cid as usize].mask_source
        {
            wanted[src as usize] = true;
        }
    }
    let ids: Vec<u32> = (0..page.clips.len() as u32)
        .filter(|&i| wanted[i as usize])
        .collect();
    // Below this count, rayon fan-out costs more than it saves.
    const PARALLEL_MASK_THRESHOLD: usize = 16;
    if ids.len() < PARALLEL_MASK_THRESHOLD {
        return;
    }
    // One reused scratch kernel per worker thread (grows on first fill).
    let geom = ClipGeom::of(page);
    let should_cancel = page.decode_limits.should_cancel.as_deref();
    #[cfg(feature = "profiling")]
    {
        // Each rayon worker's kernel carries its own attribution; hand it back
        // with the mask and merge serially (summed CPU time, not wall time).
        let built: Vec<(u32, Option<ClipMask>, crate::render_cpu::raster::RasterProf)> = ids
            .par_iter()
            .map_init(RasterKernel::default, |rk, &cid| {
                rk.prof.class = crate::render_cpu::raster::RasterClass::Clip;
                let mask = build_clip_mask_cancellable(rk, geom, cid, should_cancel);
                (cid, mask, std::mem::take(&mut rk.prof))
            })
            .collect();
        for (cid, mask, worker_prof) in built {
            prof.merge(&worker_prof);
            if let Some(mask) = mask {
                masks[cid as usize] = Some(mask);
            }
        }
    }
    #[cfg(not(feature = "profiling"))]
    {
        let built: Vec<(u32, ClipMask)> = ids
            .par_iter()
            .map_init(RasterKernel::default, |rk, &cid| {
                build_clip_mask_cancellable(rk, geom, cid, should_cancel).map(|mask| (cid, mask))
            })
            .filter_map(|built| built)
            .collect();
        for (cid, m) in built {
            masks[cid as usize] = Some(m);
        }
    }
}

/// Execute ops `[start, end)` into `surface`. `BeginGroup` recurses into a
/// fresh offscreen surface and composites back; `PushSoftMask` renders its
/// content offscreen, derives a per-pixel mask, and pushes it.
#[allow(clippy::too_many_arguments)]
fn run_ops(
    page: &CpuPreparedPage,
    start: usize,
    end: usize,
    surface: &mut Surface,
    raster: &mut RasterKernel,
    kernels: &KernelSet,
    masks: &mut Vec<Option<ClipMask>>,
    soft: &mut Vec<Option<ClipMask>>,
    stats: &mut RenderStats,
) {
    let mut i = start;
    while i < end {
        // Cooperative mid-render cancellation (roadmap §4.4): checked at op
        // boundaries every 16 commands, so a cancelled viewer request stops
        // within a bounded slice of work instead of at page completion.
        if i.trailing_zeros() >= 4
            && let Some(cancel) = &page.decode_limits.should_cancel
            && cancel()
        {
            stats.cancelled = true;
            return;
        }
        match &page.ops[i] {
            PreparedOp::Draw(cmd) => {
                let active_soft = soft.last().and_then(Option::as_ref);
                paint_command(
                    page,
                    cmd,
                    surface,
                    raster,
                    kernels,
                    masks,
                    active_soft,
                    stats,
                );
                i += 1;
            }
            PreparedOp::GlyphRun(gr) => {
                let active_soft = soft.last().and_then(Option::as_ref);
                paint_glyph_run(
                    page,
                    gr,
                    surface,
                    raster,
                    kernels,
                    masks,
                    active_soft,
                    stats,
                );
                i += 1;
            }
            PreparedOp::TiledFill(t) => {
                #[cfg(feature = "profiling")]
                let tiling_start = Instant::now();
                render_tiling(page, t, surface, raster, kernels, masks, stats);
                #[cfg(feature = "profiling")]
                {
                    stats.hot.ns_tiling += tiling_start.elapsed().as_nanos() as u64;
                    stats.hot.n_tiling_fills += 1;
                    stats.hot.clock_reads += 2;
                }
                i += 1;
            }
            PreparedOp::Image(img) => {
                let active_soft = soft.last().and_then(Option::as_ref);
                paint_image(page, img, surface, raster, masks, active_soft, stats);
                i += 1;
            }
            PreparedOp::BeginGroup {
                group,
                end: group_end,
            } => {
                let ge = *group_end as usize;
                if group.bounds.width == 0 || group.bounds.height == 0 {
                    i = ge + 1;
                    continue;
                }
                // Group backdrop (ISO 32000-1 §11.4.7): an *isolated* group
                // starts transparent; a *non-isolated* group's elements
                // composite against the backdrop behind it. We seed the
                // backdrop only for a non-isolated group whose own composite
                // blend is Normal (the common wrapper case) — there the
                // seeded offscreen is composited back by a plain replace/lerp,
                // which is exact for an opaque backdrop and cannot double-count
                // it. A non-isolated group with a *non-Normal* composite blend
                // (e.g. a Multiply group) is still rendered on a transparent
                // offscreen (its content isolated) and composited with that
                // blend against the parent — which, when the parent is the page
                // or an already-seeded non-isolated wrapper, now holds the real
                // backdrop, so `Multiply` finally hits the tone underneath
                // instead of transparency (the Young-Turks gold, the Medieval
                // page tone). This is Stage 1: full non-isolated compositing
                // with backdrop removal for a non-Normal group whose *content*
                // carries its own non-Normal blends remains approximated.
                let blend = choose_blend(group.blend);
                // The soft mask in force at the invocation modulates the
                // *group's* composite, not its contents (§11.6.6 — lowering
                // pushes a None reset inside the group for that reason). Its
                // stack slot is stable across the group's ops, which are
                // balanced, so remember the depth rather than borrowing across
                // the `run_ops` mutable borrow.
                let soft_slot = soft.len().checked_sub(1);
                let seed = !group.isolated && matches!(blend, BlendChoice::Normal);
                let mut off = if seed {
                    Surface::offscreen_seeded(surface, group.bounds)
                } else {
                    Surface::offscreen(group.bounds)
                };
                if group.knockout {
                    run_knockout_group(
                        page,
                        i + 1,
                        ge,
                        &mut off,
                        raster,
                        kernels,
                        masks,
                        soft,
                        stats,
                    );
                } else {
                    run_ops(
                        page,
                        i + 1,
                        ge,
                        &mut off,
                        raster,
                        kernels,
                        masks,
                        soft,
                        stats,
                    );
                }
                let group_soft = soft_slot
                    .and_then(|ix| soft.get(ix))
                    .and_then(Option::as_ref);
                if seed {
                    // Seeded offscreen already holds backdrop∘content; fold it
                    // back at group opacity without re-compositing the backdrop.
                    composite_group_seeded(surface, &off, group.opacity, group_soft);
                } else {
                    composite_group(surface, &off, group.opacity, blend, group_soft);
                }
                stats.transparency_groups += 1;
                i = ge + 1;
            }
            PreparedOp::EndGroup => i += 1,
            PreparedOp::PushSoftMask {
                kind,
                transfer,
                content_end,
                bounds,
            } => {
                let ce = *content_end as usize;
                let mask = render_soft_mask(
                    page,
                    i + 1,
                    ce,
                    *kind,
                    transfer.as_deref(),
                    *bounds,
                    raster,
                    kernels,
                    masks,
                    stats,
                );
                soft.push(Some(mask));
                stats.soft_masks += 1;
                i = ce;
            }
            PreparedOp::PushSoftMaskNone => {
                soft.push(None);
                i += 1;
            }
            PreparedOp::PopSoftMask => {
                soft.pop();
                i += 1;
            }
        }
        if stats.cancelled {
            return;
        }
    }
}

#[allow(clippy::too_many_arguments)]
fn render_soft_mask(
    page: &CpuPreparedPage,
    content_start: usize,
    content_end: usize,
    kind: crate::page_ir::MaskKind,
    transfer: Option<&[u8; 256]>,
    bounds: DeviceRect,
    raster: &mut RasterKernel,
    kernels: &KernelSet,
    masks: &mut Vec<Option<ClipMask>>,
    stats: &mut RenderStats,
) -> ClipMask {
    if bounds.width == 0 || bounds.height == 0 {
        // An empty real mask is not `/SMask /None`: its outside value still
        // gates every subsequent pixel. Keeping an explicit zero-sized mask
        // also fixes the formerly inverted Alpha/plain-Luminosity empty-mask
        // case, where `None` accidentally disabled masking altogether.
        return ClipMask {
            bounds,
            data: Vec::new(),
            outside: apply_transfer(soft_mask_outside(kind), transfer),
            all_opaque: false,
        };
    }

    let mut off = Surface::offscreen(bounds);
    // A /BC luminosity mask composites its content against the backdrop color,
    // not transparent black (§11.6.5.2).
    if let crate::page_ir::MaskKind::LuminosityBc { backdrop } = kind {
        for ly in 0..off.height {
            let row = off.row_mut(off.origin_y + ly);
            for px in row.chunks_exact_mut(4) {
                px[0] = backdrop[0];
                px[1] = backdrop[1];
                px[2] = backdrop[2];
                px[3] = 255;
            }
        }
    }
    // The mask content renders isolated from any outer soft mask.
    let mut inner: Vec<Option<ClipMask>> = Vec::new();
    run_ops(
        page,
        content_start,
        content_end,
        &mut off,
        raster,
        kernels,
        masks,
        &mut inner,
        stats,
    );
    derive_soft_mask(&off, kind, transfer)
}

fn build_render_clip_mask(
    page: &CpuPreparedPage,
    raster: &mut RasterKernel,
    cid: u32,
    stats: &mut RenderStats,
) -> Option<ClipMask> {
    #[cfg(feature = "profiling")]
    let caller_class =
        std::mem::replace(&mut raster.prof.class, crate::render_cpu::raster::RasterClass::Clip);
    let mask = build_clip_mask_cancellable(
        raster,
        ClipGeom::of(page),
        cid,
        page.decode_limits.should_cancel.as_deref(),
    );
    #[cfg(feature = "profiling")]
    {
        raster.prof.class = caller_class;
    }
    if mask.is_none() {
        stats.cancelled = true;
    }
    mask
}

/// Execute a *knockout* group's ops `[start, end)` into `off` (ISO 32000-1
/// §11.6.6): every painting element composites against the group's **initial**
/// backdrop rather than the accumulated result, later elements replacing
/// earlier ones where they overlap.
///
/// Implementation: `initial` snapshots the offscreen; each top-level element
/// (a draw, or a whole nested group/tiled fill) renders onto a fresh copy of
/// `initial`, and every pixel the element changed is copied into the
/// accumulator (`off`). Diffing against `initial` detects "touched": an
/// element that writes exactly the backdrop value leaves the accumulator
/// unchanged, which is value-identical. Soft-mask push/pop ops are graphics
/// *state*, not elements — they execute once, in order, and stay active for
/// the following elements.
#[allow(clippy::too_many_arguments)]
fn run_knockout_group(
    page: &CpuPreparedPage,
    start: usize,
    end: usize,
    off: &mut Surface,
    raster: &mut RasterKernel,
    kernels: &KernelSet,
    masks: &mut Vec<Option<ClipMask>>,
    soft: &mut Vec<Option<ClipMask>>,
    stats: &mut RenderStats,
) {
    let initial = off.clone();
    let mut scratch = initial.clone();
    let mut scratch_is_initial = true;
    let mut i = start;
    while i < end {
        // One element's op extent, and whether it paints (vs pure state).
        let (next, paints) = match &page.ops[i] {
            PreparedOp::Draw(_)
            | PreparedOp::GlyphRun(_)
            | PreparedOp::TiledFill(_)
            | PreparedOp::Image(_) => (i + 1, true),
            PreparedOp::BeginGroup { end: ge, .. } => (*ge as usize + 1, true),
            PreparedOp::PushSoftMask { content_end, .. } => (*content_end as usize, false),
            PreparedOp::PushSoftMaskNone | PreparedOp::PopSoftMask | PreparedOp::EndGroup => {
                (i + 1, false)
            }
        };
        if paints {
            if !scratch_is_initial {
                scratch.copy_pixels_from(&initial);
            }
            run_ops(
                page,
                i,
                next,
                &mut scratch,
                raster,
                kernels,
                masks,
                soft,
                stats,
            );
            scratch_is_initial = false;
            // Fold changed pixels into the accumulator.
            let (gw, gh) = (off.width, off.height);
            for ly in 0..gh {
                let srow = scratch.local_row(ly);
                let irow = initial.local_row(ly);
                let orow = off.row_mut(initial.origin_y + ly);
                for lx in 0..gw {
                    let r = lx * 4..lx * 4 + 4;
                    if srow[r.clone()] != irow[r.clone()] {
                        orow[r.clone()].copy_from_slice(&srow[r]);
                    }
                }
            }
        } else {
            // State op: execute against the accumulator (it paints nothing).
            run_ops(page, i, next, off, raster, kernels, masks, soft, stats);
        }
        i = next;
    }
}

/// Blit an image: sample every device pixel in its bounds back through the
/// inverse transform, apply the clip + soft mask, and composite — source-over
/// on the fast paths (Normal blend), the general per-pixel compositor for a
/// non-Normal image blend.
#[allow(clippy::too_many_arguments)]
fn paint_image(
    page: &CpuPreparedPage,
    img: &crate::render_cpu::image::PreparedImage,
    surface: &mut Surface,
    raster: &mut RasterKernel,
    masks: &mut [Option<ClipMask>],
    soft: Option<&ClipMask>,
    stats: &mut RenderStats,
) {
    #[cfg(feature = "profiling")]
    let image_start = Instant::now();
    stats.commands += 1;
    // A minified hard stencil is coverage-averaged, as a one-bit soft mask.
    let coverage_masked;
    let img = match img.minified_stencil_as_coverage() {
        Some(promoted) => {
            coverage_masked = promoted;
            &coverage_masked
        }
        None => img,
    };
    let cmask_cid = if img.clip_has_mask {
        // Lowering guarantees a masked draw carries its clip id; a missing id
        // means the IR invariant broke upstream. Skip the draw (never panic a
        // page) and record the degradation.
        let Some(cid) = img.clip else {
            page.diagnostics
                .note_degraded("image draw skipped: masked clip without a clip id".into());
            return;
        };
        // Share the nearest path-clip ancestor's mask across rect descendants.
        let cid = page.clips[cid as usize].mask_source.unwrap_or(cid);
        if masks[cid as usize].is_none() {
            let Some(mask) = build_render_clip_mask(page, raster, cid, stats) else {
                return;
            };
            masks[cid as usize] = Some(mask);
        }
        Some(cid as usize)
    } else {
        None
    };
    let raw_cmask = cmask_cid.and_then(|cid| masks[cid].as_ref());
    // Path clips that rasterize to full coverage over their envelope are
    // semantically rectangular for this draw. Avoid a mask lookup and
    // multiply for every destination pixel once that is proven.
    let opaque_clip_elided = raw_cmask.is_some_and(|cm| cm.all_opaque);
    let cmask = raw_cmask.filter(|_| !opaque_clip_elided);

    let b = img.bounds;
    let (x0, y0) = (b.x as usize, b.y as usize);
    let x1 = (b.x + b.width as i32) as usize;
    let y1 = (b.y + b.height as i32) as usize;
    // Pixels this image actually marks. `covered_pixels` feeds
    // `is_silent_blank()`; an image-only page that DID paint must not be
    // mislabeled a silent blank just because no `SolidPath` ran.
    let mut covered: u64 = 0;
    #[cfg(feature = "profiling")]
    let mut sample_attempts: u64 = 0;
    #[cfg(feature = "profiling")]
    let mut sample_taps: u64 = 0;
    #[cfg(feature = "profiling")]
    let mut fast_cmyk_area_used = false;
    // Non-Normal image blend takes the generic per-pixel path with the
    // general compositor; every fast path below is source-over.
    let blend = choose_blend(img.blend);
    let blend_is_normal = matches!(blend, BlendChoice::Normal);
    // Eight-bit gray sources (book scans, MRC pages) are one byte per texel
    // where every fast path below reads three. Promote the axis-aligned
    // opaque ones to RGB8 once so they qualify; sampling the promoted image
    // is byte-identical (see `PreparedImage::gray8_promoted_to_rgb8`). A
    // magnified draw under a mask has no fast path either way, so it is not
    // expanded for nothing.
    let promoted_gray;
    let img = if blend_is_normal
        && cmask.is_none()
        && soft.is_none()
        && img.alpha == 255
        && img.inv.b == 0.0
        && img.inv.c == 0.0
        && matches!(img.color_space, crate::page_ir::ImageColorSpace::Gray)
        && (img.footprint[0] > 1.0
            || img.footprint[1] > 1.0
            || (img.smask.is_none() && img.mask.is_none()))
    {
        match img.gray8_promoted_to_rgb8() {
            Some(rgb) => {
                promoted_gray = rgb;
                &promoted_gray
            }
            None => img,
        }
    } else {
        img
    };
    // Indexed (palette) sources are one byte (or less) per texel resolved
    // through a palette, which no fast path reads. Expand them to RGB8 once
    // through the palette; sampling the promoted image is byte-identical (see
    // `PreparedImage::indexed_promoted_to_rgb8`), and every path from here on —
    // the axis-aligned fast paths, the masked MRC path, and the generic
    // sampler's RGB8 byte-sum branch — is then open to it. The expansion is
    // one pass over the source; any sampling of the original costs at least a
    // palette resolution per tap, and the taps are never fewer than the texels
    // a draw touches, so it pays for itself on every geometry. A colour-key
    // mask keys on the raw palette indices and keeps the original.
    //
    // Lowering already performs this expansion behind the content-keyed image
    // cache (`prepared.rs::promote_through_cache`), so a lowered image arrives
    // here as RGB8 and only images built elsewhere expand per draw.
    let promoted_indexed;
    let img = if matches!(
        img.color_space,
        crate::page_ir::ImageColorSpace::Indexed { .. }
    ) && !matches!(img.mask, Some(crate::page_ir::ImageMask::ColorKey(_)))
    {
        #[cfg(feature = "profiling")]
        let promote_start = Instant::now();
        let promoted = img.indexed_promoted_to_rgb8();
        #[cfg(feature = "profiling")]
        stats
            .profile
            .add_duration("render.image.indexed_promotion", promote_start.elapsed());
        match promoted {
            Some(rgb) => {
                promoted_indexed = rgb;
                &promoted_indexed
            }
            None => img,
        }
    } else {
        img
    };
    let fast_rgb8_base = blend_is_normal
        && cmask.is_none()
        && soft.is_none()
        && img.alpha == 255
        && img.smask.is_none()
        && img.mask.is_none()
        && !img.is_stencil
        && img.bpc == 8
        && img.decode.is_none()
        && matches!(img.color_space, crate::page_ir::ImageColorSpace::Rgb)
        && img.footprint[0] <= 1.0
        && img.footprint[1] <= 1.0
        && img.inv.b.abs() < 1e-12
        && img.inv.c.abs() < 1e-12
        && img.samples.len() >= img.width as usize * img.height as usize * 3;
    let fast_rgb8 =
        fast_rgb8_base && img.interpolation == crate::page_ir::InterpolationMode::Nearest;
    // Magnified/1:1 continuous-tone JPEG/JPX is forced to Bilinear in
    // prepared.rs; without a dedicated path those draws fall into the generic
    // per-pixel bilinear loop (~tens of Mpix/s). Same axis-aligned eligibility
    // as nearest, with bilinear taps matching `PreparedImage::bilinear`.
    let fast_rgb8_bilinear =
        fast_rgb8_base && img.interpolation == crate::page_ir::InterpolationMode::Bilinear;
    // The low-bit-depth twin of `fast_rgb8`: a 1-, 2- or 4-bit single-component
    // image — the bilevel JBIG2 or CCITT page of a scan, an MRC producer or
    // A preprocessor's own output — drawn axis-aligned at or above its own resolution,
    // sampled through its prepared lookup table. Without it such a draw took
    // the generic per-pixel loop (~30 ns a pixel, 100 ms for a 1474×2400
    // page). Minified draws keep the summed-area `fast_binary` path below.
    let lut_nearest = if blend_is_normal
        && cmask.is_none()
        && soft.is_none()
        && img.alpha == 255
        && img.smask.is_none()
        && img.mask.is_none()
        && img.footprint[0] <= 1.0
        && img.footprint[1] <= 1.0
        && img.inv.b.abs() < 1e-12
        && img.inv.c.abs() < 1e-12
        && img.interpolation == crate::page_ir::InterpolationMode::Nearest
    {
        img.lut_nearest_opaque()
    } else {
        None
    };
    // The area-minified twin of `fast_rgb8`: same eligibility, but the image is
    // minified on at least one axis (footprint > 1), so each destination pixel
    // box-averages its source footprint (what the generic path's
    // `area_average` does) instead of point-sampling. Off-diagonal inverse
    // terms must be *exactly* zero so per-column/row source boxes reproduce the
    // generic per-pixel `inv.apply` bit-for-bit. Interpolation is not checked:
    // minification ignores it (`shade` area-averages regardless of the
    // Nearest/Bilinear hint), so a minified Bilinear draw lands here too.
    let rgb8_area_shape = blend_is_normal
        && cmask.is_none()
        && soft.is_none()
        && img.alpha == 255
        && !img.is_stencil
        && img.bpc == 8
        && img.decode.is_none()
        && matches!(img.color_space, crate::page_ir::ImageColorSpace::Rgb)
        && (img.footprint[0] > 1.0 || img.footprint[1] > 1.0)
        && img.inv.b == 0.0
        && img.inv.c == 0.0
        && img.samples.len() >= img.width as usize * img.height as usize * 3;
    let fast_rgb8_area = rgb8_area_shape && img.smask.is_none() && img.mask.is_none();
    // The MRC shape: the same opaque axis-aligned minified RGB8 source, but cut
    // out by a one-bit JBIG2 layer. Without this the draw falls into the
    // generic per-pixel loop and pays a fresh inverse map, two base tap boxes,
    // and a mask lookup for every destination pixel — all of which depend only
    // on the destination column or row once the placement is axis-aligned.
    let area_min_mask = if rgb8_area_shape {
        area_min_mask(img)
    } else {
        None
    };
    // The same, for an opaque axis-aligned minified CMYK image: the source is
    // converted to RGB8 once and then box-averaged identically. Eligibility
    // mirrors `fast_rgb8_area` but for the CMYK colour space; the sample-length
    // and size checks live in `cmyk_source_as_rgb8`.
    let fast_cmyk_area = blend_is_normal
        && cmask.is_none()
        && soft.is_none()
        && img.alpha == 255
        && img.smask.is_none()
        && img.mask.is_none()
        && !img.is_stencil
        && img.bpc == 8
        && img.decode.is_none()
        && matches!(img.color_space, crate::page_ir::ImageColorSpace::Cmyk)
        && (img.footprint[0] > 1.0 || img.footprint[1] > 1.0)
        && img.inv.b == 0.0
        && img.inv.c == 0.0;
    let fast_binary = blend_is_normal && soft.is_none() && img.is_binary_box_filterable();
    // An `/ImageMask` stencil in solid colour is a one-bit image whose
    // painting bit is opaque and whose masking bit is transparent, so it takes
    // the bilevel box filter when minified and a transparent-skip nearest walk
    // otherwise, on the interior rectangle; the border band stays generic.
    // The placement must be axis-aligned with off-diagonal terms exactly zero
    // (that is what makes the per-axis tables and the interior test reproduce
    // the generic `inv.apply`), and a magnified Bilinear stencil keeps the
    // generic sampler, whose four-tap blend this path does not reproduce.
    let stencil_lut = if blend_is_normal && soft.is_none() {
        stencil_fast_lut(img)
    } else {
        None
    };

    if fast_rgb8 {
        let result = paint_axis_aligned_rgb8_nearest_opaque(img, surface, x0, y0, x1, y1);
        covered = result.0;
        #[cfg(feature = "profiling")]
        {
            sample_attempts = (x1 - x0) as u64 * (y1 - y0) as u64;
            sample_taps = result.1;
        }
    } else if fast_rgb8_bilinear {
        let result = paint_axis_aligned_rgb8_bilinear_opaque(img, surface, x0, y0, x1, y1);
        covered = result.0;
        #[cfg(feature = "profiling")]
        {
            sample_attempts = (x1 - x0) as u64 * (y1 - y0) as u64;
            sample_taps = result.1;
        }
    } else if let Some(lut) = lut_nearest {
        let result = paint_axis_aligned_lut_nearest_opaque(img, lut, surface, x0, y0, x1, y1);
        covered = result.0;
        #[cfg(feature = "profiling")]
        {
            sample_attempts = (x1 - x0) as u64 * (y1 - y0) as u64;
            sample_taps = result.1;
        }
    } else if fast_rgb8_area {
        let result = paint_axis_aligned_rgb8_area_min_opaque(img, surface, x0, y0, x1, y1);
        covered = result.0;
        #[cfg(feature = "profiling")]
        {
            sample_attempts = (x1 - x0) as u64 * (y1 - y0) as u64;
            sample_taps = result.1;
        }
    } else if let Some(mask) = area_min_mask {
        let result = paint_axis_aligned_rgb8_area_min_masked(img, mask, surface, x0, y0, x1, y1);
        covered = result.0;
        #[cfg(feature = "profiling")]
        {
            sample_attempts = (x1 - x0) as u64 * (y1 - y0) as u64;
            sample_taps = result.1;
        }
    } else if let Some(result) = fast_cmyk_area
        .then(|| paint_axis_aligned_cmyk_area_min_opaque(img, surface, x0, y0, x1, y1))
        .flatten()
    {
        covered = result.0;
        #[cfg(feature = "profiling")]
        {
            fast_cmyk_area_used = true;
            sample_attempts = (x1 - x0) as u64 * (y1 - y0) as u64;
            sample_taps = result.1;
        }
    } else if let Some(lut) = fast_binary.then(|| img.binary_box_lut()).flatten() {
        let result = paint_axis_aligned_binary_box(img, lut, surface, cmask, x0, y0, x1, y1);
        covered = result.0;
        #[cfg(feature = "profiling")]
        {
            sample_attempts = result.1;
            sample_taps = result.2;
        }
    } else if let Some(lut) = stencil_lut {
        let totals = paint_axis_aligned_stencil(img, lut, surface, cmask, blend, x0, y0, x1, y1);
        covered = totals.0;
        #[cfg(feature = "profiling")]
        {
            sample_attempts = totals.1;
            sample_taps = totals.2;
        }
        #[cfg(not(feature = "profiling"))]
        let _ = (totals.1, totals.2);
    } else {
        let totals = paint_image_generic(img, surface, cmask, soft, blend, x0, y0, x1, y1, None);
        covered += totals.0;
        #[cfg(feature = "profiling")]
        {
            sample_attempts += totals.1;
            sample_taps += totals.2;
        }
        #[cfg(not(feature = "profiling"))]
        let _ = (totals.1, totals.2);
    }
    stats.covered_pixels += covered;
    stats.ops_painted += 1;
    #[cfg(feature = "profiling")]
    {
        let profile = &mut stats.profile;
        profile.add_duration("render.image", image_start.elapsed());
        profile.increment("image.draws", 1);
        profile.increment(
            "image.destination_pixels",
            (x1 - x0) as u64 * (y1 - y0) as u64,
        );
        profile.increment("image.sample_attempts", sample_attempts);
        profile.increment("image.source_sample_taps", sample_taps);
        profile.increment("image.painted_pixels", covered);
        if fast_rgb8 {
            profile.increment("image.fast_rgb8_nearest_pixels", covered);
        }
        if fast_rgb8_bilinear {
            profile.increment("image.fast_rgb8_bilinear_pixels", covered);
        }
        if lut_nearest.is_some() {
            profile.increment("image.fast_lut_nearest_pixels", covered);
        }
        if fast_rgb8_area {
            profile.increment("image.fast_rgb8_area_min_pixels", covered);
            profile.add_duration("render.image.area_min", image_start.elapsed());
        } else if let Some(mask) = area_min_mask {
            profile.increment("image.fast_rgb8_area_min_masked_pixels", covered);
            profile.add_duration("render.image.area_min_masked", image_start.elapsed());
            profile.increment(
                match mask {
                    AreaMinMask::Soft(_) => "image.area_min_masked.soft1_draws",
                    AreaMinMask::Soft8(_) => "image.area_min_masked.soft8_draws",
                    AreaMinMask::Stencil(_) => "image.area_min_masked.stencil_draws",
                },
                1,
            );
        }
        if fast_cmyk_area_used {
            profile.increment("image.fast_cmyk_area_min_pixels", covered);
        }
        if fast_binary {
            profile.increment("image.fast_binary_box_pixels", covered);
        }
        if stencil_lut.is_some() {
            profile.increment("image.fast_stencil_pixels", covered);
        }
        if opaque_clip_elided {
            profile.increment("image.opaque_clip_elisions", 1);
        }
        if img.footprint[0] > 1.0 || img.footprint[1] > 1.0 {
            profile.increment("image.minified_draws", 1);
            profile.increment("image.area_average_pixels", sample_attempts);
        } else {
            profile.increment("image.magnified_or_1to1_draws", 1);
            match img.interpolation {
                crate::page_ir::InterpolationMode::Nearest => {
                    profile.increment("image.nearest_pixels", sample_attempts);
                }
                crate::page_ir::InterpolationMode::Bilinear => {
                    profile.increment("image.bilinear_pixels", sample_attempts);
                }
            }
        }
        match &img.color_space {
            crate::page_ir::ImageColorSpace::Gray => profile.increment("image.gray_draws", 1),
            crate::page_ir::ImageColorSpace::Rgb => profile.increment("image.rgb_draws", 1),
            crate::page_ir::ImageColorSpace::Cmyk => profile.increment("image.cmyk_draws", 1),
            crate::page_ir::ImageColorSpace::Indexed { .. } => {
                profile.increment("image.indexed_draws", 1)
            }
            crate::page_ir::ImageColorSpace::TintLut { .. }
            | crate::page_ir::ImageColorSpace::TintLut2 { .. } => {
                profile.increment("image.tint_lut_draws", 1)
            }
            crate::page_ir::ImageColorSpace::Lab { .. } => profile.increment("image.lab_draws", 1),
            crate::page_ir::ImageColorSpace::IccRgb { .. } => {
                profile.increment("image.icc_rgb_draws", 1)
            }
            crate::page_ir::ImageColorSpace::IccCmyk { .. } => {
                profile.increment("image.icc_cmyk_draws", 1)
            }
        }
        if img.is_stencil {
            profile.increment("image.stencil_draws", 1);
        }
        if img.smask.is_some() || img.mask.is_some() {
            profile.increment("image.resource_masked_draws", 1);
        }
        if img.inv.b.abs() < 1e-12 && img.inv.c.abs() < 1e-12 {
            profile.increment("image.axis_aligned_draws", 1);
        } else {
            profile.increment("image.general_affine_draws", 1);
        }
        if img.clip_has_mask {
            profile.increment("image.clip_masked_draws", 1);
        }
        if soft.is_some() {
            profile.increment("image.soft_masked_draws", 1);
        }
    }
}

/// The generic per-pixel image body: the clip and soft-clip coverage, the
/// image-edge coverage (`edge_coverage`: whole pixels by centre for an
/// axis-aligned draw, A10 fractional area otherwise), the full `shade()` sampler and the general
/// compositor, for every destination pixel of `[x0, x1) × [y0, y1)`.
///
/// `hole`, as `[hx0, hx1, hy0, hy1]`, is a rectangle of whole destination
/// columns and rows a fast path has already painted; it is skipped. The fast
/// paths that pass one paint exactly the pixels whose `edge_coverage` is
/// `None` there, so the border band around it is still drawn by
/// this body, and the draw stays byte-identical to running it everywhere.
///
/// Returns `(covered, sample_attempts, sample_taps)`; the last two stay zero
/// unless the profiling counters are compiled in.
#[allow(clippy::too_many_arguments)]
fn paint_image_generic(
    img: &crate::render_cpu::image::PreparedImage,
    surface: &mut Surface,
    cmask: Option<&ClipMask>,
    soft: Option<&ClipMask>,
    blend: BlendChoice,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
    hole: Option<[usize; 4]>,
) -> (u64, u64, u64) {
    // Mask geometry is fixed for the whole draw; resolve it once.
    let clip_win = cmask.map(ClipMask::clip_window);
    let soft_win = soft.map(ClipMask::soft_window);
    let ox = surface.origin_x;
    // One destination pixel. Every term is a pure function of the source, the
    // masks and this pixel's own device coordinate, and the only write is
    // into its own row. Adds to `(covered, sample_attempts, sample_taps)`.
    let paint_px = |x: usize, y: usize, row: &mut [u8], totals: &mut (u64, u64, u64)| {
        // Clip mask coverage.
        let mut cov: u16 = 255;
        if let Some(cw) = &clip_win {
            cov = cw.coverage(x, y);
        }
        if let Some(sw) = &soft_win {
            cov = mul_div_255(cov, sw.coverage(x, y));
        }
        if cov == 0 {
            return;
        }
        // Image-edge coverage: pixels straddling the image's device-space
        // quad edge paint at their A10 fractional coverage when the draw is
        // rotated or sheared, and fully or not at all by pixel centre when
        // it is axis-aligned, masked or not, like the opaque fast paths
        // (`None` = provably interior, full weight).
        let (dx, dy) = (x as f64 + 0.5, y as f64 + 0.5);
        let edge = img.edge_coverage(dx, dy);
        if edge == Some(0) {
            return;
        }
        #[cfg(feature = "profiling")]
        {
            totals.1 += 1;
        }
        let color = match edge {
            None => {
                #[cfg(feature = "profiling")]
                {
                    let (color, taps) = img.shade_profiled(dx, dy);
                    totals.2 += taps;
                    color
                }
                #[cfg(not(feature = "profiling"))]
                img.shade(dx, dy)
            }
            // Edge sliver: sample at the nearest in-quad point.
            Some(_) => img.shade_clamped(dx, dy),
        };
        let Some(color) = color else {
            return;
        };
        let cov = match edge {
            Some(ec) => mul_div_255(cov, ec),
            None => cov,
        };
        if cov == 0 {
            return;
        }
        let a = mul_div_255(mul_div_255(color[3] as u16, img.alpha as u16), cov);
        if a == 0 {
            return;
        }
        let px = &mut row[(x - ox) * 4..(x - ox) * 4 + 4];
        composite_px_blended(px, [color[0], color[1], color[2]], a as u8, blend);
        totals.0 += 1;
    };
    // One destination row: the rows are independent, so the per-pixel
    // arithmetic does not depend on how they are scheduled.
    let paint_row = |y: usize, row: &mut [u8]| -> (u64, u64, u64) {
        let mut totals = (0u64, 0u64, 0u64);
        match hole {
            Some([hx0, hx1, hy0, hy1]) if (hy0..hy1).contains(&y) => {
                for x in x0..hx0 {
                    paint_px(x, y, row, &mut totals);
                }
                for x in hx1..x1 {
                    paint_px(x, y, row, &mut totals);
                }
            }
            _ => {
                for x in x0..x1 {
                    paint_px(x, y, row, &mut totals);
                }
            }
        }
        totals
    };

    let (buf, first_abs_y, row_stride) = surface.rows_mut_abs(y0, y1);
    let parallel = image_row_parallel_enabled()
        && (x1 - x0).saturating_mul(y1 - y0) >= IMAGE_ROW_PAR_PIXEL_THRESHOLD;
    if parallel {
        buf.par_chunks_mut(row_stride)
            .enumerate()
            .map(|(i, row)| paint_row(first_abs_y + i, row))
            .reduce(|| (0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2))
    } else {
        buf.chunks_exact_mut(row_stride)
            .enumerate()
            .map(|(i, row)| paint_row(first_abs_y + i, row))
            .fold((0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2))
    }
}

/// The two-entry table under which `img`, an `/ImageMask` stencil, can take
/// [`paint_axis_aligned_stencil`], or `None` to keep the generic body. The
/// caller adds the draw-level terms (Normal blend, no soft clip).
fn stencil_fast_lut(img: &crate::render_cpu::image::PreparedImage) -> Option<([u8; 4], [u8; 4])> {
    let eligible = img.is_stencil
        && img.inv.b == 0.0
        && img.inv.c == 0.0
        && img.inv.a != 0.0
        && img.inv.d != 0.0
        && (img.footprint[0] > 1.0
            || img.footprint[1] > 1.0
            || img.interpolation == crate::page_ir::InterpolationMode::Nearest);
    if eligible {
        img.stencil_bilevel_lut()
    } else {
        None
    }
}

/// The destination columns (or rows) `[lo, hi)` of an axis-aligned draw that
/// `PreparedImage::edge_coverage` classifies as interior along this axis:
/// the mapped pixel square, `t ± scale/2` with `t = scale·(i + 0.5) + offset`,
/// stays inside `[0, 1]`. With `inv.b == inv.c == 0` exactly, `edge_coverage`'s
/// bound and its `inv.apply` reduce to this per-axis expression bit for bit,
/// so a pixel is interior iff its column and its row both are. `t` is
/// monotone in `i`, so the set is one run; `None` when it is empty.
fn interior_span(scale: f64, offset: f64, lo: usize, hi: usize) -> Option<(usize, usize)> {
    let half = 0.5 * scale.abs();
    let inside = |i: usize| {
        let t = scale * (i as f64 + 0.5) + offset;
        t >= half && t <= 1.0 - half
    };
    let first = (lo..hi).find(|&i| inside(i))?;
    let end = (first..hi).find(|&i| !inside(i)).unwrap_or(hi);
    Some((first, end))
}

/// An axis-aligned `/ImageMask` stencil in solid colour, as a one-bit image
/// whose painting bit is `[stencil_rgb, 255]` and masking bit transparent
/// (`lut`, from `PreparedImage::stencil_bilevel_lut`). The interior rectangle,
/// where `edge_coverage` is `None`, takes the bilevel box filter when the draw
/// minifies, or a nearest walk that skips masked texels when it does not; the
/// border band around it keeps the generic per-pixel body. Both
/// fast paths compute the generic stencil sampler's integers term for term,
/// so the draw is byte-identical to the generic body. The caller has checked
/// Normal blend, no soft clip, `inv.b == inv.c == 0` and, for a draw that
/// does not minify, Nearest interpolation.
#[inline(never)]
#[allow(clippy::too_many_arguments)]
fn paint_axis_aligned_stencil(
    img: &crate::render_cpu::image::PreparedImage,
    lut: ([u8; 4], [u8; 4]),
    surface: &mut Surface,
    cmask: Option<&ClipMask>,
    blend: BlendChoice,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64, u64) {
    let mut totals = (0u64, 0u64, 0u64);
    let span = interior_span(img.inv.a, img.inv.e, x0, x1)
        .zip(interior_span(img.inv.d, img.inv.f, y0, y1));
    let hole = span.map(|((hx0, hx1), (hy0, hy1))| {
        totals = if img.footprint[0] > 1.0 || img.footprint[1] > 1.0 {
            paint_axis_aligned_binary_box(img, lut, surface, cmask, hx0, hy0, hx1, hy1)
        } else {
            paint_axis_aligned_stencil_nearest(img, lut, surface, cmask, hx0, hy0, hx1, hy1)
        };
        [hx0, hx1, hy0, hy1]
    });
    let band = paint_image_generic(img, surface, cmask, None, blend, x0, y0, x1, y1, hole);
    (totals.0 + band.0, totals.1 + band.1, totals.2 + band.2)
}

/// The nearest-sampled interior of an axis-aligned stencil drawn at or above
/// its own resolution (see [`paint_axis_aligned_stencil`]). Every column and
/// row of `[x0, x1) × [y0, y1)` maps inside the image, so each picks its
/// source texel exactly as `shade()` does (`round`, clamped), reads its bit,
/// and skips it when it masks; a painting texel is `[stencil_rgb, 255]`
/// composited at the generic body's `alpha · clip` weight.
#[allow(clippy::too_many_arguments)]
fn paint_axis_aligned_stencil_nearest(
    img: &crate::render_cpu::image::PreparedImage,
    (zero, one): ([u8; 4], [u8; 4]),
    surface: &mut Surface,
    cmask: Option<&ClipMask>,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64, u64) {
    let columns: Vec<u32> = (x0..x1)
        .map(|x| {
            let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
            let fx = u * img.width as f64 - 0.5;
            (fx.round() as i64).clamp(0, img.width.saturating_sub(1) as i64) as u32
        })
        .collect();
    // The bit value that paints, and the paint colour (the table's opaque entry).
    let (paint_bit, paint) = if zero[3] != 0 {
        (0u8, zero)
    } else {
        (1u8, one)
    };
    let rgb = [paint[0], paint[1], paint[2]];
    let row_bytes = img.packed_row_bits() / 8;
    let samples: &[u8] = &img.samples;
    // `color[3]` is 255 for a painting texel, so the generic body's
    // `mul_div_255(255, alpha)` is `alpha`, kept in that form.
    let alpha = mul_div_255(255, img.alpha as u16);
    let clip_win = cmask.map(ClipMask::clip_window);
    let output_origin = surface.origin_x;
    let paint_row = |y: usize, row: &mut [u8]| -> (u64, u64, u64) {
        let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
        let fy = (1.0 - v) * img.height as f64 - 0.5;
        let source_row = (fy.round() as i64).clamp(0, img.height.saturating_sub(1) as i64) as usize;
        let source = &samples[source_row * row_bytes..][..row_bytes];
        let mut painted = 0u64;
        for (local_x, &col) in columns.iter().enumerate() {
            let bit = (source[col as usize >> 3] >> (7 - (col & 7))) & 1;
            if bit != paint_bit {
                continue;
            }
            let x = x0 + local_x;
            let cov = clip_win.as_ref().map_or(255, |cw| cw.coverage(x, y));
            let a = mul_div_255(alpha, cov);
            if a == 0 {
                continue;
            }
            let px = &mut row[(x - output_origin) * 4..][..4];
            if a == 255 {
                px.copy_from_slice(&[rgb[0], rgb[1], rgb[2], 255]);
            } else {
                composite_px_blended(px, rgb, a as u8, BlendChoice::Normal);
            }
            painted += 1;
        }
        let attempts = columns.len() as u64;
        (painted, attempts, attempts)
    };
    let (output, first_output_y, output_stride) = surface.rows_mut_abs(y0, y1);
    let parallel = image_row_parallel_enabled()
        && (x1 - x0).saturating_mul(y1 - y0) >= IMAGE_ROW_PAR_PIXEL_THRESHOLD;
    if parallel {
        output
            .par_chunks_mut(output_stride)
            .enumerate()
            .map(|(i, row)| paint_row(first_output_y + i, row))
            .reduce(|| (0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2))
    } else {
        output
            .chunks_exact_mut(output_stride)
            .enumerate()
            .map(|(i, row)| paint_row(first_output_y + i, row))
            .fold((0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2))
    }
}

/// Fast path for an axis-aligned minified one-bit image. Device X and Y map
/// independently into source space, so prepare the inclusive source box for
/// each destination column/row once instead of repeating affine and footprint
/// math for every pixel.
#[allow(clippy::too_many_arguments)]
fn paint_axis_aligned_binary_box(
    img: &crate::render_cpu::image::PreparedImage,
    lut: ([u8; 4], [u8; 4]),
    surface: &mut Surface,
    cmask: Option<&ClipMask>,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64, u64) {
    let mut source_columns: Vec<Option<crate::render_cpu::image::AxisTaps>> =
        Vec::with_capacity(x1 - x0);
    for x in x0..x1 {
        let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
        if !(0.0..1.0).contains(&u) {
            source_columns.push(None);
            continue;
        }
        let fx = u * img.width as f64 - 0.5;
        source_columns.push(img.box_taps_x(fx));
    }

    let mut source_rows: Vec<Option<crate::render_cpu::image::AxisTaps>> =
        Vec::with_capacity(y1 - y0);
    for y in y0..y1 {
        let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
        if !(0.0..1.0).contains(&v) {
            source_rows.push(None);
            continue;
        }
        let fy = (1.0 - v) * img.height as f64 - 0.5;
        source_rows.push(img.box_taps_y(fy));
    }

    // Prefer the row-band filter: per destination row, weight each referenced
    // source column's bits down the row's taps once, then every destination
    // box's weighted ones count is two edge reads and one prefix difference.
    // The same integers as the per-pixel `binary_box_average`, in another
    // order, so the output is byte-for-byte unchanged.
    if let Some(window) = BilevelWindow::new(img, &source_columns, &source_rows) {
        return paint_binary_box_rows(
            img,
            lut,
            surface,
            cmask,
            &source_columns,
            &source_rows,
            &window,
            x0,
            y0,
        );
    }
    paint_binary_box_serial(
        img,
        lut,
        surface,
        cmask,
        &source_columns,
        &source_rows,
        x0,
        y0,
    )
}

/// The per-pixel minified bilevel loop: each destination box's weighted ones
/// count by packed popcount (`binary_box_average_with`, which reads the rows
/// through `get`, so a truncated buffer counts its missing bytes as zero).
/// The fallback when [`BilevelWindow::new`] declines the draw, and the
/// reference the row-band filter is tested against.
#[allow(clippy::too_many_arguments)]
fn paint_binary_box_serial(
    img: &crate::render_cpu::image::PreparedImage,
    lut: ([u8; 4], [u8; 4]),
    surface: &mut Surface,
    cmask: Option<&ClipMask>,
    source_columns: &[Option<crate::render_cpu::image::AxisTaps>],
    source_rows: &[Option<crate::render_cpu::image::AxisTaps>],
    x0: usize,
    y0: usize,
) -> (u64, u64, u64) {
    let output_origin = surface.origin_x;
    let mut painted = 0u64;
    let mut attempts = 0u64;
    let mut taps = 0u64;
    // Fixed for the whole draw; resolve it once rather than per pixel.
    let clip_win = cmask.map(ClipMask::clip_window);
    let (output, first_output_y, output_stride) = surface.rows_mut_abs(y0, y0 + source_rows.len());
    // Align the row table with the clipped output window.
    let row_offset = first_output_y.saturating_sub(y0);
    let row_slice = source_rows.get(row_offset..).unwrap_or(&[]);
    for (i, (row, row_taps)) in output
        .chunks_exact_mut(output_stride)
        .zip(row_slice)
        .enumerate()
    {
        let y = first_output_y + i;
        for (local_x, col_taps) in source_columns.iter().enumerate() {
            let x = x0 + local_x;
            let cov = clip_win.as_ref().map_or(255, |cw| cw.coverage(x, y));
            if cov == 0 {
                continue;
            }
            attempts += 1;
            let (Some(tx), Some(ty)) = (col_taps, row_taps) else {
                continue;
            };
            let Some((color, source_taps)) = img.binary_box_average_with(lut, tx, ty) else {
                continue;
            };
            taps += source_taps;
            let a = mul_div_255(mul_div_255(color[3] as u16, img.alpha as u16), cov);
            if a == 0 {
                continue;
            }
            let target = (x - output_origin) * 4;
            if a == 255 {
                row[target] = color[0];
                row[target + 1] = color[1];
                row[target + 2] = color[2];
                row[target + 3] = 255;
            } else {
                let ia = 255 - a;
                row[target] =
                    (mul_div_255(color[0] as u16, a) + mul_div_255(row[target] as u16, ia)) as u8;
                row[target + 1] = (mul_div_255(color[1] as u16, a)
                    + mul_div_255(row[target + 1] as u16, ia))
                    as u8;
                row[target + 2] = (mul_div_255(color[2] as u16, a)
                    + mul_div_255(row[target + 2] as u16, ia))
                    as u8;
                row[target + 3] = (a + mul_div_255(row[target + 3] as u16, ia)) as u8;
            }
            painted += 1;
        }
    }
    (painted, attempts, taps)
}

/// The referenced source window of a minified one-bit draw, for the row-band
/// weighted popcount ([`paint_binary_box_rows`]). It reads the packed rows in
/// whole bytes from `byte_lo`, so its column index `i` is source column
/// `byte_lo * 8 + i`; the few columns outside the taps' union only cost a
/// read.
struct BilevelWindow<'a> {
    samples: &'a [u8],
    row_bytes: usize,
    byte_lo: usize,
    nbytes: usize,
    /// Source rows the draw's taps span, for the parallel decision.
    rows: usize,
}

impl<'a> BilevelWindow<'a> {
    /// `None` (keep the per-pixel loop) when no destination column or row
    /// maps into the image, when the sample buffer is shorter than the rows
    /// the taps reach (a truncated JBIG2 or CCITT decode: the window indexes
    /// rows directly, the per-pixel loop reads them through `get`), or when a
    /// row's tap weights could overflow the `u32` column sums.
    fn new(
        img: &'a crate::render_cpu::image::PreparedImage,
        source_columns: &[Option<crate::render_cpu::image::AxisTaps>],
        source_rows: &[Option<crate::render_cpu::image::AxisTaps>],
    ) -> Option<Self> {
        let col_lo = source_columns.iter().flatten().map(|t| t.lo).min()?;
        let col_hi = source_columns.iter().flatten().map(|t| t.hi).max()?;
        let row_lo = source_rows.iter().flatten().map(|t| t.lo).min()?;
        let row_hi = source_rows.iter().flatten().map(|t| t.hi).max()?;
        let max_row_total = source_rows.iter().flatten().map(|t| t.total).max()?;
        if max_row_total > u32::MAX as u64 {
            return None;
        }
        let row_bytes = img.packed_row_bits() / 8;
        let byte_lo = col_lo as usize >> 3;
        let nbytes = (col_hi as usize >> 3) + 1 - byte_lo;
        let end = (row_hi as usize)
            .checked_mul(row_bytes)?
            .checked_add(byte_lo + nbytes)?;
        if img.samples.len() < end {
            return None;
        }
        Some(Self {
            samples: &img.samples,
            row_bytes,
            byte_lo,
            nbytes,
            rows: (row_hi - row_lo) as usize + 1,
        })
    }

    /// `colw[i] = Σ_y wy(y)·bit(i, y)` over the source rows of `rows`, each
    /// row weighted by its tap weight; then `prefix[i] = Σ_{j<i} colw[j]`.
    /// Returns whether any referenced bit is set (when none is, both stay
    /// zero and every box of the row counts zero ones).
    fn column_sums(
        &self,
        rows: &crate::render_cpu::image::AxisTaps,
        colw: &mut [u32],
        prefix: &mut [u64],
    ) -> bool {
        colw.fill(0);
        let mut any = 0u8;
        for y in rows.lo..=rows.hi {
            let wy = rows.weight_at(y) as u32;
            let start = y as usize * self.row_bytes + self.byte_lo;
            let src = &self.samples[start..start + self.nbytes];
            for (&byte, sums) in src.iter().zip(colw.chunks_exact_mut(8)) {
                if byte == 0 {
                    continue;
                }
                any |= byte;
                for (k, sum) in sums.iter_mut().enumerate() {
                    *sum += wy * ((byte >> (7 - k)) & 1) as u32;
                }
            }
        }
        if any == 0 {
            return false;
        }
        let mut acc = 0u64;
        prefix[0] = 0;
        for (p, &c) in prefix[1..].iter_mut().zip(colw.iter()) {
            acc += c as u64;
            *p = acc;
        }
        true
    }
}

/// `Σ_x wx(x)·colw[x]` over the column taps `cols`, with `colw` and its
/// exclusive prefix from [`BilevelWindow::column_sums`] (index 0 at source
/// column `base`): the interior columns weigh a full `AXIS_TAP_SCALE`, so
/// they are one prefix difference. Equals `Σ_y Σ_x wy·wx·bit`, the integer
/// `BilevelIntegral::weighted_ones` and `binary_box_average` compute.
#[inline]
fn row_band_weighted_ones(
    cols: &crate::render_cpu::image::AxisTaps,
    base: u32,
    colw: &[u32],
    prefix: &[u64],
) -> u64 {
    let lo = (cols.lo - base) as usize;
    let hi = (cols.hi - base) as usize;
    if lo == hi {
        return cols.w_lo * colw[lo] as u64;
    }
    cols.w_lo * colw[lo] as u64
        + cols.w_hi * colw[hi] as u64
        + crate::render_cpu::image::AXIS_TAP_SCALE * (prefix[hi] - prefix[lo + 1])
}

/// Composite a prepared axis-aligned minified one-bit image with the row-band
/// weighted popcount ([`BilevelWindow`]). The clip coverage, the two-entry
/// mix and the source-over arithmetic are the per-pixel loop's
/// ([`paint_binary_box_serial`]); only the weighted ones count is reordered,
/// and the mix is memoized across identical `(weight, ones)` runs, which
/// dominate bilevel scans' long white/black stretches.
///
/// Destination rows are independent: each band of them weights its own
/// source rows into its own scratch and writes only its own output rows, so
/// bands run across the rayon pool (when `PDF_RENDERER_IMAGE_ROW_PAR` and the
/// pages in flight allow) without changing a byte. A source row a band shares
/// with its neighbour is only read twice. The working set is two rows of the
/// referenced source width per band, where the summed-area table this
/// replaces held four bytes per referenced source texel (34 MB for a 300-dpi
/// page, and none at all above its 32M-entry cap, which a 600-dpi Letter page
/// exceeds).
#[allow(clippy::too_many_arguments)]
fn paint_binary_box_rows(
    img: &crate::render_cpu::image::PreparedImage,
    (zero, one): ([u8; 4], [u8; 4]),
    surface: &mut Surface,
    cmask: Option<&ClipMask>,
    source_columns: &[Option<crate::render_cpu::image::AxisTaps>],
    source_rows: &[Option<crate::render_cpu::image::AxisTaps>],
    window: &BilevelWindow<'_>,
    x0: usize,
    y0: usize,
) -> (u64, u64, u64) {
    let alpha = img.alpha as u16;
    let output_origin = surface.origin_x;
    // Fixed for the whole draw; resolve it once rather than per pixel.
    let clip_win = cmask.map(ClipMask::clip_window);
    let base = (window.byte_lo * 8) as u32;
    let span = window.nbytes * 8;

    let paint_band = |first_y: usize,

                      band: &mut [u8],
                      band_rows: &[Option<crate::render_cpu::image::AxisTaps>],
                      stride: usize|

     -> (u64, u64, u64) {
        let mut colw = vec![0u32; span];
        let mut prefix = vec![0u64; span + 1];
        let (mut painted, mut attempts, mut taps) = (0u64, 0u64, 0u64);
        for (i, (row, row_taps)) in band.chunks_exact_mut(stride).zip(band_rows).enumerate() {
            let y = first_y + i;
            // Whether any referenced bit of this row's taps is set; when none
            // is, every box counts zero ones and the sums are not built.
            let any = row_taps
                .as_ref()
                .is_some_and(|ty| window.column_sums(ty, &mut colw, &mut prefix));
            // All-zero / all-one boxes short-circuit without division; the
            // mixed boxes memoize on `(weight, weighted ones)`. Clip coverage
            // and destination blending stay per pixel.
            let mut memo_key = (u64::MAX, u64::MAX);
            let mut memo_color = [0u8; 4];
            for (local_x, col_taps) in source_columns.iter().enumerate() {
                let x = x0 + local_x;
                let cov = clip_win.as_ref().map_or(255, |cw| cw.coverage(x, y));
                if cov == 0 {
                    continue;
                }
                attempts += 1;
                let (Some(tx), Some(ty)) = (col_taps, row_taps) else {
                    continue;
                };
                let weight = tx.total * ty.total;
                if weight == 0 {
                    continue;
                }
                taps += (tx.hi - tx.lo + 1) as u64 * (ty.hi - ty.lo + 1) as u64;
                let ones_w = if any {
                    row_band_weighted_ones(tx, base, &colw, &prefix)
                } else {
                    0
                };
                let color = if ones_w == 0 {
                    zero
                } else if ones_w >= weight {
                    one
                } else if memo_key == (weight, ones_w) {
                    memo_color
                } else {
                    let c = crate::render_cpu::image::mix_bilevel(zero, one, ones_w, weight);
                    memo_key = (weight, ones_w);
                    memo_color = c;
                    c
                };
                let a = mul_div_255(mul_div_255(color[3] as u16, alpha), cov);
                if a == 0 {
                    continue;
                }
                let target = (x - output_origin) * 4;
                if a == 255 {
                    row[target] = color[0];
                    row[target + 1] = color[1];
                    row[target + 2] = color[2];
                    row[target + 3] = 255;
                } else {
                    let ia = 255 - a;
                    row[target] = (mul_div_255(color[0] as u16, a)
                        + mul_div_255(row[target] as u16, ia))
                        as u8;
                    row[target + 1] = (mul_div_255(color[1] as u16, a)
                        + mul_div_255(row[target + 1] as u16, ia))
                        as u8;
                    row[target + 2] = (mul_div_255(color[2] as u16, a)
                        + mul_div_255(row[target + 2] as u16, ia))
                        as u8;
                    row[target + 3] = (a + mul_div_255(row[target + 3] as u16, ia)) as u8;
                }
                painted += 1;
            }
        }
        (painted, attempts, taps)
    };

    let dest_w = source_columns.len();
    let dest_h = source_rows.len();
    let (output, first_output_y, output_stride) = surface.rows_mut_abs(y0, y0 + dest_h);
    // Align the row table with the clipped output window.
    let row_offset = first_output_y.saturating_sub(y0);
    let row_slice = source_rows.get(row_offset..).unwrap_or(&[]);

    // Fan out on either side of the work: many destination pixels, or a large
    // source read (a heavily minified page has few of the former).
    let parallel = image_row_parallel_enabled()
        && (dest_w.saturating_mul(dest_h) >= IMAGE_ROW_PAR_PIXEL_THRESHOLD
            || span.saturating_mul(window.rows) >= BILEVEL_ROWS_PAR_MIN_BITS);
    if parallel {
        const BAND: usize = 16;
        output
            .par_chunks_mut(output_stride * BAND)
            .zip(row_slice.par_chunks(BAND))
            .enumerate()
            .map(|(i, (band, rows))| {
                paint_band(first_output_y + i * BAND, band, rows, output_stride)
            })
            .reduce(|| (0, 0, 0), |a, b| (a.0 + b.0, a.1 + b.1, a.2 + b.2))
    } else {
        paint_band(first_output_y, output, row_slice, output_stride)
    }
}

/// A summed-area table of set bits over the referenced source sub-rectangle of a
/// prepared one-bit image. `sat[(ay+1)*stride + (ax+1)]` holds the number of set
/// bits in the local sub-rectangle rows `0..=ay`, columns `0..=ax`; the first
/// row and column are zero, so any inclusive box `[ax0..=ax1] × [ay0..=ay1]`
/// counts its ones in four reads.
///
/// Test-only: the oracle the row-band filter ([`BilevelWindow`]) that
/// replaced it is checked against.
#[cfg(test)]
struct BilevelIntegral {
    sat: Vec<u32>,
    stride: usize,
    col_lo: u32,
    row_lo: u32,
}

#[cfg(test)]
impl BilevelIntegral {
    /// Fill `sat` with the same table the serial walk in [`Self::build`]
    /// produces, in three passes: every block of rows sums from zero in
    /// parallel; the block-boundary carries are chained once (a handful of
    /// rows); every block but the first then adds its carry back, in parallel.
    /// Each cell ends as the same sum of the same `u32` terms, so the table is
    /// bit-identical to the serial one.
    #[allow(clippy::too_many_arguments)]
    fn fill_parallel(
        sat: &mut [u32],
        samples: &[u8],
        stride: usize,
        sw: usize,
        sh: usize,
        row_bits: usize,
        col_lo: u32,
        row_lo: u32,
    ) {
        // Row 0 of the table is the all-zero sentinel and is never written.
        let body = &mut sat[stride..];
        let threads = rayon::current_num_threads().max(1);
        // Two blocks per thread keeps the tail balanced without making the
        // serial carry chain (one row of `stride` adds per block) matter.
        let block_rows = sh.div_ceil(threads * 2).max(1);
        let chunk = block_rows * stride;

        body.par_chunks_mut(chunk).enumerate().for_each(|(b, blk)| {
            let first_ly = b * block_rows;
            let rows = blk.len() / stride;
            for i in 0..rows {
                let source_row = row_lo as usize + first_ly + i;
                let base_bit = source_row * row_bits + col_lo as usize;
                let (before, rest) = blk.split_at_mut(i * stride);
                let cur = &mut rest[..stride];
                let mut rowsum = 0u32;
                if i == 0 {
                    for (lx, bitpos) in (base_bit..base_bit + sw).enumerate() {
                        let byte = samples[bitpos >> 3];
                        rowsum += ((byte >> (7 - (bitpos & 7))) & 1) as u32;
                        cur[lx + 1] = rowsum;
                    }
                } else {
                    let prev = &before[(i - 1) * stride..i * stride];
                    for (lx, bitpos) in (base_bit..base_bit + sw).enumerate() {
                        let byte = samples[bitpos >> 3];
                        rowsum += ((byte >> (7 - (bitpos & 7))) & 1) as u32;
                        cur[lx + 1] = prev[lx + 1] + rowsum;
                    }
                }
            }
        });

        let blocks = body.len().div_ceil(chunk);
        if blocks < 2 {
            return;
        }
        // `carries[b]` is the running column total of every row before block
        // `b`; block 0 needs none. Only whole blocks are ever a predecessor,
        // so the last row of block `b - 1` is always at `b * block_rows - 1`.
        let mut carries = vec![0u32; blocks * stride];
        for b in 1..blocks {
            let last = (b * block_rows - 1) * stride;
            let (done, pending) = carries.split_at_mut(b * stride);
            let prev_carry = &done[(b - 1) * stride..];
            for ((dst, carry), tail) in pending[..stride]
                .iter_mut()
                .zip(prev_carry)
                .zip(&body[last..last + stride])
            {
                *dst = *carry + *tail;
            }
        }

        body.par_chunks_mut(chunk)
            .enumerate()
            .skip(1)
            .for_each(|(b, blk)| {
                let carry = &carries[b * stride..(b + 1) * stride];
                for row in blk.chunks_exact_mut(stride) {
                    for (cell, add) in row.iter_mut().zip(carry) {
                        *cell += *add;
                    }
                }
            });
    }

    /// Cap on the integral-image allocation. Above this the referenced source
    /// region is large enough that per-pixel popcount (whose total work is
    /// bounded by the box footprint, not the source area) is preferred, and the
    /// table is not built. 128 MiB of `u32` covers a ~180-megapixel scan.
    const MAX_ENTRIES: usize = 32 * 1024 * 1024;

    fn build(
        img: &crate::render_cpu::image::PreparedImage,
        source_columns: &[Option<crate::render_cpu::image::AxisTaps>],
        source_rows: &[Option<crate::render_cpu::image::AxisTaps>],
    ) -> Option<Self> {
        let (mut col_lo, mut col_hi, mut any_col) = (u32::MAX, 0u32, false);
        for taps in source_columns.iter().flatten() {
            col_lo = col_lo.min(taps.lo);
            col_hi = col_hi.max(taps.hi);
            any_col = true;
        }
        let (mut row_lo, mut row_hi, mut any_row) = (u32::MAX, 0u32, false);
        for taps in source_rows.iter().flatten() {
            row_lo = row_lo.min(taps.lo);
            row_hi = row_hi.max(taps.hi);
            any_row = true;
        }
        if !any_col || !any_row {
            return None;
        }
        let sw = (col_hi - col_lo + 1) as usize;
        let sh = (row_hi - row_lo + 1) as usize;
        let stride = sw + 1;
        let entries = stride.checked_mul(sh + 1)?;
        if entries > Self::MAX_ENTRIES {
            return None;
        }

        let row_bits = img.packed_row_bits();
        let samples: &[u8] = &img.samples;
        // The fill indexes the packed rows directly. A truncated buffer (a
        // short JBIG2 or CCITT decode) would panic there; the per-pixel
        // fallback reads it through `get`, as the generic sampler does.
        let last_bit = (row_hi as usize * row_bits).checked_add(col_hi as usize)?;
        if samples.len() <= last_bit >> 3 {
            return None;
        }
        let mut sat = vec![0u32; entries];
        // The table is a running sum, so the rows form one dependency chain —
        // but a *block* of rows can be summed from zero independently and then
        // shifted by the running total that reaches it, and integer addition
        // is associative, so the finished table is bit-for-bit the same one
        // the serial walk below produces. That matters here because the table
        // is the draw's dominant cost: a full-page bilevel scan writes ~100 MB
        // of `u32`, most of it first-touch page faults, and those parallelize.
        if image_row_parallel_enabled() && entries >= BILEVEL_ROWS_PAR_MIN_BITS {
            Self::fill_parallel(&mut sat, samples, stride, sw, sh, row_bits, col_lo, row_lo);
        } else {
            for ly in 0..sh {
                let source_row = row_lo as usize + ly;
                let base_bit = source_row * row_bits + col_lo as usize;
                let (prev, cur) = sat.split_at_mut((ly + 1) * stride);
                let prev = &prev[ly * stride..ly * stride + stride];
                let cur = &mut cur[..stride];
                let mut rowsum = 0u32;
                for (lx, bitpos) in (base_bit..base_bit + sw).enumerate() {
                    let byte = samples[bitpos >> 3];
                    rowsum += ((byte >> (7 - (bitpos & 7))) & 1) as u32;
                    cur[lx + 1] = prev[lx + 1] + rowsum;
                }
            }
        }
        Some(Self {
            sat,
            stride,
            col_lo,
            row_lo,
        })
    }

    /// Set bits in the inclusive source box, in four table reads.
    #[inline]
    fn ones(&self, sx0: u32, sx1: u32, sy0: u32, sy1: u32) -> u32 {
        let ax0 = (sx0 - self.col_lo) as usize;
        let ax1 = (sx1 - self.col_lo + 1) as usize;
        let ay0 = (sy0 - self.row_lo) as usize;
        let ay1 = (sy1 - self.row_lo + 1) as usize;
        let s = self.stride;
        self.sat[ay1 * s + ax1] + self.sat[ay0 * s + ax0]
            - self.sat[ay0 * s + ax1]
            - self.sat[ay1 * s + ax0]
    }

    /// Fractionally-weighted set-bit count of the tap box, in `AXIS_TAP_SCALE²`
    /// units. Interior taps weigh a full `S²`; the edge rows/columns carry
    /// their overlap weight. Expansion of `Σ wy·wx·bit` with per-axis edge
    /// deficits `u = S − w`:
    ///
    /// `S²·box − S·Σ u_c·colstrip(c) − S·Σ u_r·rowstrip(r) + Σ u_c·u_r·corner`
    ///
    /// — every term a SAT box read, so the cost stays O(1) per pixel.
    fn weighted_ones(
        &self,
        cols: &crate::render_cpu::image::AxisTaps,
        rows: &crate::render_cpu::image::AxisTaps,
    ) -> u64 {
        const S: i64 = crate::render_cpu::image::AXIS_TAP_SCALE as i64;
        let box_ones = self.ones(cols.lo, cols.hi, rows.lo, rows.hi) as i64;
        let mut acc = S * S * box_ones;

        // Unique edge indices with their weight deficits (lo == hi collapses
        // to a single entry carrying the whole deficit).
        let col_edges: [(u32, i64); 2] = if cols.lo == cols.hi {
            [(cols.lo, S - cols.w_lo as i64), (cols.lo, 0)]
        } else {
            [
                (cols.lo, S - cols.w_lo as i64),
                (cols.hi, S - cols.w_hi as i64),
            ]
        };
        let row_edges: [(u32, i64); 2] = if rows.lo == rows.hi {
            [(rows.lo, S - rows.w_lo as i64), (rows.lo, 0)]
        } else {
            [
                (rows.lo, S - rows.w_lo as i64),
                (rows.hi, S - rows.w_hi as i64),
            ]
        };

        for &(c, u) in &col_edges {
            if u > 0 {
                acc -= S * u * self.ones(c, c, rows.lo, rows.hi) as i64;
            }
        }
        for &(r, u) in &row_edges {
            if u > 0 {
                acc -= S * u * self.ones(cols.lo, cols.hi, r, r) as i64;
            }
        }
        for &(c, uc) in &col_edges {
            if uc == 0 {
                continue;
            }
            for &(r, ur) in &row_edges {
                if ur == 0 {
                    continue;
                }
                acc += uc * ur * self.ones(c, c, r, r) as i64;
            }
        }
        acc.max(0) as u64
    }
}

/// Fast path for the common scan/viewer case: an opaque, unmasked, axis-aligned
/// RGB8 image sampled nearest-neighbor. Source X indices depend only on device
/// X, so compute them once per draw; then copy bytes directly into the
/// premultiplied RGBA surface (opaque straight RGB equals premultiplied RGB).
///
/// Runs of destination columns that read consecutive source texels — the
/// whole row at 1:1 — are widened 3→4 bytes by [`widen_rgb8_to_rgba8_opaque`]
/// instead of copied texel by texel.
fn paint_axis_aligned_rgb8_nearest_opaque(
    img: &crate::render_cpu::image::PreparedImage,
    surface: &mut Surface,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64) {
    // Present (in-image) destination columns form one interval: `u` is
    // monotone in `x`, so the set where it lies in `[0, 1)` is contiguous.
    let mut first_x = None;
    let mut columns: Vec<u32> = Vec::with_capacity(x1 - x0);
    for x in x0..x1 {
        let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
        if !(0.0..1.0).contains(&u) {
            if first_x.is_some() {
                break;
            }
            continue;
        }
        first_x.get_or_insert(x);
        let fx = u * img.width as f64 - 0.5;
        columns.push((fx.round() as i64).clamp(0, img.width.saturating_sub(1) as i64) as u32);
    }
    let Some(first_x) = first_x else {
        return (0, 0);
    };
    let runs = consecutive_runs(&columns);
    let n = columns.len();

    let source_stride = img.width as usize * 3;
    let samples: &[u8] = &img.samples;
    let output_origin = surface.origin_x;
    let kernel = image_kernel();
    let mut painted = 0u64;
    for y in y0..y1 {
        let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
        if !(0.0..1.0).contains(&v) {
            continue;
        }
        let fy = (1.0 - v) * img.height as f64 - 0.5;
        let source_row = (fy.round() as i64).clamp(0, img.height.saturating_sub(1) as i64) as usize;
        let source_base = source_row * source_stride;
        let row = surface.row_mut(y);
        let dst = &mut row[(first_x - output_origin) * 4..][..n * 4];
        for &(start, len) in &runs {
            let src_off = source_base + columns[start] as usize * 3;
            widen_rgb8_to_rgba8_opaque(kernel, samples, src_off, &mut dst[start * 4..][..len * 4]);
        }
        painted += n as u64;
    }
    (painted, painted)
}

/// Fast path for an axis-aligned magnified or 1:1 low-bit-depth image that
/// samples through a prepared lookup table (`PreparedImage::sample_lut`): the
/// one-bit JBIG2 or CCITT page a scanner, or an MRC producer
/// writes, drawn at or above its own resolution. The generic per-pixel loop
/// paid an inverse map, an edge test and a `shade()` per destination pixel
/// for it (~30 ns each, 100 ms for a 1474×2400 page). Device X and Y map to a
/// source column and row independently once the placement is axis-aligned,
/// so the column → texel table is built once and each destination row reads
/// its packed source row through the lookup table. Nearest sampling,
/// byte-identical to `PreparedImage::shade` (`nearest` → `pixel` →
/// `lut[read_bits(..)]`); the caller has checked the table is complete and
/// opaque and the sample data covers every row (`lut_nearest_opaque`).
fn paint_axis_aligned_lut_nearest_opaque(
    img: &crate::render_cpu::image::PreparedImage,
    lut: &[[u8; 4]],
    surface: &mut Surface,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64) {
    // Same column mapping as `paint_axis_aligned_rgb8_nearest_opaque`.
    let mut first_x = None;
    let mut columns: Vec<u32> = Vec::with_capacity(x1 - x0);
    for x in x0..x1 {
        let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
        if !(0.0..1.0).contains(&u) {
            if first_x.is_some() {
                break;
            }
            continue;
        }
        first_x.get_or_insert(x);
        let fx = u * img.width as f64 - 0.5;
        columns.push((fx.round() as i64).clamp(0, img.width.saturating_sub(1) as i64) as u32);
    }
    let Some(first_x) = first_x else {
        return (0, 0);
    };
    let n = columns.len();

    let bpc = img.bpc as usize;
    let mask = ((1u16 << bpc) - 1) as u8;
    // Packed rows are byte-aligned (`row_bits` is a multiple of 8), and every
    // column index is below the width, so `bit >> 3` stays inside the row.
    let row_bytes = img.packed_row_bits() / 8;
    let samples: &[u8] = &img.samples;
    let output_origin = surface.origin_x;
    let mut painted = 0u64;
    for y in y0..y1 {
        let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
        if !(0.0..1.0).contains(&v) {
            continue;
        }
        let fy = (1.0 - v) * img.height as f64 - 0.5;
        let source_row = (fy.round() as i64).clamp(0, img.height.saturating_sub(1) as i64) as usize;
        let source = &samples[source_row * row_bytes..][..row_bytes];
        let row = surface.row_mut(y);
        let dst = &mut row[(first_x - output_origin) * 4..][..n * 4];
        for (&col, out) in columns.iter().zip(dst.chunks_exact_mut(4)) {
            let bit = col as usize * bpc;
            let value = (source[bit >> 3] >> (8 - bpc - (bit & 7))) & mask;
            out.copy_from_slice(&lut[value as usize]);
        }
        painted += n as u64;
    }
    (painted, painted)
}

/// Split `columns` into maximal runs `(start, len)` of consecutive source
/// texel indices (`columns[k + 1] == columns[k] + 1`).
fn consecutive_runs(columns: &[u32]) -> Vec<(usize, usize)> {
    let mut runs = Vec::new();
    let mut start = 0usize;
    for k in 1..=columns.len() {
        if k == columns.len() || columns[k] != columns[k - 1].wrapping_add(1) {
            runs.push((start, k - start));
            start = k;
        }
    }
    runs
}

/// Which vector kernel the opaque RGB8 image painters run. Probed once per
/// draw, never per pixel; the scalar twins are the reference the vector
/// kernels are tested against bit for bit.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
enum ImageKernel {
    Scalar,
    #[cfg(target_arch = "x86_64")]
    Avx2,
}

#[inline]
fn image_kernel() -> ImageKernel {
    #[cfg(target_arch = "x86_64")]
    {
        if is_x86_feature_detected!("avx2") {
            return ImageKernel::Avx2;
        }
    }
    ImageKernel::Scalar
}

/// Write `dst.len() / 4` opaque RGBA pixels from the packed RGB8 texels at
/// `src[src_off..]`: `[r, g, b]` → `[r, g, b, 255]`. The source is the whole
/// sample buffer (not just the run) so the vector kernel can read a few bytes
/// past the run's end wherever the buffer continues; it never reads past the
/// buffer itself.
#[inline]
#[allow(
    unsafe_code,
    reason = "dispatches the AVX2 widen kernel behind a runtime probe; see SAFETY comment"
)]
fn widen_rgb8_to_rgba8_opaque(kernel: ImageKernel, src: &[u8], src_off: usize, dst: &mut [u8]) {
    let n = dst.len() / 4;
    // Bounds-check the run once, here, so both kernels share one invariant.
    let run = &src[src_off..src_off + n * 3];
    match kernel {
        #[cfg(target_arch = "x86_64")]
        ImageKernel::Avx2 => {
            // SAFETY: AVX2 is present (`image_kernel` probed it); `run` is a
            // valid `3n` byte slice at `src_off` within `src`, and `dst` holds
            // at least `4n` bytes.
            unsafe { widen_rgb8_to_rgba8_avx2(src, src_off, n, dst) }
        }
        ImageKernel::Scalar => widen_rgb8_to_rgba8_scalar(run, dst),
    }
}

/// Scalar reference for [`widen_rgb8_to_rgba8_opaque`].
#[inline]
fn widen_rgb8_to_rgba8_scalar(run: &[u8], dst: &mut [u8]) {
    for (rgb, out) in run.chunks_exact(3).zip(dst.chunks_exact_mut(4)) {
        out[0] = rgb[0];
        out[1] = rgb[1];
        out[2] = rgb[2];
        out[3] = 255;
    }
}

/// AVX2 widen: eight texels per iteration (two 16-byte loads, one in-lane
/// byte shuffle, one alpha OR, one 32-byte store), scalar for the remainder
/// and wherever a 16-byte load would run past the end of `src`.
///
/// # Safety
/// The CPU must support AVX2. `src[src_off..src_off + 3n]` and `dst[..4n]`
/// must be in bounds (the caller slices both).
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[allow(unsafe_code)]
unsafe fn widen_rgb8_to_rgba8_avx2(src: &[u8], src_off: usize, n: usize, dst: &mut [u8]) {
    use core::arch::x86_64::*;
    debug_assert!(dst.len() >= n * 4 && src.len() >= src_off + n * 3);
    // Per 128-bit lane: texel k's bytes 3k..3k+2 land at 4k..4k+2; byte 4k+3
    // is zeroed (shuffle index -1) and then OR'd to 255.
    let shuffle = _mm256_setr_epi8(
        0, 1, 2, -1, 3, 4, 5, -1, 6, 7, 8, -1, 9, 10, 11, -1, //
        0, 1, 2, -1, 3, 4, 5, -1, 6, 7, 8, -1, 9, 10, 11, -1,
    );
    let alpha = _mm256_set1_epi32(0xFF00_0000u32 as i32);
    let mut i = 0usize;
    // The second lane's load starts 12 bytes in and reads 16, so the group
    // needs 28 readable source bytes.
    while i + 8 <= n && src_off + i * 3 + 28 <= src.len() {
        // SAFETY: both 16-byte loads lie within `src` by the loop condition;
        // the 32-byte store lies within `dst[..4n]` since `i + 8 <= n`.
        unsafe {
            let p = src.as_ptr().add(src_off + i * 3);
            let lo = _mm_loadu_si128(p.cast());
            let hi = _mm_loadu_si128(p.add(12).cast());
            let v = _mm256_set_m128i(hi, lo);
            let out = _mm256_or_si256(_mm256_shuffle_epi8(v, shuffle), alpha);
            _mm256_storeu_si256(dst.as_mut_ptr().add(i * 4).cast(), out);
        }
        i += 8;
    }
    if i < n {
        widen_rgb8_to_rgba8_scalar(
            &src[src_off + i * 3..src_off + n * 3],
            &mut dst[i * 4..n * 4],
        );
    }
}

/// The present destination columns of an axis-aligned bilinear draw, as
/// structure-of-arrays tables the row kernels stream through. Present columns
/// (those whose centre maps inside the image) form one interval starting at
/// device column `first_x`; absent columns paint nothing.
struct BilinearColumns {
    first_x: usize,
    /// Byte offset of the floor tap within a source row (`i0 * 3`).
    off0: Vec<i32>,
    /// Byte offset of the ceil tap within a source row (`i1 * 3`, clamped).
    off1: Vec<i32>,
    /// Fractional weight toward the ceil tap (matches `PreparedImage::bilinear`).
    t: Vec<f32>,
    one_minus_t: Vec<f32>,
}

impl BilinearColumns {
    fn len(&self) -> usize {
        self.off0.len()
    }
}

/// The present destination rows of an axis-aligned bilinear draw: the source
/// row pair and vertical weights of each, starting at device row `first_y`.
struct BilinearRows {
    first_y: usize,
    i0: Vec<u32>,
    i1: Vec<u32>,
    t: Vec<f32>,
    one_minus_t: Vec<f32>,
}

impl BilinearRows {
    fn len(&self) -> usize {
        self.i0.len()
    }
}

/// Prepare the column table over device columns `x0..x1`, or `None` when no
/// column centre maps inside the image.
fn bilinear_columns(
    img: &crate::render_cpu::image::PreparedImage,
    x0: usize,
    x1: usize,
) -> Option<BilinearColumns> {
    let w = img.width;
    let last = (w as i64 - 1).max(0);
    let mut cols = BilinearColumns {
        first_x: 0,
        off0: Vec::with_capacity(x1 - x0),
        off1: Vec::with_capacity(x1 - x0),
        t: Vec::with_capacity(x1 - x0),
        one_minus_t: Vec::with_capacity(x1 - x0),
    };
    let mut first = None;
    for x in x0..x1 {
        let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
        if !(0.0..1.0).contains(&u) {
            if first.is_some() {
                break;
            }
            continue;
        }
        first.get_or_insert(x);
        let fx = u * w as f64 - 0.5;
        let x_floor = fx.floor();
        let tx = (fx - x_floor) as f32;
        let ix0 = (x_floor as i64).clamp(0, last);
        let ix1 = (x_floor as i64 + 1).clamp(0, last);
        cols.off0.push((ix0 * 3) as i32);
        cols.off1.push((ix1 * 3) as i32);
        cols.t.push(tx);
        cols.one_minus_t.push(1.0 - tx);
    }
    cols.first_x = first?;
    Some(cols)
}

/// Prepare the row table over device rows `y0..y1` (see [`bilinear_columns`]).
fn bilinear_rows(
    img: &crate::render_cpu::image::PreparedImage,
    y0: usize,
    y1: usize,
) -> Option<BilinearRows> {
    let h = img.height;
    let last = (h as i64 - 1).max(0);
    let mut rows = BilinearRows {
        first_y: 0,
        i0: Vec::with_capacity(y1 - y0),
        i1: Vec::with_capacity(y1 - y0),
        t: Vec::with_capacity(y1 - y0),
        one_minus_t: Vec::with_capacity(y1 - y0),
    };
    let mut first = None;
    for y in y0..y1 {
        let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
        if !(0.0..1.0).contains(&v) {
            if first.is_some() {
                break;
            }
            continue;
        }
        first.get_or_insert(y);
        let fy = (1.0 - v) * h as f64 - 0.5;
        let y_floor = fy.floor();
        let ty = (fy - y_floor) as f32;
        rows.i0.push((y_floor as i64).clamp(0, last) as u32);
        rows.i1.push((y_floor as i64 + 1).clamp(0, last) as u32);
        rows.t.push(ty);
        rows.one_minus_t.push(1.0 - ty);
    }
    rows.first_y = first?;
    Some(rows)
}

/// Fast path for opaque, unmasked, axis-aligned RGB8 magnification / 1:1 with
/// bilinear sampling — the continuous-tone JPEG/JPX case.
///
/// Mirrors [`paint_axis_aligned_rgb8_nearest_opaque`]: source U depends only on
/// device X and V only on Y, so axis tables are prepared once. The filter is
/// separable and is run that way: each *source* row touched is lerped
/// horizontally once into a planar f32 row (`hlerp`), and each destination row
/// lerps its two cached source rows vertically (`vlerp`) and writes opaque
/// premultiplied RGBA. Under magnification a source row serves several
/// destination rows, and even at 1:1 it serves two, so the horizontal work is
/// shared instead of repeated per destination pixel. Every op is the same f32
/// op in the same order as `PreparedImage::bilinear` (horizontal, then
/// vertical, then truncate), so the result is byte-identical to the generic
/// per-pixel sampler.
///
/// When every fractional weight is exactly zero — the image placed at unit
/// scale on an integer translation — the lerps reduce to the floor texel and
/// the draw is a straight 3→4 byte widen of each source row.
///
/// Rows are independent and painted in bands across the rayon pool when the
/// destination is large enough that the parallel overhead is recovered. On
/// x86_64 with AVX2 the row kernels gather and lerp eight columns at a time;
/// the scalar twins are the tested reference.
fn paint_axis_aligned_rgb8_bilinear_opaque(
    img: &crate::render_cpu::image::PreparedImage,
    surface: &mut Surface,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64) {
    let (Some(columns), Some(rows)) = (bilinear_columns(img, x0, x1), bilinear_rows(img, y0, y1))
    else {
        return (0, 0);
    };
    let painted = paint_bilinear_rows(image_kernel(), img, surface, &columns, &rows);
    // Four source taps per painted destination pixel (edge clamps may alias).
    (painted, painted.saturating_mul(4))
}

/// Paint the prepared bilinear tables with `kernel`. Split from
/// [`paint_axis_aligned_rgb8_bilinear_opaque`] so the tests can run every
/// kernel over the same tables and compare the surfaces.
fn paint_bilinear_rows(
    kernel: ImageKernel,
    img: &crate::render_cpu::image::PreparedImage,
    surface: &mut Surface,
    columns: &BilinearColumns,
    rows: &BilinearRows,
) -> u64 {
    let source_stride = img.width as usize * 3;
    let samples: &[u8] = &img.samples;
    let n = columns.len();
    let dst_x = (columns.first_x - surface.origin_x) * 4;

    // The integer-aligned unit-scale draw: `t == 0` everywhere makes every
    // lerp return its floor tap exactly, so the row is a widened copy.
    let unit_blit = columns.t.iter().all(|&t| t == 0.0) && rows.t.iter().all(|&t| t == 0.0);

    let (buf, first_abs_y, stride) = surface.rows_mut_abs(rows.first_y, rows.first_y + rows.len());
    // Align the row table with the clipped buffer window.
    let row_offset = first_abs_y.saturating_sub(rows.first_y);
    let dest_rows = rows
        .len()
        .saturating_sub(row_offset)
        .min(buf.len() / stride.max(1));
    if dest_rows == 0 || n == 0 {
        return 0;
    }
    let buf = &mut buf[..dest_rows * stride];
    let parallel = image_row_parallel_enabled()
        && n.saturating_mul(dest_rows) >= IMAGE_ROW_PAR_PIXEL_THRESHOLD;

    if unit_blit {
        let texels: Vec<u32> = columns.off0.iter().map(|&o| (o / 3) as u32).collect();
        let runs = consecutive_runs(&texels);
        let paint_row = |i: usize, row: &mut [u8]| {
            let base = rows.i0[row_offset + i] as usize * source_stride;
            let dst = &mut row[dst_x..dst_x + n * 4];
            for &(start, len) in &runs {
                let src_off = base + columns.off0[start] as usize;
                widen_rgb8_to_rgba8_opaque(
                    kernel,
                    samples,
                    src_off,
                    &mut dst[start * 4..][..len * 4],
                );
            }
        };
        if parallel {
            buf.par_chunks_mut(stride)
                .enumerate()
                .for_each(|(i, row)| paint_row(i, row));
        } else {
            buf.chunks_exact_mut(stride)
                .enumerate()
                .for_each(|(i, row)| paint_row(i, row));
        }
        return (n * dest_rows) as u64;
    }

    // Each band of destination rows streams its own two-slot cache of
    // horizontally lerped source rows. Bands are the unit of fan-out; serially
    // the whole draw is one band so no source row is lerped twice.
    const BAND_ROWS: usize = 32;
    let band_rows = if parallel { BAND_ROWS } else { dest_rows };
    let paint_band = |band: usize, band_buf: &mut [u8]| {
        let mut cache = HLerpCache::new(n);
        for (i, row) in band_buf.chunks_exact_mut(stride).enumerate() {
            let r = row_offset + band * band_rows + i;
            let (iy0, iy1) = (rows.i0[r], rows.i1[r]);
            let s0 = cache.ensure(iy0, None, |plane| {
                hlerp_row(
                    kernel,
                    samples,
                    iy0 as usize * source_stride,
                    columns,
                    plane,
                )
            });
            let s1 = cache.ensure(iy1, Some(s0), |plane| {
                hlerp_row(
                    kernel,
                    samples,
                    iy1 as usize * source_stride,
                    columns,
                    plane,
                )
            });
            let (p0, p1) = (cache.plane(s0), cache.plane(s1));
            vlerp_row(
                kernel,
                p0,
                p1,
                n,
                rows.t[r],
                rows.one_minus_t[r],
                &mut row[dst_x..dst_x + n * 4],
            );
        }
    };
    if parallel {
        buf.par_chunks_mut(stride * band_rows)
            .enumerate()
            .for_each(|(band, band_buf)| paint_band(band, band_buf));
    } else {
        buf.chunks_mut(stride * band_rows)
            .enumerate()
            .for_each(|(band, band_buf)| paint_band(band, band_buf));
    }
    (n * dest_rows) as u64
}

/// Two horizontally lerped source rows, planar f32 (`[r; n][g; n][b; n]`),
/// keyed by source row. Destination rows walk the source monotonically with
/// step ≤ 1 under magnification, so two slots make every source row's
/// horizontal pass happen once per band.
struct HLerpCache {
    n: usize,
    keys: [Option<u32>; 2],
    planes: [Vec<f32>; 2],
    next_evict: usize,
}

impl HLerpCache {
    fn new(n: usize) -> Self {
        Self {
            n,
            keys: [None, None],
            planes: [vec![0.0; n * 3], vec![0.0; n * 3]],
            next_evict: 0,
        }
    }

    /// The slot holding source row `row`, filling one with `fill` if absent.
    /// `keep` is a slot the caller still needs and must not be evicted.
    fn ensure(&mut self, row: u32, keep: Option<usize>, fill: impl FnOnce(&mut [f32])) -> usize {
        if let Some(slot) = (0..2).find(|&s| self.keys[s] == Some(row)) {
            return slot;
        }
        let mut slot = self.next_evict;
        if keep == Some(slot) {
            slot = 1 - slot;
        }
        fill(&mut self.planes[slot][..self.n * 3]);
        self.keys[slot] = Some(row);
        self.next_evict = 1 - slot;
        slot
    }

    fn plane(&self, slot: usize) -> &[f32] {
        &self.planes[slot][..self.n * 3]
    }
}

/// Horizontal pass of one source row (at byte offset `base`) over the column
/// table, into `plane` (`[r; n][g; n][b; n]`): each lane is
/// `s0 * (1 - t) + s1 * t` in f32, the order `PreparedImage::bilinear` uses.
#[inline]
#[allow(
    unsafe_code,
    reason = "dispatches the AVX2 gather kernel behind a runtime probe; see SAFETY comment"
)]
fn hlerp_row(
    kernel: ImageKernel,
    samples: &[u8],
    base: usize,
    columns: &BilinearColumns,
    plane: &mut [f32],
) {
    match kernel {
        #[cfg(target_arch = "x86_64")]
        ImageKernel::Avx2 => {
            // SAFETY: AVX2 is present (`image_kernel` probed it). The kernel
            // bounds every gather against `samples.len()` itself and takes the
            // scalar path for columns a 4-byte gather would overrun.
            unsafe { hlerp_row_avx2(samples, base, columns, plane) }
        }
        ImageKernel::Scalar => hlerp_row_scalar(samples, base, columns, plane, 0),
    }
}

/// Scalar reference for [`hlerp_row`], from column `start` on.
#[inline]
fn hlerp_row_scalar(
    samples: &[u8],
    base: usize,
    columns: &BilinearColumns,
    plane: &mut [f32],
    start: usize,
) {
    let n = columns.len();
    let (r, rest) = plane.split_at_mut(n);
    let (g, b) = rest.split_at_mut(n);
    for k in start..n {
        let s0 = base + columns.off0[k] as usize;
        let s1 = base + columns.off1[k] as usize;
        let omt = columns.one_minus_t[k];
        let t = columns.t[k];
        r[k] = samples[s0] as f32 * omt + samples[s1] as f32 * t;
        g[k] = samples[s0 + 1] as f32 * omt + samples[s1 + 1] as f32 * t;
        b[k] = samples[s0 + 2] as f32 * omt + samples[s1 + 2] as f32 * t;
    }
}

/// AVX2 horizontal pass: eight columns per iteration, each tap fetched as one
/// 32-bit gather (`[r, g, b, next]`) and split into three f32 lanes. Same
/// mul/mul/add order as the scalar twin, no FMA, so the planes are identical.
///
/// # Safety
/// The CPU must support AVX2. `plane.len() >= 3 * columns.len()`.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[allow(unsafe_code)]
unsafe fn hlerp_row_avx2(
    samples: &[u8],
    base: usize,
    columns: &BilinearColumns,
    plane: &mut [f32],
) {
    use core::arch::x86_64::*;
    let n = columns.len();
    debug_assert!(plane.len() >= n * 3);
    // A gather reads 4 bytes at `base + off`; the row's ceil-tap offsets are
    // non-decreasing, so the columns it may serve are a prefix.
    let avail = samples.len().saturating_sub(base);
    let gather_cols = if avail >= 4 {
        columns.off1.partition_point(|&o| (o as usize) + 4 <= avail)
    } else {
        0
    };
    let byte_mask = _mm256_set1_epi32(0xFF);
    let mut k = 0usize;
    // SAFETY: every index gathered in this loop satisfies
    // `base + off + 4 <= samples.len()` by `gather_cols`; the plane stores are
    // within `plane[..3n]` since `k + 8 <= n`.
    unsafe {
        let row_ptr = samples.as_ptr().add(base).cast::<i32>();
        let (r_out, rest) = plane.split_at_mut(n);
        let (g_out, b_out) = rest.split_at_mut(n);
        // Eight consecutive texels (24 bytes) split into per-channel i32 lanes:
        // two 16-byte loads (the second 12 bytes in, so each 128-bit lane
        // holds four texels) and one in-lane byte shuffle per channel.
        let plane_mask = |c: i8| {
            _mm256_setr_epi8(
                c,
                -1,
                -1,
                -1,
                c + 3,
                -1,
                -1,
                -1,
                c + 6,
                -1,
                -1,
                -1,
                c + 9,
                -1,
                -1,
                -1, //
                c,
                -1,
                -1,
                -1,
                c + 3,
                -1,
                -1,
                -1,
                c + 6,
                -1,
                -1,
                -1,
                c + 9,
                -1,
                -1,
                -1,
            )
        };
        let (mask_r, mask_g, mask_b) = (plane_mask(0), plane_mask(1), plane_mask(2));
        let texel_ramp = _mm256_setr_epi32(0, 3, 6, 9, 12, 15, 18, 21);
        let load_run = |off: i32| {
            let p = samples.as_ptr().add(base + off as usize);
            let v = _mm256_set_m128i(_mm_loadu_si128(p.add(12).cast()), _mm_loadu_si128(p.cast()));
            (
                _mm256_shuffle_epi8(v, mask_r),
                _mm256_shuffle_epi8(v, mask_g),
                _mm256_shuffle_epi8(v, mask_b),
            )
        };
        while k + 8 <= gather_cols {
            let omt = _mm256_loadu_ps(columns.one_minus_t.as_ptr().add(k));
            let t = _mm256_loadu_ps(columns.t.as_ptr().add(k));
            let lerp = |a: __m256i, b: __m256i| {
                let fa = _mm256_cvtepi32_ps(a);
                let fb = _mm256_cvtepi32_ps(b);
                _mm256_add_ps(_mm256_mul_ps(fa, omt), _mm256_mul_ps(fb, t))
            };
            let (o0, o1) = (columns.off0[k], columns.off1[k]);
            let idx0 = _mm256_loadu_si256(columns.off0.as_ptr().add(k).cast());
            let idx1 = _mm256_loadu_si256(columns.off1.as_ptr().add(k).cast());
            // When the eight columns read eight consecutive texels — the 1:1
            // case — both taps are plain loads instead of gathers. The test is
            // per lane: at 1:1 the floor index can also step by zero or two
            // texels where floating-point noise straddles an integer, so a
            // matching span alone would not do. The second lane's load reads
            // 28 bytes from the run's start.
            let consecutive = |idx: __m256i, o: i32| {
                let expected = _mm256_add_epi32(_mm256_set1_epi32(o), texel_ramp);
                _mm256_movemask_epi8(_mm256_cmpeq_epi32(idx, expected)) == -1
            };
            let run = consecutive(idx0, o0)
                && consecutive(idx1, o1)
                && base + o1 as usize + 28 <= samples.len();
            let ((r0, g0, b0), (r1, g1, b1)) = if run {
                (load_run(o0), load_run(o1))
            } else {
                let v0 = _mm256_i32gather_epi32::<1>(row_ptr, idx0);
                let v1 = _mm256_i32gather_epi32::<1>(row_ptr, idx1);
                let split = |v: __m256i| {
                    (
                        _mm256_and_si256(v, byte_mask),
                        _mm256_and_si256(_mm256_srli_epi32::<8>(v), byte_mask),
                        _mm256_and_si256(_mm256_srli_epi32::<16>(v), byte_mask),
                    )
                };
                (split(v0), split(v1))
            };
            _mm256_storeu_ps(r_out.as_mut_ptr().add(k), lerp(r0, r1));
            _mm256_storeu_ps(g_out.as_mut_ptr().add(k), lerp(g0, g1));
            _mm256_storeu_ps(b_out.as_mut_ptr().add(k), lerp(b0, b1));
            k += 8;
        }
    }
    if k < n {
        hlerp_row_scalar(samples, base, columns, plane, k);
    }
}

/// Vertical pass of one destination row: `p0 * (1 - t) + p1 * t` per channel
/// in f32, truncated toward zero, written as opaque RGBA into `dst` (`4n`
/// bytes). The order `PreparedImage::bilinear` uses after its horizontal lerps.
#[inline]
#[allow(
    unsafe_code,
    reason = "dispatches the AVX2 pack kernel behind a runtime probe; see SAFETY comment"
)]
fn vlerp_row(
    kernel: ImageKernel,
    p0: &[f32],
    p1: &[f32],
    n: usize,
    t: f32,
    one_minus_t: f32,
    dst: &mut [u8],
) {
    assert!(p0.len() >= n * 3 && p1.len() >= n * 3 && dst.len() >= n * 4);
    match kernel {
        #[cfg(target_arch = "x86_64")]
        ImageKernel::Avx2 => {
            // SAFETY: AVX2 is present (`image_kernel` probed it); the slice
            // lengths asserted above are the kernel's only precondition.
            unsafe { vlerp_row_avx2(p0, p1, n, t, one_minus_t, dst) }
        }
        ImageKernel::Scalar => vlerp_row_scalar(p0, p1, n, t, one_minus_t, dst, 0),
    }
}

/// Scalar reference for [`vlerp_row`], from column `start` on.
#[inline]
fn vlerp_row_scalar(
    p0: &[f32],
    p1: &[f32],
    n: usize,
    t: f32,
    omt: f32,
    dst: &mut [u8],
    start: usize,
) {
    for k in start..n {
        let out = &mut dst[k * 4..k * 4 + 4];
        out[0] = (p0[k] * omt + p1[k] * t).clamp(0.0, 255.0) as u8;
        out[1] = (p0[n + k] * omt + p1[n + k] * t).clamp(0.0, 255.0) as u8;
        out[2] = (p0[2 * n + k] * omt + p1[2 * n + k] * t).clamp(0.0, 255.0) as u8;
        out[3] = 255;
    }
}

/// AVX2 vertical pass: eight columns per iteration — three planar lerps, a
/// truncating `cvtt` (matching `as u8` on `[0, 255]`), a clamp, and one packed
/// 32-byte RGBA store.
///
/// # Safety
/// The CPU must support AVX2. `p0.len() >= 3n`, `p1.len() >= 3n`,
/// `dst.len() >= 4n`.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[allow(unsafe_code)]
unsafe fn vlerp_row_avx2(p0: &[f32], p1: &[f32], n: usize, t: f32, omt: f32, dst: &mut [u8]) {
    use core::arch::x86_64::*;
    debug_assert!(p0.len() >= n * 3 && p1.len() >= n * 3 && dst.len() >= n * 4);
    let tv = _mm256_set1_ps(t);
    let omtv = _mm256_set1_ps(omt);
    let zero = _mm256_setzero_si256();
    let max = _mm256_set1_epi32(255);
    let alpha = _mm256_set1_epi32(0xFF00_0000u32 as i32);
    let mut k = 0usize;
    // SAFETY: every load reads `[k, k + 8)` of a plane channel with
    // `k + 8 <= n`, within the asserted lengths; the store writes
    // `dst[4k..4k + 32]`, within `4n`.
    unsafe {
        while k + 8 <= n {
            let channel = |c: usize| {
                let a = _mm256_loadu_ps(p0.as_ptr().add(c * n + k));
                let b = _mm256_loadu_ps(p1.as_ptr().add(c * n + k));
                let v = _mm256_add_ps(_mm256_mul_ps(a, omtv), _mm256_mul_ps(b, tv));
                let i = _mm256_cvttps_epi32(v);
                _mm256_min_epi32(_mm256_max_epi32(i, zero), max)
            };
            let r = channel(0);
            let g = _mm256_slli_epi32::<8>(channel(1));
            let b = _mm256_slli_epi32::<16>(channel(2));
            let px = _mm256_or_si256(_mm256_or_si256(r, g), _mm256_or_si256(b, alpha));
            _mm256_storeu_si256(dst.as_mut_ptr().add(k * 4).cast(), px);
            k += 8;
        }
    }
    if k < n {
        vlerp_row_scalar(p0, p1, n, t, omt, dst, k);
    }
}

/// Fast path for an opaque, unmasked, axis-aligned RGB8 image being
/// area-minified. The minification twin of `paint_axis_aligned_rgb8_nearest_opaque`:
/// each destination pixel averages the inclusive source-texel box that
/// `image.rs::area_average` computes, then — the image being fully opaque — the
/// averaged RGB is written straight to the surface (opaque source-over is a
/// copy), skipping the generic path's per-pixel float shade dispatch, `/Decode`,
/// mask tests, `average_rgba`, and blend.
///
/// Source X boxes are prepared once per destination column and Y boxes once per
/// row. The dispatch gate requires exactly-zero off-diagonal inverse terms, so
/// `u = inv.a·dx + inv.e` and `v = inv.d·dy + inv.f` equal the generic path's
/// `inv.apply` bit-for-bit (adding `inv.c·dy = 0.0` / `inv.b·dx = 0.0` is the
/// identity on a finite float). The box bounds, the uniform-weight sum, and the
/// integer-truncating divide all mirror `area_average` exactly, so the output is
/// byte-for-byte identical to the generic path. Returns `(painted, taps)` where
/// `taps` is the summed box area, matching `image.source_sample_taps`.
fn paint_axis_aligned_rgb8_area_min_opaque(
    img: &crate::render_cpu::image::PreparedImage,
    surface: &mut Surface,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64) {
    // RGB8 source samples are already the exact output component representation.
    area_min_box_average_opaque(img, surface, &img.samples, x0, y0, x1, y1)
}

/// Area-minify an opaque axis-aligned CMYK image. The source is converted to
/// packed RGB8 **once** (each pixel through the identical `cmyk_to_rgb`/`to_u8`
/// as the generic `pixel()`), then box-averaged like the RGB8 path. This is
/// byte-identical to the generic convert-each-tap-then-average, but the
/// conversion is hoisted out of the per-destination-pixel loop. `None` (→ the
/// caller keeps the generic path) if the source is not convertible or too large.
fn paint_axis_aligned_cmyk_area_min_opaque(
    img: &crate::render_cpu::image::PreparedImage,
    surface: &mut Surface,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> Option<(u64, u64)> {
    let rgb = img.cmyk_source_as_rgb8()?;
    Some(area_min_box_average_opaque(
        img, surface, &rgb, x0, y0, x1, y1,
    ))
}

/// The bilevel cut-out a minified RGB8 draw carries. MRC producers write one of
/// two encodings: a grayscale `/SMask` coverage layer whose alpha is
/// box-filtered with the base image, or a hard `/Mask` stencil that is
/// point-sampled all-or-nothing. Both are JBIG2 in practice.
#[derive(Clone, Copy)]
enum AreaMinMask<'a> {
    /// A one-bit `/SMask`, box-filtered by packed popcount.
    Soft(&'a crate::page_ir::ImageSMask),
    /// An eight-bit `/SMask` (a cover's transparency layer), box-filtered in
    /// f64 exactly as the generic sampler does.
    Soft8(&'a crate::page_ir::ImageSMask),
    Stencil(&'a crate::page_ir::ImageSMask),
}

/// Classify `img`'s mask for the axis-aligned area-minification fast path, or
/// `None` to keep the generic per-pixel path.
fn area_min_mask(img: &crate::render_cpu::image::PreparedImage) -> Option<AreaMinMask<'_>> {
    if let Some(sm) = img.smask.as_deref() {
        // `sample_smask` only box-filters at all when the mask minifies on an
        // axis; point-sampled masks are not what this path reproduces. Its
        // packed-bit branch is reproduced at 1 bpc, its multi-bit branch at
        // 8 bpc over a complete byte-per-texel buffer.
        let footprint = img.smask_footprint(sm);
        let minified = sm.width > 0 && sm.height > 0 && (footprint[0] > 1.0 || footprint[1] > 1.0);
        if !minified {
            return None;
        }
        return match sm.bits_per_component {
            1 => Some(AreaMinMask::Soft(sm)),
            8 if sm.samples.len() >= sm.width as usize * sm.height as usize => {
                Some(AreaMinMask::Soft8(sm))
            }
            _ => None,
        };
    }
    match img.mask.as_ref()? {
        // A colour-key mask tests the base image's own samples, not an
        // independent bitmap, so it does not separate per axis.
        crate::page_ir::ImageMask::ColorKey(_) => None,
        crate::page_ir::ImageMask::Stencil(sm) => {
            (sm.width > 0 && sm.height > 0).then_some(AreaMinMask::Stencil(sm))
        }
    }
}

/// The prepared mask lookup for one destination column or row.
#[derive(Clone, Copy)]
enum MaskAxis {
    /// Box-filter taps into a one-bit `/SMask`.
    Taps(crate::render_cpu::image::AxisTaps),
    /// The point-sampled texel index of a hard `/Mask` stencil.
    Texel(u32),
}

/// Area-minify an axis-aligned opaque RGB8 image cut out by a mask — the MRC
/// scanned-page shape (a JPX foreground over a JPX background, cut out by a
/// JBIG2 layer sharing the foreground's placement) and the cover-image shape
/// (a Flate RGB/palette image under an eight-bit transparency layer).
///
/// The generic per-pixel loop recomputes, for every destination pixel, the
/// inverse map, the base image's two box-filter tap ranges, and the mask's own
/// per-axis lookup. With `inv.b == inv.c == 0` every one of those depends only
/// on the destination column (X) or row (Y), so they are prepared once each
/// here. What remains per pixel — the weighted box average, the mask's
/// coverage or stencil test, the `/Decode` remap, and the source-over
/// composite — is the generic path's arithmetic term for term, so the painted
/// pixels are unchanged.
// Called once per draw, and large enough (two prepared axis passes, the box
// average, both mask encodings, and the generic border fallback) that inlining
// it into `paint_image` measurably degrades the *sibling* fast paths' codegen —
// the unmasked JPX scan lost 37 % of its raster time to the bloat before this.
#[inline(never)]
fn paint_axis_aligned_rgb8_area_min_masked(
    img: &crate::render_cpu::image::PreparedImage,
    mask: AreaMinMask<'_>,
    surface: &mut Surface,
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64) {
    let stride = img.width as usize * 3;
    let rgb: &[u8] = &img.samples;
    // `edge_coverage` returns `None` — provably interior, full weight — exactly
    // when the mapped pixel square stays inside the unit square on both axes.
    // With `inv.b == inv.c == 0` that test separates, so the interior is a
    // rectangle of whole destination columns and rows: the prepared body runs
    // there, and the border band keeps the generic per-pixel
    // treatment. The draw therefore stays pixel-identical, edges included.
    let half_u = 0.5 * img.inv.a.abs();
    let half_v = 0.5 * img.inv.d.abs();
    let mask_footprint = match mask {
        AreaMinMask::Soft(sm) | AreaMinMask::Soft8(sm) => img.smask_footprint(sm),
        AreaMinMask::Stencil(_) => [0.0, 0.0],
    };

    // Per destination column: whether it is interior in u, the base image's X
    // tap box, and the mask's X lookup.
    let mut columns: Vec<(bool, Option<(crate::render_cpu::image::AxisTaps, MaskAxis)>)> =
        Vec::with_capacity(x1 - x0);
    for x in x0..x1 {
        let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
        let interior = u >= half_u && u <= 1.0 - half_u;
        if !(0.0..1.0).contains(&u) {
            columns.push((interior, None));
            continue;
        }
        let base = img.box_taps_x(u * img.width as f64 - 0.5);
        let axis = match mask {
            AreaMinMask::Soft(sm) | AreaMinMask::Soft8(sm) => {
                crate::render_cpu::image::PreparedImage::smask_box_taps(
                    u * sm.width as f64 - 0.5,
                    mask_footprint[0],
                    sm.width,
                )
                .map(MaskAxis::Taps)
            }
            AreaMinMask::Stencil(sm) => Some(MaskAxis::Texel(
                crate::render_cpu::image::stencil_col(sm, u),
            )),
        };
        columns.push((interior, base.zip(axis)));
    }

    // Per destination row, the same.
    let mut rows: Vec<(bool, Option<(crate::render_cpu::image::AxisTaps, MaskAxis)>)> =
        Vec::with_capacity(y1 - y0);
    for y in y0..y1 {
        let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
        let interior = v >= half_v && v <= 1.0 - half_v;
        if !(0.0..1.0).contains(&v) {
            rows.push((interior, None));
            continue;
        }
        let base = img.box_taps_y((1.0 - v) * img.height as f64 - 0.5);
        let axis = match mask {
            AreaMinMask::Soft(sm) | AreaMinMask::Soft8(sm) => {
                crate::render_cpu::image::PreparedImage::smask_box_taps(
                    (1.0 - v) * sm.height as f64 - 0.5,
                    mask_footprint[1],
                    sm.height,
                )
                .map(MaskAxis::Taps)
            }
            AreaMinMask::Stencil(sm) => Some(MaskAxis::Texel(
                crate::render_cpu::image::stencil_row(sm, v),
            )),
        };
        rows.push((interior, base.zip(axis)));
    }

    let output_origin = surface.origin_x;
    let dest_w = x1 - x0;
    let dest_h = y1 - y0;
    let columns = columns.as_slice();
    // The alpha a soft mask yields over a box whose texels are all clear or
    // all set. Both coverages are exact in either filter (see
    // `MaskRowSummary`), so these are the bytes the per-tap filter produces.
    let (alpha_clear, alpha_set) = match mask {
        AreaMinMask::Soft(sm) | AreaMinMask::Soft8(sm) => (
            (255.0 * crate::render_cpu::image::apply_smask_decode(sm, 0.0)) as u8,
            (255.0 * crate::render_cpu::image::apply_smask_decode(sm, 1.0)) as u8,
        ),
        AreaMinMask::Stencil(_) => (0, 0),
    };
    // The prepared body: the columns that are interior and map into the
    // image. `u` is monotonic in `x`, so they are one run; its base and mask
    // taps are kept compact, apart from the column table. Every other column
    // is the border band, painted generically.
    let body = body_run(
        columns
            .iter()
            .map(|&(interior, axes)| interior && axes.is_some()),
    );
    let (body_start, body_end) = body.unwrap_or((0, 0));
    let (body_taps, body_masks): (Vec<crate::render_cpu::image::AxisTaps>, Vec<MaskAxis>) = columns
        [body_start..body_end]
        .iter()
        .filter_map(|&(_, axes)| axes)
        .unzip();
    let border_cols: Vec<usize> = (0..columns.len())
        .filter(|x| !(body_start..body_end).contains(x))
        .collect();
    let border_cols = border_cols.as_slice();
    // The body's soft-mask texel span, to test a whole row's boxes for clear
    // at once, and its summed tap widths for the tap telemetry.
    let body_mask_span = body_masks.iter().fold(None, |span, mx| match (span, mx) {
        (None, MaskAxis::Taps(m)) => Some((m.lo, m.hi)),
        (Some((lo, hi)), MaskAxis::Taps(m)) => Some((m.lo.min(lo), m.hi.max(hi))),
        (span, MaskAxis::Texel(_)) => span,
    });
    let body_col_taps: u64 = body_taps.iter().map(|t| (t.hi - t.lo + 1) as u64).sum();
    // Whether the body's soft-mask boxes advance with x (an unmirrored draw;
    // `u` is monotonic in `x`, so a mirrored one descends). The alpha pass
    // skips clear runs only in that order.
    let masks_ascending = body_masks.windows(2).all(|pair| match (pair[0], pair[1]) {
        (MaskAxis::Taps(a), MaskAxis::Taps(b)) => a.lo <= b.lo,
        _ => false,
    });

    // A border-band pixel, or one whose center maps outside the image: the
    // generic per-pixel treatment, minus the clip and soft-clip terms this
    // path's eligibility already excluded. Returns whether it painted.
    let paint_generic = |x: usize, y: usize, px: &mut [u8]| -> bool {
        let (dx, dy) = (x as f64 + 0.5, y as f64 + 0.5);
        let edge = img.edge_coverage(dx, dy);
        if edge == Some(0) {
            return false;
        }
        let color = match edge {
            None => img.shade(dx, dy),
            Some(_) => img.shade_clamped(dx, dy),
        };
        let Some(color) = color else { return false };
        let cov = match edge {
            Some(ec) => mul_div_255(255, ec),
            None => 255,
        };
        let a = mul_div_255(color[3] as u16, cov);
        if a == 0 {
            return false;
        }
        composite_px_blended(
            px,
            [color[0], color[1], color[2]],
            a as u8,
            BlendChoice::Normal,
        );
        true
    };

    // The row filter: a body row with many visible pixels (a cover under a
    // mostly opaque layer) is box-averaged a whole row at a time, a sparse
    // one (a scanned page's foreground layer) per visible pixel. Both are
    // exact, so the choice is only about speed.
    let max_row_total = rows
        .iter()
        .filter_map(|&(_, axes)| axes.map(|(ty, _)| ty.total))
        .max();
    let template = max_row_total
        .filter(|_| !body_taps.is_empty())
        .and_then(|rt| RowBoxFilter::new(rgb, stride, &body_taps, rt));

    let (output, first_output_y, output_stride) = surface.rows_mut_abs(y0, y1);
    // Align the row table with the clipped output window.
    let row_offset = first_output_y.saturating_sub(y0);
    let row_slice = rows.get(row_offset..).unwrap_or(&[]);

    // One band of destination rows: reads only its own base/mask source rows
    // and writes only its own output rows, so bands are independent and the
    // per-pixel arithmetic is untouched by how they are scheduled.
    let paint_band = |first_y: usize,

                      band: &mut [u8],
                      band_rows: &[(
        bool,
        Option<(crate::render_cpu::image::AxisTaps, MaskAxis)>,
    )]|

     -> (u64, u64) {
        let mut painted = 0u64;
        let mut taps = 0u64;
        let mut filter = template.as_ref().map(RowBoxFilter::fresh);
        let mut alphas = vec![0u8; body_taps.len()];
        let mut colors = vec![0u8; body_taps.len() * 4];
        for (i, (row, &(row_interior, row_axes))) in band
            .chunks_exact_mut(output_stride)
            .zip(band_rows)
            .enumerate()
        {
            let y = first_y + i;
            // The union and intersection of the soft-mask rows this row's
            // boxes span, so a box that is uniformly clear or set — most of a
            // scanned page's foreground mask, most of a cover's opacity layer
            // — is classified without its per-tap filter.
            let summary = match (mask, row_axes) {
                (AreaMinMask::Soft(sm), Some((_, MaskAxis::Taps(mty)))) => {
                    Some(MaskRowSummary::bits(sm, &mty))
                }
                (AreaMinMask::Soft8(sm), Some((_, MaskAxis::Taps(mty)))) => {
                    Some(MaskRowSummary::bytes(sm, &mty))
                }
                _ => None,
            };
            // The one-bit mask rows this row's boxes span, with their bit
            // offsets and weights laid out once for the mixed-box filter.
            let mask_rows = match (mask, row_axes) {
                (AreaMinMask::Soft(sm), Some((_, MaskAxis::Taps(mty)))) => {
                    BilevelMaskRows::new(sm, &mty)
                }
                _ => None,
            };
            // Every body box of this row clear, and clear means transparent
            // (no inverting `/Decode`): the body paints nothing, so only the
            // border band remains — the blank lines and margins of a scanned
            // page's foreground layer cost one scan of the mask union.
            if alpha_clear == 0
                && row_interior
                && let (Some(summary), Some((ty, _)), Some((lo, hi))) =
                    (&summary, row_axes, body_mask_span)
                && summary.clear_over(lo, hi)
            {
                taps += body_col_taps * (ty.hi - ty.lo + 1) as u64;
                for &local_x in border_cols {
                    let x = x0 + local_x;
                    if paint_generic(x, y, &mut row[(x - output_origin) * 4..][..4]) {
                        painted += 1;
                    }
                }
                continue;
            }

            // The border band, generically.
            for &local_x in border_cols {
                let x = x0 + local_x;
                if paint_generic(x, y, &mut row[(x - output_origin) * 4..][..4]) {
                    painted += 1;
                }
            }
            let (Some((ty, my)), true) = (row_axes, row_interior && !body_taps.is_empty()) else {
                // Not a body row: the body columns are generic too.
                for x in x0 + body_start..x0 + body_end {
                    if paint_generic(x, y, &mut row[(x - output_origin) * 4..][..4]) {
                        painted += 1;
                    }
                }
                continue;
            };
            taps += body_col_taps * (ty.hi - ty.lo + 1) as u64;

            // Pass 1: each body pixel's mask alpha, first — a transparent
            // pixel skips the box average.
            //
            // A scanned page's foreground mask is clear over most of every
            // row, so the pass walks the union row's set texels: every box
            // that ends before the next set texel is clear, and a whole run
            // of them takes one fill instead of a window test each. Only a
            // box that reaches a set texel is classified per column. The
            // alpha of a clear box is `alpha_clear` either way (a clear
            // window is `uniform == Some(false)`; a box too wide to test
            // filters to coverage 0.0, which decodes to the same byte), so
            // the row's alphas are unchanged.
            let mut visible = 0usize;
            // The first set texel at or after the last queried `lo`, once
            // known; valid for every later box because `lo` only grows.
            let mut next_set: Option<Option<usize>> = None;
            let mut k = 0usize;
            while k < body_masks.len() {
                let mx = body_masks[k];
                if masks_ascending && let (Some(s), MaskAxis::Taps(mtx)) = (&summary, mx) {
                    let lo = mtx.lo as usize;
                    let ns = match next_set {
                        Some(ns) if ns.is_none_or(|p| p >= lo) => ns,
                        _ => {
                            let ns = s.next_set(lo);
                            next_set = Some(ns);
                            ns
                        }
                    };
                    let run_end = match ns {
                        // No set texel from here on: every remaining box is
                        // clear.
                        None => body_masks.len(),
                        Some(p) if p > mtx.hi as usize => {
                            // Every box ending before `p` is clear.
                            k + body_masks[k..]
                                .iter()
                                .take_while(
                                    |m| matches!(m, MaskAxis::Taps(t) if (t.hi as usize) < p),
                                )
                                .count()
                        }
                        Some(_) => k,
                    };
                    if run_end > k {
                        alphas[k..run_end].fill(alpha_clear);
                        if alpha_clear != 0 {
                            visible += run_end - k;
                        }
                        k = run_end;
                        continue;
                    }
                }
                let a = &mut alphas[k];
                k += 1;
                // After the run walk the box is known to reach a set texel,
                // so only the all-set test remains of the uniform check.
                let known_set = masks_ascending && next_set.is_some();
                let uniform = summary.as_ref().and_then(|s| match mx {
                    MaskAxis::Taps(mtx) if known_set => s.all_set(&mtx).then_some(true),
                    MaskAxis::Taps(mtx) => s.uniform(&mtx),
                    MaskAxis::Texel(_) => None,
                });
                let alpha = match (mask, mx, my) {
                    _ if uniform.is_some() => {
                        if uniform == Some(true) {
                            alpha_set
                        } else {
                            alpha_clear
                        }
                    }
                    (AreaMinMask::Soft(sm), MaskAxis::Taps(mtx), MaskAxis::Taps(mty)) => {
                        let coverage = match &mask_rows {
                            Some(rows) if mtx.hi - mtx.lo < 57 => {
                                bilevel_coverage_prepared(sm, rows, &mtx)
                            }
                            _ => bilevel_smask_coverage_windowed(sm, &mtx, &mty),
                        };
                        (255.0 * crate::render_cpu::image::apply_smask_decode(sm, coverage)) as u8
                    }
                    (AreaMinMask::Soft8(sm), MaskAxis::Taps(mtx), MaskAxis::Taps(mty)) => {
                        let coverage =
                            crate::render_cpu::image::gray8_smask_coverage(sm, &mtx, &mty);
                        (255.0 * crate::render_cpu::image::apply_smask_decode(sm, coverage)) as u8
                    }
                    (AreaMinMask::Stencil(sm), MaskAxis::Texel(col), MaskAxis::Texel(srow)) => {
                        if crate::render_cpu::image::stencil_hides_at(sm, col, srow) {
                            0
                        } else {
                            255
                        }
                    }
                    // The axis kinds are built from `mask` above, so the mixed
                    // combinations cannot occur.
                    _ => 0,
                };
                *a = alpha;
                visible += (alpha != 0) as usize;
            }
            if visible == 0 {
                continue;
            }

            // Pass 2: colour and composite the visible body pixels — a dense
            // row through the row filter, a sparse one pixel by pixel.
            let dense = visible * 2 >= body_taps.len()
                && filter
                    .as_mut()
                    .is_some_and(|f| f.average_row(&ty, &mut colors));
            let body_row = &mut row[(x0 + body_start - output_origin) * 4..];
            for (k, ((&alpha, tx), px)) in alphas
                .iter()
                .zip(&body_taps)
                .zip(body_row.chunks_exact_mut(4))
                .enumerate()
            {
                if alpha == 0 {
                    continue;
                }
                let color = if dense {
                    [colors[k * 4], colors[k * 4 + 1], colors[k * 4 + 2]]
                } else {
                    rgb8_box_average(rgb, stride, tx, &ty, tx.total * ty.total)
                };
                composite_px_blended(px, color, alpha, BlendChoice::Normal);
                painted += 1;
            }
        }
        (painted, taps)
    };

    let parallel = image_row_parallel_enabled()
        && dest_w.saturating_mul(dest_h) >= IMAGE_ROW_PAR_PIXEL_THRESHOLD;
    if parallel {
        const BAND: usize = 32;
        output
            .par_chunks_mut(output_stride * BAND)
            .zip(row_slice.par_chunks(BAND))
            .enumerate()
            .map(|(i, (band, rows))| paint_band(first_output_y + i * BAND, band, rows))
            .reduce(|| (0, 0), |a, b| (a.0 + b.0, a.1 + b.1))
    } else {
        paint_band(first_output_y, output, row_slice)
    }
}

/// Core of the opaque axis-aligned area-minification fast paths. `rgb` is a
/// packed `width*height*3` RGB8 view of the source (the samples themselves for
/// an RGB image; a converted buffer for CMYK). Prepares per-column source X
/// boxes and per-row Y boxes, then box-averages each destination pixel exactly
/// as `image.rs::area_average` does and writes it opaque.
fn area_min_box_average_opaque(
    img: &crate::render_cpu::image::PreparedImage,
    surface: &mut Surface,
    rgb: &[u8],
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize,
) -> (u64, u64) {
    let stride = img.width as usize * 3;

    let mut source_columns: Vec<Option<crate::render_cpu::image::AxisTaps>> =
        Vec::with_capacity(x1 - x0);
    for x in x0..x1 {
        let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
        if !(0.0..1.0).contains(&u) {
            source_columns.push(None);
            continue;
        }
        let fx = u * img.width as f64 - 0.5;
        source_columns.push(img.box_taps_x(fx));
    }

    let mut source_rows: Vec<Option<crate::render_cpu::image::AxisTaps>> =
        Vec::with_capacity(y1 - y0);
    for y in y0..y1 {
        let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
        if !(0.0..1.0).contains(&v) {
            source_rows.push(None);
            continue;
        }
        let fy = (1.0 - v) * img.height as f64 - 0.5;
        source_rows.push(img.box_taps_y(fy));
    }

    let output_origin = surface.origin_x;
    let dest_w = x1 - x0;
    let dest_h = y1 - y0;
    let columns = source_columns.as_slice();

    // The columns that map into the image form one run (u is monotonic in x);
    // the row filter serves it whole.
    let body = body_run(columns.iter().map(Option::is_some));
    let body_taps: Option<Vec<crate::render_cpu::image::AxisTaps>> =
        body.map(|(bx0, bx1)| columns[bx0..bx1].iter().flatten().copied().collect());
    let max_row_total = source_rows.iter().flatten().map(|t| t.total).max();
    let filter_template = body_taps
        .as_deref()
        .zip(max_row_total)
        .and_then(|(cols, rt)| RowBoxFilter::new(rgb, stride, cols, rt));
    if let (Some(template), Some((bx0, _))) = (&filter_template, body) {
        let cols = template.cols;
        let col_span: u64 = cols.iter().map(|t| (t.hi - t.lo + 1) as u64).sum();
        let (output, first_output_y, output_stride) = surface.rows_mut_abs(y0, y1);
        let row_offset = first_output_y.saturating_sub(y0);
        let row_slice = source_rows.get(row_offset..).unwrap_or(&[]);
        let first_target = (x0 + bx0 - output_origin) * 4;
        // One band of destination rows with its own row cache; bands are
        // independent, and each row's bytes do not depend on the cache.
        let paint_band =
            |band: &mut [u8], band_rows: &[Option<crate::render_cpu::image::AxisTaps>]| {
                let mut filter = template.fresh();
                let (mut painted, mut taps) = (0u64, 0u64);
                for (row, ty) in band.chunks_exact_mut(output_stride).zip(band_rows) {
                    let Some(ty) = ty else { continue };
                    if !filter.average_row(ty, &mut row[first_target..]) {
                        for (x, tx) in cols.iter().enumerate() {
                            let c = rgb8_box_average(rgb, stride, tx, ty, tx.total * ty.total);
                            let t = first_target + x * 4;
                            row[t..t + 4].copy_from_slice(&[c[0], c[1], c[2], 255]);
                        }
                    }
                    painted += cols.len() as u64;
                    taps += col_span * (ty.hi - ty.lo + 1) as u64;
                }
                (painted, taps)
            };
        let parallel = image_row_parallel_enabled()
            && dest_w.saturating_mul(dest_h) >= IMAGE_ROW_PAR_PIXEL_THRESHOLD;
        return if parallel {
            const BAND: usize = 32;
            output
                .par_chunks_mut(output_stride * BAND)
                .zip(row_slice.par_chunks(BAND))
                .map(|(band, rows)| paint_band(band, rows))
                .reduce(|| (0, 0), |a, b| (a.0 + b.0, a.1 + b.1))
        } else {
            paint_band(output, row_slice)
        };
    }

    // One destination row: reads only its own source rows and writes only its
    // own output row, so rows are independent and the per-pixel arithmetic is
    // untouched by how they are scheduled.
    let paint_row =
        |row_taps: &Option<crate::render_cpu::image::AxisTaps>, row: &mut [u8]| -> (u64, u64) {
            let Some(ty) = *row_taps else {
                return (0, 0);
            };
            let mut painted = 0u64;
            let mut taps = 0u64;
            for (local_x, col_taps) in columns.iter().enumerate() {
                let Some(tx) = *col_taps else { continue };
                let weight = tx.total * ty.total;
                if weight == 0 {
                    continue;
                }
                let color = rgb8_box_average(rgb, stride, &tx, &ty, weight);
                let target = (x0 + local_x - output_origin) * 4;
                row[target..target + 4].copy_from_slice(&[color[0], color[1], color[2], 255]);
                painted += 1;
                taps += (tx.hi - tx.lo + 1) as u64 * (ty.hi - ty.lo + 1) as u64;
            }
            (painted, taps)
        };

    let (output, first_output_y, output_stride) = surface.rows_mut_abs(y0, y1);
    // Align the row table with the clipped output window.
    let row_offset = first_output_y.saturating_sub(y0);
    let row_slice = source_rows.get(row_offset..).unwrap_or(&[]);

    // Same fan-out policy as the sibling bilinear fast path: below this many
    // destination pixels the rayon scheduling costs more than it saves.
    let parallel = image_row_parallel_enabled()
        && dest_w.saturating_mul(dest_h) >= IMAGE_ROW_PAR_PIXEL_THRESHOLD;
    let (painted, taps) = if parallel {
        output
            .par_chunks_mut(output_stride)
            .zip(row_slice.par_iter())
            .map(|(row, ty)| paint_row(ty, row))
            .reduce(|| (0, 0), |a, b| (a.0 + b.0, a.1 + b.1))
    } else {
        output
            .chunks_exact_mut(output_stride)
            .zip(row_slice.iter())
            .map(|(row, ty)| paint_row(ty, row))
            .fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1))
    };
    (painted, taps)
}

/// Weighted box average of a packed RGB8 source over one destination pixel's
/// prepared tap boxes: per channel `(Σ wy·wx·texel + weight/2) / weight`,
/// clamped to 255 — the integer arithmetic of `PreparedImage::area_average`'s
/// RGB8 branch, tap for tap. `weight` is `tx.total * ty.total` (non-zero, the
/// caller's check).
#[inline(always)]
fn rgb8_box_average(
    rgb: &[u8],
    stride: usize,
    tx: &crate::render_cpu::image::AxisTaps,
    ty: &crate::render_cpu::image::AxisTaps,
    weight: u64,
) -> [u8; 3] {
    let (mut a0, mut a1, mut a2) = (0u64, 0u64, 0u64);
    for sr in ty.lo..=ty.hi {
        let wy = ty.weight_at(sr);
        let base = sr as usize * stride + tx.lo as usize * 3;
        let end = sr as usize * stride + (tx.hi as usize + 1) * 3;
        for (col, texel) in (tx.lo..).zip(rgb[base..end].chunks_exact(3)) {
            let w = wy * tx.weight_at(col);
            a0 += w * texel[0] as u64;
            a1 += w * texel[1] as u64;
            a2 += w * texel[2] as u64;
        }
    }
    [
        ((a0 + weight / 2) / weight).min(255) as u8,
        ((a1 + weight / 2) / weight).min(255) as u8,
        ((a2 + weight / 2) / weight).min(255) as u8,
    ]
}

/// The single run of `true` in `flags` as `(start, end)`, or `None` when
/// there is none or more than one.
fn body_run(flags: impl Iterator<Item = bool>) -> Option<(usize, usize)> {
    let mut run: Option<(usize, usize)> = None;
    for (i, flag) in flags.enumerate() {
        if !flag {
            continue;
        }
        run = match run {
            None => Some((i, i + 1)),
            Some((start, end)) if end == i => Some((start, i + 1)),
            Some(_) => return None,
        };
    }
    run
}

/// An exact box filter that averages a whole destination row at once over a
/// contiguous run of destination columns (`cols`, their prepared X taps).
///
/// The per-pixel filter sums `Σ_rows wy · Σ_cols wx · texel` for every
/// destination pixel and divides three times; the rows of one destination row
/// share their row weights, and neighbouring destination rows share most of
/// their source rows. Here each source row's horizontal sums `Σ wx · texel`
/// are computed once per band of destination rows and cached; a destination
/// row is then a weighted sum of a few cached rows and one division per
/// channel, both over contiguous planar arrays the compiler vectorises.
///
/// The arithmetic is carried in `f64` but every value in it is an integer:
/// the horizontal sums, the products with a row weight and their sums stay
/// below 2⁴⁹ (the constructor requires `tx.total · ty.total < 2⁴⁰`, and a
/// texel is at most 255), so all of them are exact, and the sums are the
/// per-pixel filter's `u64` sums regrouped — integer addition is
/// associative. The rounding division `(acc + ⌊w/2⌋) / w`, truncated, is the
/// integer floor: an IEEE quotient is correctly rounded, the quotient is
/// below 256 where the rounding error is under 2⁻⁴⁶, and a quotient that is
/// not an integer is at least `1/w > 2⁻⁴⁰` from the next one, so truncation
/// never crosses an integer. The bytes are the per-pixel filter's.
struct RowBoxFilter<'a> {
    rgb: &'a [u8],
    stride: usize,
    cols: &'a [crate::render_cpu::image::AxisTaps],
    /// `tx.total` per column.
    col_total: Vec<f64>,
    /// When every box is at most four texels wide: per column, the byte
    /// offsets of four texels within a source row and their weights, the
    /// absent ones weighted zero (and pointed at a texel that exists), and
    /// how many of the four the widest box uses. Otherwise empty, and the
    /// horizontal pass sums each box's taps in a loop.
    taps4: Vec<([usize; 4], [u32; 4])>,
    taps_used: usize,
    /// Cached horizontal passes: `(source row, last use, R | G | B planes)`.
    slots: Vec<(u32, u64, Vec<f64>)>,
    clock: u64,
    /// The weighted sums of the current destination row, planar.
    acc: Vec<f64>,
    kernel: ImageKernel,
}

impl<'a> RowBoxFilter<'a> {
    /// Tallest box the filter serves; a taller one (a minification of more
    /// than ~15× on Y) is left to the per-pixel filter.
    const MAX_ROWS: usize = 16;

    /// `None` when a box's total weight could leave the exact range, or the
    /// run is empty. `max_row_total` bounds `ty.total` over the rows served.
    fn new(
        rgb: &'a [u8],
        stride: usize,
        cols: &'a [crate::render_cpu::image::AxisTaps],
        max_row_total: u64,
    ) -> Option<Self> {
        let max_col_total = cols.iter().map(|t| t.total).max()?;
        if max_col_total.checked_mul(max_row_total)? >= 1 << 40 {
            return None;
        }
        let n = cols.len();
        let taps_used = cols.iter().map(|t| (t.hi - t.lo) as usize + 1).max()?;
        let taps4 = if taps_used <= 4 {
            cols.iter()
                .map(|t| {
                    let (lo, span) = (t.lo as usize, (t.hi - t.lo) as usize);
                    let mut offsets = [lo * 3; 4];
                    let mut weights = [0u32; 4];
                    for (k, (o, w)) in offsets.iter_mut().zip(&mut weights).enumerate() {
                        if k <= span {
                            *o = (lo + k) * 3;
                            *w = t.weight_at((lo + k) as u32) as u32;
                        }
                    }
                    (offsets, weights)
                })
                .collect()
        } else {
            Vec::new()
        };
        Some(Self {
            rgb,
            stride,
            cols,
            col_total: cols.iter().map(|t| t.total as f64).collect(),
            taps4,
            taps_used,
            slots: Vec::new(),
            clock: 0,
            acc: vec![0.0; 3 * n],
            kernel: image_kernel(),
        })
    }

    /// The same filter with an empty row cache, for another band of rows.
    fn fresh(&self) -> Self {
        Self {
            rgb: self.rgb,
            stride: self.stride,
            cols: self.cols,
            col_total: self.col_total.clone(),
            taps4: self.taps4.clone(),
            taps_used: self.taps_used,
            slots: Vec::new(),
            clock: 0,
            acc: vec![0.0; self.acc.len()],
            kernel: self.kernel,
        }
    }

    /// `Σ wx · texel` of source row `row` for every column, planar.
    fn horizontal(&self, row: u32, planes: &mut [f64]) {
        let n = self.cols.len();
        let (r, rest) = planes.split_at_mut(n);
        let (g, b) = rest.split_at_mut(n);
        let row_base = row as usize * self.stride;
        let src = &self.rgb[row_base..row_base + self.stride];
        // Weights are at most `S` and texels 255, so four products fit `u32`;
        // the absent taps add `0 · texel`. The tap count is fixed per draw so
        // the loop body is straight-line code.
        let fixed = |taps: usize, r: &mut [f64], g: &mut [f64], b: &mut [f64]| {
            for (x, (o, w)) in self.taps4.iter().enumerate() {
                let mut sum = [0u32; 3];
                for k in 0..taps {
                    let t = &src[o[k]..o[k] + 3];
                    sum[0] += w[k] * t[0] as u32;
                    sum[1] += w[k] * t[1] as u32;
                    sum[2] += w[k] * t[2] as u32;
                }
                r[x] = sum[0] as f64;
                g[x] = sum[1] as f64;
                b[x] = sum[2] as f64;
            }
        };
        match (self.taps4.is_empty(), self.taps_used) {
            (false, 1..=2) => return fixed(2, r, g, b),
            (false, 3) => return fixed(3, r, g, b),
            (false, _) => return fixed(4, r, g, b),
            (true, _) => {}
        }
        for (x, tx) in self.cols.iter().enumerate() {
            let base = row_base + tx.lo as usize * 3;
            let end = row_base + (tx.hi as usize + 1) * 3;
            let (mut a0, mut a1, mut a2) = (0u64, 0u64, 0u64);
            for (col, texel) in (tx.lo..).zip(self.rgb[base..end].chunks_exact(3)) {
                let w = tx.weight_at(col);
                a0 += w * texel[0] as u64;
                a1 += w * texel[1] as u64;
                a2 += w * texel[2] as u64;
            }
            r[x] = a0 as f64;
            g[x] = a1 as f64;
            b[x] = a2 as f64;
        }
    }

    /// The cache slot holding source row `row`, filling one if needed. Rows
    /// in `keep` (the box being assembled) are never evicted.
    fn slot(&mut self, row: u32, keep: (u32, u32)) -> usize {
        self.clock += 1;
        if let Some(i) = self.slots.iter().position(|s| s.0 == row) {
            self.slots[i].1 = self.clock;
            return i;
        }
        let i = if self.slots.len() <= Self::MAX_ROWS {
            self.slots.push((row, 0, vec![0.0; 3 * self.cols.len()]));
            self.slots.len() - 1
        } else {
            // More slots than the tallest box, so one lies outside it.
            self.slots
                .iter()
                .enumerate()
                .filter(|(_, s)| s.0 < keep.0 || s.0 > keep.1)
                .min_by_key(|(_, s)| s.1)
                .map_or(0, |(i, _)| i)
        };
        let mut planes = std::mem::take(&mut self.slots[i].2);
        self.horizontal(row, &mut planes);
        self.slots[i] = (row, self.clock, planes);
        i
    }

    /// Average every column over the rows `ty` and write the pixels opaque
    /// into `dst` (RGBA, one pixel per column). `false` when the box is taller
    /// than [`Self::MAX_ROWS`] (nothing is written).
    fn average_row(&mut self, ty: &crate::render_cpu::image::AxisTaps, dst: &mut [u8]) -> bool {
        if (ty.hi - ty.lo) as usize >= Self::MAX_ROWS {
            return false;
        }
        self.acc.fill(0.0);
        for r in ty.lo..=ty.hi {
            let i = self.slot(r, (ty.lo, ty.hi));
            box_accumulate(
                self.kernel,
                &mut self.acc,
                &self.slots[i].2,
                ty.weight_at(r) as f64,
            );
        }
        box_finish(
            self.kernel,
            &self.acc,
            &self.col_total,
            ty.total as f64,
            dst,
        );
        true
    }
}

/// `acc[i] += wy · h[i]`: one cached source row's horizontal sums, weighted,
/// into a destination row's planar sums. Exact (see [`RowBoxFilter`]).
#[inline]
#[allow(
    unsafe_code,
    reason = "dispatches the AVX2 build of the loop behind a runtime probe; see SAFETY comment"
)]
fn box_accumulate(kernel: ImageKernel, acc: &mut [f64], h: &[f64], wy: f64) {
    match kernel {
        #[cfg(target_arch = "x86_64")]
        // SAFETY: AVX2 is present (`image_kernel` probed it); the body is
        // safe code.
        ImageKernel::Avx2 => unsafe { box_accumulate_avx2(acc, h, wy) },
        ImageKernel::Scalar => box_accumulate_body(acc, h, wy),
    }
}

#[inline(always)]
fn box_accumulate_body(acc: &mut [f64], h: &[f64], wy: f64) {
    for (a, &v) in acc.iter_mut().zip(h) {
        *a += wy * v;
    }
}

/// [`box_accumulate_body`] compiled for AVX2, which the compiler vectorises
/// four lanes wide (separate multiply and add, never fused: Rust does not
/// contract floating-point expressions).
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
fn box_accumulate_avx2(acc: &mut [f64], h: &[f64], wy: f64) {
    box_accumulate_body(acc, h, wy);
}

/// Divide a destination row's planar sums (`acc`: `R | G | B`, one entry per
/// column) by each box's weight `row_total · col_total[x]`, rounding to
/// nearest as `(acc + ⌊w/2⌋) / w` does in integers — computed as
/// `trunc((acc + w/2) / w)`, which is the same floor (see [`RowBoxFilter`];
/// the half-integer numerator cannot reach the next multiple of `w` either)
/// — and write the pixels opaque RGBA into `dst`.
#[inline]
#[allow(
    unsafe_code,
    reason = "dispatches the AVX2 kernel behind a runtime probe; see SAFETY comment"
)]
fn box_finish(kernel: ImageKernel, acc: &[f64], col_total: &[f64], row_total: f64, dst: &mut [u8]) {
    let n = col_total.len();
    // Bounds-check once, here, so both kernels share one invariant.
    let dst = &mut dst[..n * 4];
    let acc = &acc[..n * 3];
    match kernel {
        #[cfg(target_arch = "x86_64")]
        // SAFETY: AVX2 is present (`image_kernel` probed it); `acc` holds
        // `3n` sums, `col_total` `n` totals and `dst` `4n` bytes, which is all
        // the kernel reads and writes.
        ImageKernel::Avx2 => unsafe { box_finish_avx2(acc, col_total, row_total, dst) },
        ImageKernel::Scalar => box_finish_scalar(acc, col_total, row_total, dst, 0),
    }
}

/// Scalar reference for [`box_finish`], from column `start` on.
#[inline]
fn box_finish_scalar(acc: &[f64], col_total: &[f64], row_total: f64, dst: &mut [u8], start: usize) {
    let n = col_total.len();
    for x in start..n {
        let w = row_total * col_total[x];
        let q = |a: f64| ((a + 0.5 * w) / w) as i32 as u8;
        dst[x * 4..x * 4 + 4].copy_from_slice(&[q(acc[x]), q(acc[n + x]), q(acc[2 * n + x]), 255]);
    }
}

/// AVX2 [`box_finish`]: four columns per iteration — the same multiply, add,
/// divide and truncation as the scalar reference, lane for lane — packed to
/// four RGBA pixels with one store.
#[cfg(target_arch = "x86_64")]
#[target_feature(enable = "avx2")]
#[allow(
    unsafe_code,
    reason = "AVX2 intrinsics over bounds-checked slices; see SAFETY comments"
)]
fn box_finish_avx2(acc: &[f64], col_total: &[f64], row_total: f64, dst: &mut [u8]) {
    use std::arch::x86_64::*;
    let n = col_total.len();
    let (ar, rest) = acc.split_at(n);
    let (ag, ab) = rest.split_at(n);
    let rt = _mm256_set1_pd(row_total);
    let half = _mm256_set1_pd(0.5);
    let alpha = _mm_set1_epi32(0xFF00_0000u32 as i32);
    let mut x = 0;
    while x + 4 <= n {
        // SAFETY: `x + 4 <= n` and every plane and `col_total` hold `n`
        // entries; `dst` holds `4n` bytes, so the 16-byte store at `4x` is in
        // bounds.
        unsafe {
            let w = _mm256_mul_pd(rt, _mm256_loadu_pd(col_total.as_ptr().add(x)));
            let hw = _mm256_mul_pd(half, w);
            let q = |plane: &[f64]| {
                let a = _mm256_loadu_pd(plane.as_ptr().add(x));
                _mm256_cvttpd_epi32(_mm256_div_pd(_mm256_add_pd(a, hw), w))
            };
            let (r, g, b) = (q(ar), q(ag), q(ab));
            let px = _mm_or_si128(
                _mm_or_si128(r, _mm_slli_epi32::<8>(g)),
                _mm_or_si128(_mm_slli_epi32::<16>(b), alpha),
            );
            _mm_storeu_si128(dst.as_mut_ptr().add(x * 4).cast::<__m128i>(), px);
        }
        x += 4;
    }
    box_finish_scalar(acc, col_total, row_total, dst, x);
}

/// The union and intersection of the soft-mask rows one destination row's
/// boxes span (`bits`: packed one-bit rows; `bytes`: eight-bit rows), padded
/// so a 64-bit window read never leaves the buffer. A box whose texels are
/// all clear or all set has an exact coverage in both mask filters — `0.0`,
/// or the full weight over itself, `1.0`: a one-bit box's weighted ones equal
/// `tx.total · ty.total` exactly when every bit is set (every tap weighs at
/// least 1), and an eight-bit box of `255` texels sums the integral products
/// `wy · wx · 1.0` without rounding (they stay far below 2⁵³) — so its alpha
/// is known without running the filter.
struct MaskRowSummary {
    any: Vec<u8>,
    all: Vec<u8>,
    one_bit: bool,
}

impl MaskRowSummary {
    fn new(
        sm: &crate::page_ir::ImageSMask,
        rows: &crate::render_cpu::image::AxisTaps,
        one_bit: bool,
    ) -> Self {
        let row_bytes = crate::render_cpu::image::smask_row_bits(sm) / 8;
        let mut any = vec![0u8; row_bytes + 8];
        let mut all = vec![0u8; row_bytes + 8];
        all[..row_bytes].fill(0xff);
        for r in rows.lo..=rows.hi {
            // Bytes past the end of the samples read as zero, as the filters'
            // own reads do.
            let src = sm
                .samples
                .get(r as usize * row_bytes..)
                .map_or(&[][..], |s| &s[..s.len().min(row_bytes)]);
            for ((a, b), &v) in any.iter_mut().zip(all.iter_mut()).zip(src) {
                *a |= v;
                *b &= v;
            }
            all[src.len()..row_bytes].fill(0);
        }
        Self { any, all, one_bit }
    }

    fn bits(sm: &crate::page_ir::ImageSMask, rows: &crate::render_cpu::image::AxisTaps) -> Self {
        Self::new(sm, rows, true)
    }

    fn bytes(sm: &crate::page_ir::ImageSMask, rows: &crate::render_cpu::image::AxisTaps) -> Self {
        Self::new(sm, rows, false)
    }

    /// Whether every texel in columns `lo..=hi` of the spanned rows is clear.
    fn clear_over(&self, lo: u32, hi: u32) -> bool {
        let (lo, hi) = (lo as usize, hi as usize);
        if !self.one_bit {
            return self.any[lo..=hi].iter().all(|&v| v == 0);
        }
        let (first, last) = (lo / 8, hi / 8);
        let head = 0xffu8 >> (lo % 8);
        let tail = 0xffu8 << (7 - hi % 8);
        if first == last {
            return self.any[first] & head & tail == 0;
        }
        self.any[first] & head == 0
            && self.any[last] & tail == 0
            && self.any[first + 1..last].iter().all(|&v| v == 0)
    }

    /// The first texel at or after `from` that is set in any spanned row, or
    /// `None` when the rest of the row is clear.
    #[inline]
    fn next_set(&self, from: usize) -> Option<usize> {
        if !self.one_bit {
            let rest = self.any.get(from..)?;
            return rest.iter().position(|&v| v != 0).map(|i| from + i);
        }
        let byte = from / 8;
        let head = self.any.get(byte)? & (0xffu8 >> (from % 8));
        if head != 0 {
            return Some(byte * 8 + head.leading_zeros() as usize);
        }
        let rest = self.any.get(byte + 1..)?;
        let i = rest.iter().position(|&v| v != 0)?;
        Some((byte + 1 + i) * 8 + rest[i].leading_zeros() as usize)
    }

    /// Whether every texel of the box is set, for a box already known to
    /// hold a set texel: the second half of [`Self::uniform`], with the same
    /// width limit (a wider box reads as not all set, and filters).
    #[inline]
    fn all_set(&self, cols: &crate::render_cpu::image::AxisTaps) -> bool {
        if self.one_bit {
            let width = (cols.hi - cols.lo + 1) as usize;
            width <= 57 && bit_window(&self.all, cols.lo as usize, width) == (1u64 << width) - 1
        } else {
            self.all[cols.lo as usize..=cols.hi as usize]
                .iter()
                .all(|&v| v == 0xff)
        }
    }

    /// `Some(false)` when every texel of the box is clear, `Some(true)` when
    /// every one is set, `None` when it is mixed (or too wide to test in one
    /// window, which only costs the shortcut).
    #[inline]
    fn uniform(&self, cols: &crate::render_cpu::image::AxisTaps) -> Option<bool> {
        if self.one_bit {
            let width = (cols.hi - cols.lo + 1) as usize;
            if width > 57 {
                return None;
            }
            let full = (1u64 << width) - 1;
            if bit_window(&self.any, cols.lo as usize, width) == 0 {
                Some(false)
            } else if bit_window(&self.all, cols.lo as usize, width) == full {
                Some(true)
            } else {
                None
            }
        } else {
            let range = cols.lo as usize..=cols.hi as usize;
            if self.any[range.clone()].iter().all(|&v| v == 0) {
                Some(false)
            } else if self.all[range].iter().all(|&v| v == 0xff) {
                Some(true)
            } else {
                None
            }
        }
    }
}

/// `width` (≤ 57) bits of an MSB-first packed buffer starting at bit `bit`,
/// right-aligned: the first bit lands at `width - 1`, the last at 0. Bytes
/// past the end of `data` read as zero.
#[inline(always)]
fn bit_window(data: &[u8], bit: usize, width: usize) -> u64 {
    let byte = bit >> 3;
    let word = match data.get(byte..byte + 8) {
        Some(b) => u64::from_be_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]),
        None => {
            let mut buf = [0u8; 8];
            if let Some(tail) = data.get(byte..) {
                buf[..tail.len()].copy_from_slice(tail);
            }
            u64::from_be_bytes(buf)
        }
    };
    (word << (bit & 7)) >> (64 - width)
}

/// The one-bit mask rows one destination row's boxes span: each row's first
/// bit offset and weight, prepared once per destination row so the mixed-box
/// filter walks them without recomputing the row stride or the weight of
/// every row for every column.
struct BilevelMaskRows {
    n: usize,
    bit_offset: [usize; Self::MAX_ROWS],
    weight: [u64; Self::MAX_ROWS],
    total: u64,
}

impl BilevelMaskRows {
    /// Tallest box prepared; a taller one (a minification of more than ~15×
    /// on Y) takes the per-column filter.
    const MAX_ROWS: usize = 16;

    fn new(
        sm: &crate::page_ir::ImageSMask,
        rows: &crate::render_cpu::image::AxisTaps,
    ) -> Option<Self> {
        let n = (rows.hi - rows.lo) as usize + 1;
        if n > Self::MAX_ROWS {
            return None;
        }
        let row_bits = crate::render_cpu::image::smask_row_bits(sm);
        let mut prepared = Self {
            n,
            bit_offset: [0; Self::MAX_ROWS],
            weight: [0; Self::MAX_ROWS],
            total: rows.total,
        };
        for (i, row) in (rows.lo..=rows.hi).enumerate() {
            prepared.bit_offset[i] = row as usize * row_bits;
            prepared.weight[i] = rows.weight_at(row);
        }
        Some(prepared)
    }
}

/// [`bilevel_smask_coverage_windowed`] over prepared rows: the same window
/// per row, the same `w_lo·first + w_hi·last + S·popcount(interior)`, the
/// same saturating row-weighted sum in the same row order, the same `f32`
/// division — so the identical coverage. The box must be at most 57 wide.
#[inline]
fn bilevel_coverage_prepared(
    sm: &crate::page_ir::ImageSMask,
    rows: &BilevelMaskRows,
    tx: &crate::render_cpu::image::AxisTaps,
) -> f32 {
    const S: u64 = crate::render_cpu::image::AXIS_TAP_SCALE;
    let width = (tx.hi - tx.lo + 1) as usize;
    let weight = tx.total.saturating_mul(rows.total).max(1);
    let mut ones_w = 0u64;
    for i in 0..rows.n {
        let win = bit_window(&sm.samples, rows.bit_offset[i] + tx.lo as usize, width);
        let row_ones = if width == 1 {
            tx.w_lo * win
        } else {
            let interior = (win >> 1) & ((1u64 << (width - 2)) - 1);
            tx.w_lo * (win >> (width - 1)) + tx.w_hi * (win & 1) + S * interior.count_ones() as u64
        };
        ones_w = ones_w.saturating_add(rows.weight[i].saturating_mul(row_ones));
    }
    ones_w as f32 / weight as f32
}

/// [`crate::render_cpu::image::bilevel_smask_coverage`] with each mask row's taps read as
/// one 64-bit window instead of bit by bit: the same `w_lo·first + w_hi·last
/// + S·popcount(interior)` per row, the same saturating row-weighted sum, the
/// same `f32` division — so the identical coverage. Boxes wider than one
/// window take the original.
#[inline]
fn bilevel_smask_coverage_windowed(
    sm: &crate::page_ir::ImageSMask,
    tx: &crate::render_cpu::image::AxisTaps,
    ty: &crate::render_cpu::image::AxisTaps,
) -> f32 {
    const S: u64 = crate::render_cpu::image::AXIS_TAP_SCALE;
    let width = (tx.hi - tx.lo + 1) as usize;
    if width > 57 {
        return crate::render_cpu::image::bilevel_smask_coverage(sm, tx, ty);
    }
    let row_bits = crate::render_cpu::image::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 win = bit_window(&sm.samples, row as usize * row_bits + tx.lo as usize, width);
        let row_ones = if width == 1 {
            tx.w_lo * win
        } else {
            let interior = (win >> 1) & ((1u64 << (width - 2)) - 1);
            tx.w_lo * (win >> (width - 1)) + tx.w_hi * (win & 1) + S * interior.count_ones() as u64
        };
        ones_w = ones_w.saturating_add(ty.weight_at(row).saturating_mul(row_ones));
    }
    ones_w as f32 / weight as f32
}

/// Referenced source bits above which a minified bilevel draw weights its
/// source rows across the rayon pool even when its destination is small.
/// Below it the serial walk is already a fraction of a millisecond and the
/// fan-out would not pay for itself.
const BILEVEL_ROWS_PAR_MIN_BITS: usize = 1 << 20;

/// Destination-pixel count above which an image draw paints its independent
/// destination rows across the rayon pool. Mirrors the bilinear fast path's
/// own long-standing `PAR_PIXEL_THRESHOLD`.
const IMAGE_ROW_PAR_PIXEL_THRESHOLD: usize = 256 * 256;

/// Page executions running in this process right now. Intra-page row fan-out
/// only pays when the render has the machine to itself: under the document
/// scheduler every core is already carrying another page, and fanning out
/// there oversubscribes the box — measured at −31 % whole-document throughput
/// on a 640-page bilevel scan — for no extra work done.
static PAGES_IN_FLIGHT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);

/// RAII counter for [`PAGES_IN_FLIGHT`], held for one top-level page execution.
struct PageInFlight;

impl PageInFlight {
    fn enter() -> Self {
        PAGES_IN_FLIGHT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        Self
    }
}

impl Drop for PageInFlight {
    fn drop(&mut self) {
        PAGES_IN_FLIGHT.fetch_sub(1, std::sync::atomic::Ordering::Relaxed);
    }
}

/// How the image row loops decide to fan out over the rayon pool.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RowParPolicy {
    /// Always serial.
    Never,
    /// Fan out only while this is the sole page render in flight.
    Auto,
    /// Always fan out above the pixel threshold.
    Always,
}

/// `PDF_RENDERER_IMAGE_ROW_PAR` selects the policy: unset or `auto` is
/// load-aware, `off`/`0`/`false` forces the serial row loop and `on`/`1`/
/// `always` forces the fan-out. The override exists for paired A/B isolation
/// on one binary. Read once.
fn row_par_policy() -> RowParPolicy {
    use std::sync::OnceLock;
    static POLICY: OnceLock<RowParPolicy> = OnceLock::new();
    *POLICY.get_or_init(|| match std::env::var("PDF_RENDERER_IMAGE_ROW_PAR") {
        Ok(v) => match v.trim().to_ascii_lowercase().as_str() {
            "off" | "0" | "false" => RowParPolicy::Never,
            "on" | "1" | "true" | "always" => RowParPolicy::Always,
            _ => RowParPolicy::Auto,
        },
        Err(_) => RowParPolicy::Auto,
    })
}

/// Whether the image row loops should fan their destination rows out over the
/// rayon pool. Consulted once per draw, never per pixel.
fn image_row_parallel_enabled() -> bool {
    match row_par_policy() {
        RowParPolicy::Never => false,
        RowParPolicy::Always => true,
        RowParPolicy::Auto => PAGES_IN_FLIGHT.load(std::sync::atomic::Ordering::Relaxed) <= 1,
    }
}

/// Render a tiling-pattern fill: replicate the compiled cell across the
/// lattice into a fill-sized offscreen, then composite it onto `surface`
/// masked by the fill shape (advice §9-style bounded offscreen).
#[allow(clippy::too_many_arguments)]
fn render_tiling(
    page: &CpuPreparedPage,
    t: &crate::render_cpu::prepared::PreparedTiling,
    surface: &mut Surface,
    raster: &mut RasterKernel,
    kernels: &KernelSet,
    masks: &mut [Option<ClipMask>],
    stats: &mut RenderStats,
) {
    #[cfg(test)]
    let cull_tiles = !RENDER_ALL_TILES.with(std::cell::Cell::get);
    #[cfg(not(test))]
    let cull_tiles = true;
    render_tiling_impl(page, t, surface, raster, kernels, masks, stats, cull_tiles);
}

#[cfg(test)]
thread_local! {
    /// Test-only reference switch: render every tile instance, as before tile
    /// culling existed, so `tiling_cull_tests` can compare bytes.
    static RENDER_ALL_TILES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Everything a tiling cell can paint, bounded conservatively in pattern
/// space, for tile culling (see [`cell_paint_extent`]).
#[derive(Debug, Clone, Copy)]
struct CellPaintExtent {
    /// Bounding box of every path control point the cell fills or strokes.
    x0: f64,
    y0: f64,
    x1: f64,
    y1: f64,
    /// Largest distance, in pattern units, that a stroke's outline can lie
    /// from its centreline (0 without strokes).
    stroke_reach: f64,
    /// Largest join/cap reach factor of the cell's strokes, for the device
    /// hairline floor (0 without strokes).
    stroke_factor: f64,
}

/// Bound the paint of a tiling cell, or `None` when the cell contains anything
/// this does not bound (text, images, shadings, nested patterns, groups, soft
/// masks) or non-finite geometry; callers then cull nothing.
///
/// Only solid-paint path fills and strokes are bounded. A flattened curve
/// lies inside the convex hull of its control points, so the box of all
/// control points contains every fill vertex. A stroke outline lies within
/// `half-width * max(miter limit, sqrt 2)` of its centreline (round and bevel
/// joins and butt/round caps reach one half-width, a square cap's corner
/// `sqrt 2`, and a miter apex is kept only within the miter limit), which is
/// recorded separately because the half-width has a device-space floor.
/// Clips inside the cell only remove paint and are ignored, as is the
/// soft-mask reset (`ClearSoftMask`) that opens a cell.
fn cell_paint_extent(cell: &crate::page_ir::CompiledPage) -> Option<CellPaintExtent> {
    use crate::page_ir::{DisplayOp, Matrix, Paint};
    let mut extent = CellPaintExtent {
        x0: f64::INFINITY,
        y0: f64::INFINITY,
        x1: f64::NEG_INFINITY,
        y1: f64::NEG_INFINITY,
        stroke_reach: 0.0,
        stroke_factor: 0.0,
    };
    let mut ctm = Matrix::IDENTITY;
    let mut stack: Vec<Matrix> = Vec::new();
    let include = |extent: &mut CellPaintExtent, ctm: Matrix, path: &crate::page_ir::PathData| {
        for point in path.points.iter() {
            let q = ctm.apply(*point);
            if !(q.x.is_finite() && q.y.is_finite()) {
                return false;
            }
            extent.x0 = extent.x0.min(q.x);
            extent.y0 = extent.y0.min(q.y);
            extent.x1 = extent.x1.max(q.x);
            extent.y1 = extent.y1.max(q.y);
        }
        true
    };
    for op in cell.operations.iter() {
        match op {
            DisplayOp::Save => stack.push(ctm),
            DisplayOp::Restore => {
                if let Some(saved) = stack.pop() {
                    ctm = saved;
                }
            }
            DisplayOp::ConcatTransform(m) => ctm = m.then(ctm),
            // State that can only restrict or leave paint unchanged: clips,
            // the soft-mask reset every cell starts with, and attribution
            // markers.
            DisplayOp::PushClip { .. }
            | DisplayOp::PopClip
            | DisplayOp::ClearSoftMask
            | DisplayOp::BeginPaintOrigin(_)
            | DisplayOp::EndPaintOrigin => {}
            DisplayOp::FillPath { path, paint, .. } => {
                if !matches!(cell.paints.get(paint.index()), Some(Paint::Solid(_))) {
                    return None;
                }
                if !include(&mut extent, ctm, cell.paths.get(path.index())?) {
                    return None;
                }
            }
            DisplayOp::StrokePath {
                path, paint, style, ..
            } => {
                if !matches!(cell.paints.get(paint.index()), Some(Paint::Solid(_))) {
                    return None;
                }
                if !include(&mut extent, ctm, cell.paths.get(path.index())?) {
                    return None;
                }
                let style = cell.stroke_styles.get(style.index())?;
                let factor = style.miter_limit.max(std::f64::consts::SQRT_2);
                // The Frobenius norm bounds the largest stretch of the CTM.
                let stretch = (ctm.a * ctm.a + ctm.b * ctm.b + ctm.c * ctm.c + ctm.d * ctm.d).sqrt();
                let reach = 0.5 * style.width.abs() * stretch * factor;
                if !(reach.is_finite() && factor.is_finite()) {
                    return None;
                }
                extent.stroke_reach = extent.stroke_reach.max(reach);
                extent.stroke_factor = extent.stroke_factor.max(factor);
            }
            _ => return None,
        }
    }
    (extent.x0 <= extent.x1 && extent.y0 <= extent.y1).then_some(extent)
}

/// Whether a tile's content can reach a pixel the shape mask covers.
/// `tile_to_local` maps pattern space to the mask's local pixel grid. The
/// tile's content box is padded by the stroke reach in device space (never
/// less than the 1.5 px a hairline-clamped pen can reach per reach factor)
/// plus 2 px for anti-aliasing and float rounding; anything not provably
/// clear of the mask is rendered.
fn tile_reaches_mask(
    extent: &CellPaintExtent,
    tile_to_local: crate::page_ir::Matrix,
    fmask: &[u8],
    w: usize,
    h: usize,
) -> bool {
    use crate::page_ir::Point;
    let m = tile_to_local;
    let stretch = (m.a * m.a + m.b * m.b + m.c * m.c + m.d * m.d).sqrt();
    let stroke_pad = if extent.stroke_factor > 0.0 {
        (extent.stroke_reach * stretch).max(1.5 * extent.stroke_factor)
    } else {
        0.0
    };
    let pad = stroke_pad + 2.0;
    let corners = [
        m.apply(Point { x: extent.x0, y: extent.y0 }),
        m.apply(Point { x: extent.x1, y: extent.y0 }),
        m.apply(Point { x: extent.x1, y: extent.y1 }),
        m.apply(Point { x: extent.x0, y: extent.y1 }),
    ];
    let (mut min_x, mut min_y, mut max_x, mut max_y) = (
        f64::INFINITY,
        f64::INFINITY,
        f64::NEG_INFINITY,
        f64::NEG_INFINITY,
    );
    for corner in corners {
        min_x = min_x.min(corner.x);
        min_y = min_y.min(corner.y);
        max_x = max_x.max(corner.x);
        max_y = max_y.max(corner.y);
    }
    let (lo_x, lo_y, hi_x, hi_y) = (min_x - pad, min_y - pad, max_x + pad, max_y + pad);
    if !(lo_x.is_finite() && lo_y.is_finite() && hi_x.is_finite() && hi_y.is_finite()) {
        return true;
    }
    // Pixel columns `floor(lo)..=floor(hi)`, clamped to the mask.
    let clamp = |v: f64, limit: usize| v.floor().clamp(-1.0, limit as f64) as i64;
    let (x0, x1) = (clamp(lo_x, w).max(0), clamp(hi_x, w).min(w as i64 - 1));
    let (y0, y1) = (clamp(lo_y, h).max(0), clamp(hi_y, h).min(h as i64 - 1));
    if x0 > x1 || y0 > y1 {
        return false;
    }
    let (x0, x1, y0, y1) = (x0 as usize, x1 as usize, y0 as usize, y1 as usize);
    (y0..=y1).any(|y| fmask[y * w + x0..=y * w + x1].iter().any(|&c| c != 0))
}

/// [`render_tiling`] with tile culling switchable, so tests can compare the
/// culled result against rendering every tile.
#[allow(clippy::too_many_arguments)]
fn render_tiling_impl(
    page: &CpuPreparedPage,
    t: &crate::render_cpu::prepared::PreparedTiling,
    surface: &mut Surface,
    raster: &mut RasterKernel,
    kernels: &KernelSet,
    masks: &mut [Option<ClipMask>],
    stats: &mut RenderStats,
    cull_tiles: bool,
) {
    let b = t.bounds;
    let (w, h) = (b.width as usize, b.height as usize);
    let (bx, by) = (b.x as usize, b.y as usize);
    if w == 0 || h == 0 {
        return;
    }

    // Cell instances render into a fill-sized surface whose local origin is
    // the fill's device origin (so cell draws are clipped to the fill bounds).
    let mut pat = Surface::new(w, h, crate::render_api::Background::Transparent);
    let size = crate::page_ir::DeviceSize {
        width: b.width,
        height: b.height,
    };
    let shift = crate::page_ir::Matrix::translate(-(b.x as f64), -(b.y as f64));
    #[cfg(feature = "profiling")]
    let mut lap = crate::profiling::Lap::start();
    #[cfg(feature = "profiling")]
    {
        stats.hot.tiling_surface_px += (w * h) as u64;
        raster.prof.class = crate::render_cpu::raster::RasterClass::Other;
    }
    // The fill shape as an Alpha8 coverage mask over the bounds.
    let subs = &page.subpaths[t.fill_subpaths.0 as usize..t.fill_subpaths.1 as usize];
    let mut fmask = vec![0u8; w * h];
    let dev_w = page.size.width as usize;
    let dev_h = page.size.height as usize;
    if !raster.fill_cancellable_in(
        &page.points,
        subs,
        dev_w,
        dev_h,
        t.fill_rule,
        by..by + h,
        page.decode_limits.should_cancel.as_deref(),
        |y, x0, x1, cov| {
            if y < by || y >= by + h {
                return;
            }
            let ly = y - by;
            let lx0 = x0.max(bx);
            let lx1 = x1.min(bx + w - 1);
            if lx0 <= lx1 {
                fmask[ly * w + (lx0 - bx)..=ly * w + (lx1 - bx)].copy_from_slice(&cov[lx0..=lx1]);
            }
        },
    ) {
        stats.cancelled = true;
        return;
    }

    // Intersect with the outer non-rectangular clip mask, if any.
    if t.clip_has_mask {
        // Lowering guarantees a masked draw carries its clip id; skip the
        // draw (never panic a page) if that IR invariant broke upstream.
        let Some(cid) = t.clip else {
            page.diagnostics
                .note_degraded("tiling fill skipped: masked clip without a clip id".into());
            return;
        };
        // Share the nearest path-clip ancestor's mask across rect
        // descendants, as every other draw does: a rect clip contributes only
        // its bounds, which the tile bounds are already intersected with, so
        // inside them the ancestor's mask is this clip's mask, and it is
        // rasterized once instead of once per descendant.
        let cid = page.clips[cid as usize].mask_source.unwrap_or(cid);
        if masks[cid as usize].is_none() {
            let Some(mask) = build_render_clip_mask(page, raster, cid, stats) else {
                return;
            };
            masks[cid as usize] = Some(mask);
        }
        let Some(cm) = masks[cid as usize].as_ref() else {
            return; // unreachable: just built above
        };
        let mw = cm.stride();
        for ly in 0..h {
            let dy = by + ly;
            if dy < cm.bounds.y as usize || dy >= cm.bounds.y as usize + cm.bounds.height as usize {
                for lx in 0..w {
                    fmask[ly * w + lx] = 0;
                }
                continue;
            }
            let base = (dy - cm.bounds.y as usize) * mw;
            let cmx = cm.bounds.x as usize;
            let cmw = cm.bounds.width as usize;
            for lx in 0..w {
                let dx = bx + lx;
                let v = if dx >= cmx && dx < cmx + cmw {
                    cm.data[base + (dx - cmx)]
                } else {
                    0
                };
                fmask[ly * w + lx] = mul_div_255(fmask[ly * w + lx] as u16, v as u16) as u8;
            }
        }
    }

    // An /ImageMask stencil painted with this pattern: the pattern shows only
    // through the stencil's per-pixel coverage. Sampled with the same edge
    // coverage as an ordinary stencil blit, then folded into the fill mask.
    if let Some(stencil) = &t.stencil {
        for ly in 0..h {
            for lx in 0..w {
                let idx = ly * w + lx;
                if fmask[idx] == 0 {
                    continue;
                }
                let (dx, dy) = ((bx + lx) as f64 + 0.5, (by + ly) as f64 + 0.5);
                let edge = stencil.edge_coverage(dx, dy);
                let scov = if edge == Some(0) {
                    0
                } else {
                    let color = match edge {
                        None => stencil.shade(dx, dy),
                        Some(_) => stencil.shade_clamped(dx, dy),
                    };
                    let base = color.map(|c| c[3] as u16).unwrap_or(0);
                    match edge {
                        Some(ec) => mul_div_255(base, ec),
                        None => base,
                    }
                };
                fmask[idx] = mul_div_255(fmask[idx] as u16, scov) as u8;
            }
        }
    }

    #[cfg(feature = "profiling")]
    {
        stats.hot.ns_tiling_fmask += lap.lap_ns();
        stats.hot.tiling_mask_px += fmask.iter().filter(|&&c| c != 0).count() as u64;
        lap.lap_ns();
    }

    // Tile-invariant state hoisted out of the instance loop (A3): one parsed-
    // font residency shared by every tile instance of this fill. Geometry
    // still lowers per instance — each tile's device transform differs by a
    // generally-fractional translation, and floating-point point transforms
    // are not translation-invariant, so a lower-once-translate-many cell
    // would not be byte-identical to per-instance lowering.
    let mut cell_fonts = crate::render_cpu::prepared::FontProgramCache::default();
    // Only pixels the shape mask covers are ever read back from `pat` (the
    // composite below skips zero coverage), so a tile whose content cannot
    // reach a covered pixel paints nothing visible and is not lowered or
    // rasterized at all. Pattern-painted strokes make this the common case:
    // the tiles span the stroke's bounding box, the mask a thin band of it.
    let extent = if cull_tiles && fmask.iter().any(|&c| c != 0) {
        cell_paint_extent(&t.cell)
    } else {
        None
    };
    let mask_is_empty = cull_tiles && fmask.iter().all(|&c| c == 0);
    for tile in &t.tiles {
        if mask_is_empty {
            break;
        }
        if let Some(extent) = &extent
            && !tile_reaches_mask(extent, tile.then(shift), &fmask, w, h)
        {
            #[cfg(feature = "profiling")]
            {
                stats.hot.n_tiles_culled += 1;
            }
            continue;
        }
        // A cancelled request stops between tile instances too — an
        // adversarial many-tile fill must not pin the worker.
        if let Some(cancel) = &page.decode_limits.should_cancel
            && cancel()
        {
            stats.cancelled = true;
            return;
        }
        let cell_prepared = crate::render_cpu::prepared::lower_cell(
            &t.cell,
            tile.then(shift),
            size,
            page,
            t.color_policy,
            &mut cell_fonts,
        );
        let mut cmasks: Vec<Option<ClipMask>> =
            (0..cell_prepared.clips.len()).map(|_| None).collect();
        let mut csoft: Vec<Option<ClipMask>> = Vec::new();
        #[cfg(feature = "profiling")]
        {
            stats.hot.ns_tiling_lower += lap.lap_ns();
            stats.hot.n_tiles += 1;
            stats.hot.tiling_cell_ops += cell_prepared.ops.len() as u64;
            stats.hot.tiling_cell_points += cell_prepared.points.len() as u64;
            stats.hot.tiling_depth += 1;
        }
        run_ops(
            &cell_prepared,
            0,
            cell_prepared.ops.len(),
            &mut pat,
            raster,
            kernels,
            &mut cmasks,
            &mut csoft,
            stats,
        );
        #[cfg(feature = "profiling")]
        {
            stats.hot.tiling_depth -= 1;
            stats.hot.ns_tiling_cells += lap.lap_ns();
            stats.hot.clock_reads += 2;
        }
        // A codec image dropped while lowering this tile cell counts too.
        stats.absorb_diagnostics(&cell_prepared.diagnostics);
    }
    #[cfg(feature = "profiling")]
    {
        // The cull's own cost lands in `cells` with the tiles it spared.
        stats.hot.ns_tiling_cells += lap.lap_ns();
    }

    // Composite the tiled offscreen onto `surface`, masked by the fill shape
    // and scaled by the fill's constant alpha.
    let sox = surface.origin_x;
    // Composite blend: `Normal` keeps the exact integer source-over below; a
    // non-Normal pattern fill un-premultiplies the cell pixel and goes
    // through the general per-pixel compositor.
    let blend = choose_blend(t.blend);
    let blend_is_normal = matches!(blend, BlendChoice::Normal);
    for ly in 0..h {
        let dy = by + ly;
        // `pat` is this function's own offscreen (built above), distinct from
        // `surface`, so the row can be borrowed rather than copied.
        let prow = pat.local_row(ly);
        let srow = surface.row_mut(dy);
        for lx in 0..w {
            let cov = fmask[ly * w + lx];
            if cov == 0 {
                continue;
            }
            let src = &prow[lx * 4..lx * 4 + 4];
            if src[3] == 0 {
                continue;
            }
            let kk = mul_div_255(cov as u16, t.alpha as u16);
            let dst = &mut srow[(bx + lx - sox) * 4..(bx + lx - sox) * 4 + 4];
            if !blend_is_normal {
                // Straight source color + effective alpha for the compositor.
                let (rgb, sa) = if t.uncolored {
                    let stencil = src[3] as u16;
                    let a = mul_div_255(mul_div_255(t.under[3] as u16, stencil), kk);
                    ([t.under[0], t.under[1], t.under[2]], a as u8)
                } else {
                    let s3 = src[3] as u16;
                    let un = |ch: usize| ((src[ch] as u16 * 255 + s3 / 2) / s3).min(255) as u8;
                    ([un(0), un(1), un(2)], mul_div_255(s3, kk) as u8)
                };
                composite_px_blended(dst, rgb, sa, blend);
                continue;
            }
            // Effective premultiplied source: the cell pixel (colored) or the
            // under-color through the cell's alpha stencil (uncolored).
            let (spr, sa) = if t.uncolored {
                let stencil = src[3] as u16;
                let a = mul_div_255(mul_div_255(t.under[3] as u16, stencil), kk);
                let pm = |ch: usize| {
                    mul_div_255(
                        mul_div_255(mul_div_255(t.under[ch] as u16, t.under[3] as u16), stencil),
                        kk,
                    ) as u8
                };
                ([pm(0), pm(1), pm(2)], a as u8)
            } else {
                let pm = |ch: usize| mul_div_255(src[ch] as u16, kk) as u8;
                ([pm(0), pm(1), pm(2)], mul_div_255(src[3] as u16, kk) as u8)
            };
            if sa == 0 {
                continue;
            }
            let ia = 255 - sa as u16;
            for ch in 0..3 {
                dst[ch] = (spr[ch] as u16 + mul_div_255(dst[ch] as u16, ia)) as u8;
            }
            dst[3] = (sa as u16 + mul_div_255(dst[3] as u16, ia)) as u8;
        }
    }
    #[cfg(feature = "profiling")]
    {
        stats.hot.ns_tiling_composite += lap.lap_ns();
        stats.hot.clock_reads += 4;
    }
    stats.commands += 1;
    stats.ops_painted += 1;
}

/// Evaluate a shading at device point `(dx, dy)`. Returns the straight RGBA
/// ramp color, or `None` when the point falls outside the shading's painted
/// extent (before the axis start / past the end without `/Extend`).
fn shade_pixel(
    sh: &crate::render_cpu::prepared::PreparedShading,
    dx: f64,
    dy: f64,
) -> Option<[u8; 4]> {
    use crate::render_cpu::prepared::ShadingSpanKind;
    // The shading's `/BBox` clip (§8.7.4.3): a device-space box outside which
    // nothing is painted, regardless of shading type or `/Extend`.
    if let Some(bb) = sh.bbox {
        let (x, y) = (dx as f32, dy as f32);
        if x < bb[0] || x > bb[2] || y < bb[1] || y > bb[3] {
            return None;
        }
    }
    // Pre-rasterized mesh layer: direct device-pixel lookup (alpha 0 = the
    // mesh does not paint here; the /Background, when honored, was baked in).
    if let ShadingSpanKind::Layer { x0, y0, w, h } = sh.kind {
        let lx = dx.floor() as i64 - x0 as i64;
        let ly = dy.floor() as i64 - y0 as i64;
        if lx < 0 || ly < 0 || lx >= w as i64 || ly >= h as i64 {
            return sh.background;
        }
        let c = sh.ramp[ly as usize * w + lx as usize];
        return if c[3] == 0 { None } else { Some(c) };
    }
    // Map the device point back into the shading's coordinate space.
    let p = sh.inv.apply(crate::page_ir::Point { x: dx, y: dy });
    if let ShadingSpanKind::Grid { domain, gw, gh } = sh.kind {
        let dw = domain[1] - domain[0];
        let dh = domain[3] - domain[2];
        if dw.abs() < 1e-12 || dh.abs() < 1e-12 {
            return sh.background;
        }
        let s = (p.x - domain[0]) / dw;
        let t = (p.y - domain[2]) / dh;
        if !(0.0..=1.0).contains(&s) || !(0.0..=1.0).contains(&t) {
            return sh.background;
        }
        let gx = ((s * gw as f64) as usize).min(gw - 1);
        let gy = ((t * gh as f64) as usize).min(gh - 1);
        return Some(sh.ramp[gy * gw + gx]);
    }
    let s = match sh.kind {
        ShadingSpanKind::Axial { p0, d, dd } => ((p.x - p0[0]) * d[0] + (p.y - p0[1]) * d[1]) / dd,
        // Outside both circles with `/Extend` off: the `/Background`, if any.
        ShadingSpanKind::Radial { c0, c1 } => match radial_param(c0, c1, p.x, p.y, sh.extend) {
            Some(s) => s,
            None => return sh.background,
        },
        // Handled above.
        ShadingSpanKind::Grid { .. } | ShadingSpanKind::Layer { .. } => return None,
    };
    // Past the axis with `/Extend` off: paint the `/Background`, if any.
    let Some(s) = apply_extend(s, sh.extend) else {
        return sh.background;
    };
    let n = sh.ramp.len();
    if n == 0 {
        return None;
    }
    let idx = (s * (n - 1) as f64).round().clamp(0.0, (n - 1) as f64) as usize;
    Some(sh.ramp[idx])
}

/// Color a glyph-coverage span from a shading (a shading-pattern text fill):
/// each covered pixel takes the shading's color at its device center, with the
/// glyph coverage folded into the source alpha. `dst` and `cov` are aligned —
/// `cov[i]`'s device coordinate is `(x0 + i, y)`.
fn shade_glyph_span(
    dst: &mut [u8],
    cov: &[u8],
    sh: &crate::render_cpu::prepared::PreparedShading,
    x0: usize,
    y: usize,
    alpha: u8,
    blend: BlendChoice,
) {
    for (i, &c) in cov.iter().enumerate() {
        if c == 0 {
            continue;
        }
        let Some(color) = shade_pixel(sh, (x0 + i) as f64 + 0.5, y as f64 + 0.5) else {
            continue;
        };
        let a = mul_div_255(c as u16, mul_div_255(color[3] as u16, alpha as u16)) as u8;
        if a == 0 {
            continue;
        }
        composite_px_blended(
            &mut dst[i * 4..i * 4 + 4],
            [color[0], color[1], color[2]],
            a,
            blend,
        );
    }
}

/// Clamp a shading parameter to `[0, 1]` honoring the extend flags; returns
/// `None` when the parameter is out of range and extension is disabled.
#[inline]
fn apply_extend(s: f64, extend: [bool; 2]) -> Option<f64> {
    if s < 0.0 {
        extend[0].then_some(0.0)
    } else if s > 1.0 {
        extend[1].then_some(1.0)
    } else {
        Some(s)
    }
}

/// Solve the radial-shading parameter at point `(px, py)`: the largest `s`
/// (outer circles paint over inner) with a non-negative radius that lies in
/// the painted range. Returns the *unclamped* `s` (extend handling is applied
/// by the caller).
fn radial_param(c0: [f64; 3], c1: [f64; 3], px: f64, py: f64, extend: [bool; 2]) -> Option<f64> {
    let dcx = c1[0] - c0[0];
    let dcy = c1[1] - c0[1];
    let dr = c1[2] - c0[2];
    let fx = px - c0[0];
    let fy = py - c0[1];
    let a = dcx * dcx + dcy * dcy - dr * dr;
    let b = -2.0 * (fx * dcx + fy * dcy + c0[2] * dr);
    let c = fx * fx + fy * fy - c0[2] * c0[2];

    // Candidate roots, largest first.
    let mut roots = [f64::NAN; 2];
    if a.abs() < 1e-9 {
        if b.abs() < 1e-12 {
            return None;
        }
        roots[0] = -c / b;
    } else {
        let disc = b * b - 4.0 * a * c;
        if disc < 0.0 {
            return None;
        }
        let sq = disc.sqrt();
        let r0 = (-b + sq) / (2.0 * a);
        let r1 = (-b - sq) / (2.0 * a);
        roots = if r0 >= r1 { [r0, r1] } else { [r1, r0] };
    }
    for &s in roots.iter() {
        if s.is_nan() {
            continue;
        }
        // Radius must be non-negative at this parameter.
        if c0[2] + s * dr < 0.0 {
            continue;
        }
        let ok = (0.0..=1.0).contains(&s) || (s < 0.0 && extend[0]) || (s > 1.0 && extend[1]);
        if ok {
            return Some(s);
        }
    }
    None
}

/// Rec.601 luma of one premultiplied pixel's RGB bytes.
#[inline]
fn luma601(r: u8, g: u8, b: u8) -> u8 {
    (0.3 * r as f32 + 0.59 * g as f32 + 0.11 * b as f32 + 0.5) as u8
}

/// Derive an `Alpha8` soft mask from a rendered mask-group offscreen: its alpha
/// channel (Alpha) or luminosity (Luminosity / LuminosityBc — for the latter
/// the offscreen was pre-filled with the `/BC` backdrop, and pixels outside
/// the mask's extent take the backdrop's luminosity).
///
/// The `/TR` transfer function (a compile-side sampled 256-entry LUT)
/// applies here: `value = lut[value]` after the per-pixel derivation and to
/// `outside`.
fn derive_soft_mask(
    off: &Surface,
    kind: crate::page_ir::MaskKind,
    transfer: Option<&[u8; 256]>,
) -> ClipMask {
    let (w, h) = (off.width, off.height);
    let mut data = vec![0u8; w * h];
    for ly in 0..h {
        let row = off.local_row(ly);
        for lx in 0..w {
            let px = &row[lx * 4..lx * 4 + 4];
            let value = match kind {
                crate::page_ir::MaskKind::Alpha => px[3],
                // Premultiplied RGB already equals the color composited over
                // the backdrop (black, or the pre-filled /BC), so its Rec.601
                // luma is the luminosity mask value.
                crate::page_ir::MaskKind::Luminosity
                | crate::page_ir::MaskKind::LuminosityBc { .. } => luma601(px[0], px[1], px[2]),
            };
            data[ly * w + lx] = apply_transfer(value, transfer);
        }
    }
    ClipMask {
        bounds: DeviceRect {
            x: off.origin_x as i32,
            y: off.origin_y as i32,
            width: w as u32,
            height: h as u32,
        },
        data,
        outside: apply_transfer(soft_mask_outside(kind), transfer),
        // A soft mask, not an elidable rectangular clip.
        all_opaque: false,
    }
}

/// Route one derived mask value through the `/TR` LUT (identity when absent).
#[inline]
fn apply_transfer(value: u8, transfer: Option<&[u8; 256]>) -> u8 {
    match transfer {
        Some(lut) => lut[value as usize],
        None => value,
    }
}

/// The soft-mask value outside the mask's rendered extent: 0 for Alpha and
/// plain Luminosity (black backdrop), the backdrop's luminosity for `/BC`.
fn soft_mask_outside(kind: crate::page_ir::MaskKind) -> u8 {
    match kind {
        crate::page_ir::MaskKind::Alpha | crate::page_ir::MaskKind::Luminosity => 0,
        crate::page_ir::MaskKind::LuminosityBc { backdrop } => {
            luma601(backdrop[0], backdrop[1], backdrop[2])
        }
    }
}

/// Blit a run of cached glyph coverage bitmaps (PDFium's per-run
/// accumulate-and-blit). Each placement's bbox-tight `u8` coverage is composited
/// at its snapped device position: the fast case (Normal blend, no non-rect clip
/// mask, no soft mask, solid colour) is a single `blend_mask_rect` per glyph,
/// which also counts the covered pixels in the same pass; masked or non-Normal
/// runs take a per-row scratch that applies the clip/soft coverage before the
/// general compositor. No rasterization happens here — that was memoized at
/// lowering time.
#[allow(clippy::too_many_arguments)]
fn paint_glyph_run(
    page: &CpuPreparedPage,
    gr: &PreparedGlyphRun,
    surface: &mut Surface,
    raster: &mut RasterKernel,
    kernels: &KernelSet,
    masks: &mut [Option<ClipMask>],
    soft: Option<&ClipMask>,
    stats: &mut RenderStats,
) {
    #[cfg(feature = "profiling")]
    let command_start = Instant::now();
    stats.commands += 1;

    let mask_cid = if gr.clip_has_mask {
        // Lowering guarantees a masked draw carries its clip id; skip the
        // draw (never panic a page) if that IR invariant broke upstream.
        let Some(cid) = gr.clip else {
            page.diagnostics
                .note_degraded("glyph run skipped: masked clip without a clip id".into());
            return;
        };
        // Use the nearest path-clip ancestor's mask (rect children only narrow
        // bounds, applied per draw): one build shared across all descendants.
        let cid = page.clips[cid as usize].mask_source.unwrap_or(cid) as usize;
        if masks[cid].is_none() {
            let Some(mask) = build_render_clip_mask(page, raster, cid as u32, stats) else {
                return;
            };
            masks[cid] = Some(mask);
        }
        Some(cid)
    } else {
        None
    };
    let raw_mask = mask_cid.and_then(|cid| masks[cid].as_ref());
    // A path clip that rasterized to full coverage over its envelope is
    // rectangular for this draw (already reflected in `bounds`): drop the mask.
    let opaque_clip_elided = raw_mask.is_some_and(|cm| cm.all_opaque);
    let mask = raw_mask.filter(|_| !opaque_clip_elided);

    let blend = choose_blend(gr.blend);
    let simple = matches!(blend, BlendChoice::Normal) && mask.is_none() && soft.is_none();

    let b = gr.bounds;
    let (cbx0, cby0) = (b.x, b.y);
    let cbx1 = b.x + b.width as i32; // exclusive
    let cby1 = b.y + b.height as i32;
    let ox = surface.origin_x;
    let mut scratch: Vec<u8> = Vec::new();
    let mut covered: u64 = 0;

    for pl in &gr.placements {
        let bmp = &pl.bitmap;
        let bw = bmp.width as usize;
        let (gw, gh) = (bmp.width as i32, bmp.height as i32);
        // Device columns/rows this bitmap touches, clamped to the clip envelope.
        let rx0 = pl.dx.max(cbx0);
        let rx1 = (pl.dx + gw).min(cbx1);
        let ry0 = pl.dy.max(cby0);
        let ry1 = (pl.dy + gh).min(cby1);
        if rx0 >= rx1 || ry0 >= ry1 {
            continue;
        }
        let span = (rx1 - rx0) as usize;
        let src_off = (rx0 - pl.dx) as usize;
        let dst0 = (rx0 as usize - ox) * 4;
        let dst1 = (rx1 as usize - ox) * 4;

        if simple && gr.shading.is_none() {
            // The common case: the whole clamped bitmap in one kernel call,
            // which also returns its non-zero coverage count (no second pass).
            let rows = (ry1 - ry0) as usize;
            let (buf, first_y, stride) = surface.rows_mut_abs(ry0 as usize, ry1 as usize);
            if first_y == ry0 as usize && buf.len() == rows * stride {
                let src0 = (ry0 - pl.dy) as usize * bw + src_off;
                covered += (kernels.blend_mask_rect)(
                    &mut buf[dst0..],
                    stride,
                    &bmp.cov[src0..],
                    bw,
                    span,
                    rows,
                    gr.rgb,
                    gr.alpha,
                );
                continue;
            }
            // Rows outside the surface: keep the per-row path's behaviour.
        }

        for y in ry0..ry1 {
            let ly = (y - pl.dy) as usize;
            let src = &bmp.cov[ly * bw + src_off..ly * bw + src_off + span];
            let row = surface.row_mut(y as usize);

            if simple {
                if let Some(sh) = &gr.shading {
                    shade_glyph_span(
                        &mut row[dst0..dst1],
                        src,
                        sh,
                        rx0 as usize,
                        y as usize,
                        gr.alpha,
                        blend,
                    );
                } else {
                    (kernels.blend_mask)(&mut row[dst0..dst1], src, gr.rgb, gr.alpha);
                }
                covered += src.iter().filter(|&&c| c != 0).count() as u64;
                continue;
            }

            // Masked / non-Normal path: apply clip + soft coverage into scratch.
            scratch.clear();
            scratch.extend_from_slice(src);
            if let Some(m) = mask {
                let mw = m.stride();
                let (mbx, mby) = (m.bounds.x as usize, m.bounds.y as usize);
                let (mbw, mbh) = (m.bounds.width as usize, m.bounds.height as usize);
                let in_row = (y as usize) >= mby && (y as usize) < mby + mbh;
                let base = if in_row { (y as usize - mby) * mw } else { 0 };
                for (i, c) in scratch.iter_mut().enumerate() {
                    let x = rx0 as usize + i;
                    let mv = if in_row && x >= mbx && x < mbx + mbw {
                        m.data[base + (x - mbx)]
                    } else {
                        0
                    };
                    *c = mul_div_255(*c as u16, mv as u16) as u8;
                }
            }
            if let Some(sm) = soft {
                let sw = sm.stride();
                let (sbx, sby) = (sm.bounds.x as usize, sm.bounds.y as usize);
                let (sbw, sbh) = (sm.bounds.width as usize, sm.bounds.height as usize);
                let in_row = (y as usize) >= sby && (y as usize) < sby + sbh;
                let base = if in_row { (y as usize - sby) * sw } else { 0 };
                for (i, c) in scratch.iter_mut().enumerate() {
                    let x = rx0 as usize + i;
                    let sv = if in_row && x >= sbx && x < sbx + sbw {
                        sm.data[base + (x - sbx)]
                    } else {
                        sm.outside
                    };
                    *c = mul_div_255(*c as u16, sv as u16) as u8;
                }
            }
            covered += scratch.iter().filter(|&&c| c != 0).count() as u64;
            let dst = &mut row[dst0..dst1];
            if let Some(sh) = &gr.shading {
                shade_glyph_span(dst, &scratch, sh, rx0 as usize, y as usize, gr.alpha, blend);
            } else {
                match blend {
                    BlendChoice::Normal => (kernels.blend_mask)(dst, &scratch, gr.rgb, gr.alpha),
                    BlendChoice::Separable(f) => blend_span(dst, &scratch, gr.rgb, gr.alpha, f),
                    BlendChoice::NonSeparable(f) => {
                        blend_span_nonsep(dst, &scratch, gr.rgb, gr.alpha, f)
                    }
                }
            }
        }
    }

    stats.covered_pixels += covered;
    stats.ops_painted += 1;
    #[cfg(feature = "profiling")]
    {
        let profile = &mut stats.profile;
        let elapsed = command_start.elapsed();
        profile.add_duration("render.path", elapsed);
        profile.add_duration("render.path.glyph_runs", elapsed);
        profile.increment("render.glyph_runs", 1);
        profile.increment("render.glyph_blits", gr.placements.len() as u64);
    }
}

#[allow(clippy::too_many_arguments)]
fn paint_command(
    page: &CpuPreparedPage,
    cmd: &PreparedCommand,
    surface: &mut Surface,
    raster: &mut RasterKernel,
    kernels: &KernelSet,
    masks: &mut [Option<ClipMask>],
    soft: Option<&ClipMask>,
    stats: &mut RenderStats,
) {
    // Page-level commands are always timed; commands nested in tiling cells
    // (often tens of thousands of tiny fills) only at `ProfileDetail::Fill`.
    #[cfg(feature = "profiling")]
    let command_start =
        (stats.hot.time_nested || stats.hot.tiling_depth == 0).then(Instant::now);
    stats.commands += 1;
    // 0 = opaque rect, 1 = direct runs, 2 = clip-masked, 3 = otherwise modulated.
    #[cfg(feature = "profiling")]
    let mut path_kind = 0u8;
    #[cfg(feature = "profiling")]
    let mut rows_outside = 0u64;
    let mask_cid = if cmd.clip_has_mask {
        // Lowering guarantees a masked draw carries its clip id; skip the
        // draw (never panic a page) if that IR invariant broke upstream.
        let Some(cid) = cmd.clip else {
            page.diagnostics
                .note_degraded("fill skipped: masked clip without a clip id".into());
            return;
        };
        // Share the nearest path-clip ancestor's mask across rect descendants.
        let cid = page.clips[cid as usize].mask_source.unwrap_or(cid) as usize;
        if masks[cid].is_none() {
            #[cfg(feature = "profiling")]
            let mask_start = Instant::now();
            #[cfg(feature = "profiling")]
            {
                raster.prof.class = crate::render_cpu::raster::RasterClass::Clip;
            }
            let Some(mask) = build_render_clip_mask(page, raster, cid as u32, stats) else {
                return;
            };
            #[cfg(feature = "profiling")]
            {
                stats.hot.ns_clip_mask_lazy += mask_start.elapsed().as_nanos() as u64;
                stats.hot.n_clip_mask_lazy += 1;
                stats.hot.clip_mask_bytes += mask.data.len() as u64;
                stats.hot.clock_reads += 2;
            }
            masks[cid] = Some(mask);
        }
        Some(cid)
    } else {
        None
    };
    #[cfg(feature = "profiling")]
    {
        raster.prof.class = if stats.hot.tiling_depth > 0 {
            crate::render_cpu::raster::RasterClass::Other
        } else {
            crate::render_cpu::raster::RasterClass::Path
        };
    }

    match cmd.class {
        DrawClass::OpaqueRect => {
            paint_opaque_rect(cmd, surface, kernels);
            // An opaque rect marks its whole device rectangle; count it toward
            // coverage so an opaque-fill-only page is never a "silent blank".
            let b = cmd.bounds;
            stats.covered_pixels += b.width as u64 * b.height as u64;
            stats.ops_painted += 1;
        }
        DrawClass::SolidPath => {
            let (rs, re) = cmd.subpath_range;
            let subs = &page.subpaths[rs as usize..re as usize];
            let b = cmd.bounds;
            let (bx0, by0) = (b.x as usize, b.y as usize);
            let bx1 = (b.x as i64 + b.width as i64) as usize; // exclusive
            let by1 = (b.y as i64 + b.height as i64) as usize;
            // A path clip that rasterized to full coverage over its envelope
            // is rectangular for this fill, as for glyphs and images: drop the
            // mask so a solid fill keeps the run-aware path. Exact: the mask
            // multiply already skips 255, and the fill lies inside the mask
            // (checked, since pixels outside it would read `outside`).
            let mask = mask_cid
                .and_then(|cid| masks[cid].as_ref())
                .filter(|m| !(m.all_opaque && rect_contains(m.bounds, b)));
            let (rgb, alpha, opaque, premul) = (cmd.rgb, cmd.alpha, cmd.opaque, cmd.premul);
            let blend = choose_blend(cmd.blend);
            let shading = cmd.shading.as_deref();
            let stencil = cmd.stencil.as_deref();
            // The coverage buffer is sized to the device plane, not the
            // (possibly offset) surface; pass full device dims. The width is
            // the plane's even for a group or soft-mask offscreen: the raster
            // clamps edges at it, and clamping at the offscreen's right edge
            // re-shaped edges that continue past it (B14). Painting is still
            // restricted to the command bounds, which lie inside the surface.
            let width = (page.size.width as usize).max(surface.origin_x + surface.width);
            let height = surface.origin_y + surface.height;
            // A solid Normal fill with no per-pixel modulation paints the
            // raster's constant runs directly; anything else wants the plain
            // coverage buffer.
            let runs_direct = mask.is_none()
                && soft.is_none()
                && stencil.is_none()
                && shading.is_none()
                && matches!(blend, BlendChoice::Normal);
            #[cfg(feature = "profiling")]
            {
                path_kind = if runs_direct {
                    1
                } else if mask.is_some() {
                    2
                } else {
                    3
                };
            }

            // Rows outside the command's bounds are never painted, so they
            // are not rasterized either (the callback's check stays as the
            // guard it always was).
            if !raster.fill_runs_cancellable_in(
                &page.points,
                subs,
                width,
                height,
                cmd.rule,
                by0..by1,
                page.decode_limits.should_cancel.as_deref(),
                |y, x0, x1, cov, runs| {
                    if y < by0 || y >= by1 {
                        #[cfg(feature = "profiling")]
                        {
                            rows_outside += 1;
                        }
                        return false;
                    }
                    if runs_direct {
                        dispatch_runs(
                            surface, kernels, y, x0, x1, cov, runs, bx0, bx1, rgb, alpha, opaque,
                            premul,
                        );
                        false
                    } else {
                        for r in runs {
                            if let Some(c) = r.fill {
                                cov[r.x0 as usize..r.x1 as usize].fill(c);
                            }
                        }
                        dispatch_row(
                            surface, kernels, y, x0, x1, cov, bx0, bx1, mask, soft, rgb, alpha,
                            opaque, premul, blend, shading, stencil,
                        );
                        true
                    }
                },
            ) {
                stats.cancelled = true;
                return;
            }
            stats.ops_painted += 1;
            stats.edges += raster.last_edges;
            stats.rows_rasterized += raster.last_rows;
            stats.covered_pixels += raster.last_covered;
        }
    }
    #[cfg(feature = "profiling")]
    {
        // Plain-field accumulation; `ExecHot::flush_into` names these once
        // per page. The kernel's own phases (edge build, deposit, sweep, and
        // optionally the row callback) are in `raster.path.*`.
        let elapsed = command_start.map_or(0, |start| start.elapsed().as_nanos() as u64);
        let hot = &mut stats.hot;
        hot.ns_path += elapsed;
        hot.clock_reads += if command_start.is_some() { 2 } else { 0 };
        hot.rows_outside_bounds += rows_outside;
        if hot.tiling_depth > 0 {
            hot.ns_path_in_tiling += elapsed;
            hot.n_path_in_tiling += 1;
        }
        match cmd.class {
            DrawClass::OpaqueRect => {
                hot.ns_opaque_rects += elapsed;
                hot.n_opaque_rects += 1;
            }
            DrawClass::SolidPath => {
                hot.ns_solid_paths += elapsed;
                hot.n_solid_paths += 1;
                match path_kind {
                    1 => {
                        hot.ns_path_direct += elapsed;
                        hot.n_path_direct += 1;
                    }
                    2 => {
                        hot.ns_path_masked += elapsed;
                        hot.n_path_masked += 1;
                    }
                    _ => {
                        hot.ns_path_modulated += elapsed;
                        hot.n_path_modulated += 1;
                    }
                }
            }
        }
    }
}

/// Whether `inner` lies entirely inside `outer` (an empty `inner` always does).
fn rect_contains(outer: DeviceRect, inner: DeviceRect) -> bool {
    if inner.width == 0 || inner.height == 0 {
        return true;
    }
    let (ox1, oy1) = (
        outer.x as i64 + outer.width as i64,
        outer.y as i64 + outer.height as i64,
    );
    let (ix1, iy1) = (
        inner.x as i64 + inner.width as i64,
        inner.y as i64 + inner.height as i64,
    );
    inner.x >= outer.x && inner.y >= outer.y && ix1 <= ox1 && iy1 <= oy1
}

/// Composite an isolated group's offscreen surface back onto `parent` with
/// constant `opacity` and blend mode.
fn composite_group(
    parent: &mut Surface,
    group: &Surface,
    opacity: u8,
    blend: BlendChoice,
    soft: Option<&ClipMask>,
) {
    let pox = parent.origin_x;
    for ly in 0..group.height {
        let abs_y = group.origin_y + ly;
        let grow = group.local_row(ly);
        let prow = parent.row_mut(abs_y);
        for lx in 0..group.width {
            let src = &grow[lx * 4..lx * 4 + 4];
            if src[3] == 0 {
                continue;
            }
            let alpha = match soft {
                Some(sm) => {
                    let sv = soft_mask_at(sm, group.origin_x + lx, abs_y);
                    if sv == 0 {
                        continue;
                    }
                    mul_div_255(opacity as u16, sv as u16) as u8
                }
                None => opacity,
            };
            let plx = group.origin_x + lx - pox;
            composite_layer_px(&mut prow[plx * 4..plx * 4 + 4], src, alpha, blend);
        }
    }
}

/// Sample a soft mask at absolute device coordinates, yielding `sm.outside`
/// beyond its rendered extent (the same convention the per-paint path uses).
#[inline]
fn soft_mask_at(sm: &ClipMask, x: usize, y: usize) -> u8 {
    let (sbx, sby) = (sm.bounds.x as usize, sm.bounds.y as usize);
    let (sbw, sbh) = (sm.bounds.width as usize, sm.bounds.height as usize);
    if y >= sby && y < sby + sbh && x >= sbx && x < sbx + sbw {
        sm.data[(y - sby) * sm.stride() + (x - sbx)]
    } else {
        sm.outside
    }
}

/// Fold a *seeded* non-isolated group (Normal composite blend) back onto its
/// parent. The offscreen already holds `backdrop ∘ content`, so we do not
/// re-composite the backdrop; we linearly blend it over the parent at the
/// group's constant opacity: `parent = lerp(parent, offscreen, opacity)`. At
/// opacity 1 this is a replace (exact for the group); at opacity 0 a no-op.
/// Since offscreen and parent share the backdrop, untouched pixels lerp to
/// themselves — no darkening halo around the group's marks.
fn composite_group_seeded(
    parent: &mut Surface,
    group: &Surface,
    opacity: u8,
    soft: Option<&ClipMask>,
) {
    if opacity == 0 {
        return;
    }
    let pox = parent.origin_x;
    // Fully opaque and unmasked, every pixel takes the `t == 255` copy below,
    // so whole rows can be copied at once (the common wrapper group).
    let whole_rows = opacity == 255 && soft.is_none();
    for ly in 0..group.height {
        let abs_y = group.origin_y + ly;
        let grow = group.local_row(ly);
        let prow = parent.row_mut(abs_y);
        if whole_rows {
            let plx = group.origin_x - pox;
            prow[plx * 4..(plx + group.width) * 4].copy_from_slice(&grow[..group.width * 4]);
            continue;
        }
        for lx in 0..group.width {
            let src = &grow[lx * 4..lx * 4 + 4];
            // Masking the lerp weight is exactly right here: at mask 0 the
            // parent keeps the backdrop it already shares with the offscreen.
            let t = match soft {
                Some(sm) => {
                    let sv = soft_mask_at(sm, group.origin_x + lx, abs_y);
                    if sv == 0 {
                        continue;
                    }
                    mul_div_255(opacity as u16, sv as u16)
                }
                None => opacity as u16,
            };
            let plx = group.origin_x + lx - pox;
            let dst = &mut prow[plx * 4..plx * 4 + 4];
            if t == 255 {
                dst.copy_from_slice(src);
                continue;
            }
            for c in 0..4 {
                // lerp(dst, src, t/255) in integer space.
                dst[c] =
                    (mul_div_255(dst[c] as u16, 255 - t) + mul_div_255(src[c] as u16, t)) as u8;
            }
        }
    }
}

/// Composite one straight-alpha source color onto a premultiplied pixel under
/// an arbitrary blend choice. `rgb` is the straight source color; `a` is the
/// *effective* source alpha (coverage, constant alpha, and the source color's
/// own alpha already folded in). The `Normal` arm is the exact integer
/// source-over that the fast paths inline (byte-identical); the non-Normal
/// arms are the per-pixel-color analog of `blend_span`/`blend_span_nonsep`,
/// used by paints whose color varies per pixel (shadings, images, tiling
/// cells).
#[inline]
fn composite_px_blended(px: &mut [u8], rgb: [u8; 3], a: u8, blend: BlendChoice) {
    if a == 0 {
        return;
    }
    match blend {
        BlendChoice::Normal => {
            let a = a as u16;
            let ia = 255 - a;
            px[0] = (mul_div_255(rgb[0] as u16, a) + mul_div_255(px[0] as u16, ia)) as u8;
            px[1] = (mul_div_255(rgb[1] as u16, a) + mul_div_255(px[1] as u16, ia)) as u8;
            px[2] = (mul_div_255(rgb[2] as u16, a) + mul_div_255(px[2] as u16, ia)) as u8;
            px[3] = (a + mul_div_255(px[3] as u16, ia)) as u8;
        }
        BlendChoice::Separable(f) => {
            let cs = [
                rgb[0] as f32 / 255.0,
                rgb[1] as f32 / 255.0,
                rgb[2] as f32 / 255.0,
            ];
            let a_s = a as f32 / 255.0;
            let da = px[3] as f32 / 255.0;
            let inv_da = if da > 0.0 { 1.0 / da } else { 0.0 };
            let b = [
                f(px[0] as f32 / 255.0 * inv_da, cs[0]),
                f(px[1] as f32 / 255.0 * inv_da, cs[1]),
                f(px[2] as f32 / 255.0 * inv_da, cs[2]),
            ];
            composite_px(px, cs, a_s, b, da);
        }
        BlendChoice::NonSeparable(f) => {
            let cs = [
                rgb[0] as f32 / 255.0,
                rgb[1] as f32 / 255.0,
                rgb[2] as f32 / 255.0,
            ];
            let a_s = a as f32 / 255.0;
            let da = px[3] as f32 / 255.0;
            let inv_da = if da > 0.0 { 1.0 / da } else { 0.0 };
            let cb = [
                px[0] as f32 / 255.0 * inv_da,
                px[1] as f32 / 255.0 * inv_da,
                px[2] as f32 / 255.0 * inv_da,
            ];
            let b = f(cb, cs);
            composite_px(px, cs, a_s, b, da);
        }
    }
}

/// Composite one premultiplied group pixel `src` onto `dst` at group opacity.
///
/// An opaque source at full opacity under Normal replaces `dst` outright:
/// the general path below returns exactly `src` for every source value and
/// every backdrop (`opaque_normal_layer_composite_is_a_copy` checks all
/// 256 x 256 x 256 channel, backdrop and backdrop-alpha combinations), so
/// the copy skips its float work for the bulk of a typical group.
#[inline]
fn composite_layer_px(dst: &mut [u8], src: &[u8], opacity: u8, blend: BlendChoice) {
    if src[3] == 255 && opacity == 255 && matches!(blend, BlendChoice::Normal) {
        dst[..4].copy_from_slice(&src[..4]);
        return;
    }
    composite_layer_px_general(dst, src, opacity, blend);
}

/// [`composite_layer_px`] without the opaque-copy shortcut.
#[inline]
fn composite_layer_px_general(dst: &mut [u8], src: &[u8], opacity: u8, blend: BlendChoice) {
    let sa = src[3] as f32 / 255.0;
    if sa <= 0.0 {
        return;
    }
    let a_s = sa * (opacity as f32 / 255.0);
    if a_s <= 0.0 {
        return;
    }
    let inv = 1.0 / sa;
    let cs = [
        src[0] as f32 / 255.0 * inv,
        src[1] as f32 / 255.0 * inv,
        src[2] as f32 / 255.0 * inv,
    ];
    let da = dst[3] as f32 / 255.0;
    let b = match blend {
        BlendChoice::Normal => cs,
        BlendChoice::Separable(f) => {
            let inv_da = if da > 0.0 { 1.0 / da } else { 0.0 };
            [
                f(dst[0] as f32 / 255.0 * inv_da, cs[0]),
                f(dst[1] as f32 / 255.0 * inv_da, cs[1]),
                f(dst[2] as f32 / 255.0 * inv_da, cs[2]),
            ]
        }
        BlendChoice::NonSeparable(f) => {
            let inv_da = if da > 0.0 { 1.0 / da } else { 0.0 };
            let cb = [
                dst[0] as f32 / 255.0 * inv_da,
                dst[1] as f32 / 255.0 * inv_da,
                dst[2] as f32 / 255.0 * inv_da,
            ];
            f(cb, cs)
        }
    };
    composite_px(dst, cs, a_s, b, da);
}

/// Direct row fill for an integer-aligned opaque rectangle — no coverage. The
/// bounds already include any rectangular clip intersection.
fn paint_opaque_rect(cmd: &PreparedCommand, surface: &mut Surface, kernels: &KernelSet) {
    let b = cmd.bounds;
    let ox = surface.origin_x;
    let x0 = b.x as usize;
    let x1 = (b.x as i64 + b.width as i64) as usize;
    let y0 = b.y as usize;
    let y1 = (b.y as i64 + b.height as i64) as usize;
    for y in y0..y1 {
        let row = surface.row_mut(y);
        (kernels.fill_opaque)(&mut row[(x0 - ox) * 4..(x1 - ox) * 4], cmd.premul);
    }
}

/// Clip the coverage row to `[bx0, bx1)`, apply the optional mask, then
/// classify the surviving coverage into spans and dispatch a kernel per span.
#[allow(clippy::too_many_arguments)]
#[inline]
fn dispatch_row(
    surface: &mut Surface,
    kernels: &KernelSet,
    y: usize,
    x0: usize,
    x1: usize,
    cov: &mut [u8],
    bx0: usize,
    bx1: usize,
    mask: Option<&ClipMask>,
    soft: Option<&ClipMask>,
    rgb: [u8; 3],
    alpha: u8,
    opaque: bool,
    premul: [u8; 4],
    blend: BlendChoice,
    shading: Option<&crate::render_cpu::prepared::PreparedShading>,
    stencil: Option<&crate::render_cpu::image::PreparedImage>,
) {
    // Restrict to the clip's column envelope.
    let cxa = x0.max(bx0);
    let cxb = x1.min(bx1.saturating_sub(1));
    if cxa > cxb {
        return;
    }
    // Apply the non-rectangular clip mask (per-pixel multiply).
    if let Some(m) = mask {
        let mw = m.stride();
        let base = (y - m.bounds.y as usize) * mw;
        let mbx = m.bounds.x as usize;
        #[allow(clippy::needless_range_loop)] // cov and mask index at different offsets
        for x in cxa..=cxb {
            let mv = m.data[base + (x - mbx)];
            if mv != 255 {
                cov[x] = mul_div_255(cov[x] as u16, mv as u16) as u8;
            }
        }
    }
    // Apply the active soft mask: pixels outside its bounds are fully masked.
    if let Some(sm) = soft {
        let sw = sm.stride();
        let (sbx, sby) = (sm.bounds.x as usize, sm.bounds.y as usize);
        let sbw = sm.bounds.width as usize;
        let sbh = sm.bounds.height as usize;
        let in_row = y >= sby && y < sby + sbh;
        let base = if in_row { (y - sby) * sw } else { 0 };
        #[allow(clippy::needless_range_loop)] // cov and mask index at different offsets
        for x in cxa..=cxb {
            let sv = if in_row && x >= sbx && x < sbx + sbw {
                sm.data[base + (x - sbx)]
            } else {
                sm.outside
            };
            cov[x] = mul_div_255(cov[x] as u16, sv as u16) as u8;
        }
    }
    // A shading-painted `/ImageMask` contributes coverage rather than color.
    // Sampling the already-prepared image preserves decode polarity,
    // interpolation, minification, rotation and shear.
    if let Some(stencil) = stencil {
        #[allow(clippy::needless_range_loop)]
        for x in cxa..=cxb {
            let alpha = stencil
                .shade(x as f64 + 0.5, y as f64 + 0.5)
                .map_or(0, |sample| sample[3]);
            cov[x] = mul_div_255(cov[x] as u16, alpha as u16) as u8;
        }
    }

    // Local column offset for a possibly-offset (group offscreen) surface.
    let ox = surface.origin_x;

    // Shading paint: evaluate the ramp per pixel and composite under the
    // command's blend (`composite_px_blended`'s Normal arm is the exact
    // integer source-over this path always used).
    if let Some(sh) = shading {
        let row = surface.row_mut(y);
        for x in cxa..=cxb {
            let c = cov[x];
            if c == 0 {
                continue;
            }
            let Some(color) = shade_pixel(sh, x as f64 + 0.5, y as f64 + 0.5) else {
                continue;
            };
            let a = mul_div_255(c as u16, mul_div_255(color[3] as u16, alpha as u16)) as u8;
            if a == 0 {
                continue;
            }
            let px = &mut row[(x - ox) * 4..(x - ox) * 4 + 4];
            composite_px_blended(px, [color[0], color[1], color[2]], a, blend);
        }
        return;
    }

    let row = surface.row_mut(y);

    // Non-Normal blend modes take the general per-pixel compositor.
    match blend {
        BlendChoice::Separable(bfn) => {
            blend_span(
                &mut row[(cxa - ox) * 4..(cxb + 1 - ox) * 4],
                &cov[cxa..=cxb],
                rgb,
                alpha,
                bfn,
            );
            return;
        }
        BlendChoice::NonSeparable(bfn) => {
            blend_span_nonsep(
                &mut row[(cxa - ox) * 4..(cxb + 1 - ox) * 4],
                &cov[cxa..=cxb],
                rgb,
                alpha,
                bfn,
            );
            return;
        }
        BlendChoice::Normal => {}
    }

    classify_spans(row, ox, cov, cxa, cxb, kernels, rgb, alpha, opaque, premul);
}

/// [`dispatch_row`] for the common solid case (Normal blend, no clip mask,
/// soft mask, stencil or shading) with the row handed over as
/// [`CovRun`]s: constant runs are painted directly — a full-coverage run is
/// one `fill_opaque`/`blend_const`, a partial constant one `blend_const` at
/// the scaled alpha — and only the cell runs go through span
/// classification. Byte-identical to materializing the runs and calling
/// `dispatch_row`: every pixel gets the kernel the classifier would choose
/// for its coverage byte (`blend_const` at `a = c·alpha` is `blend_mask`'s
/// arithmetic at constant coverage `c`; checked by
/// `kernels::tests::blend_const_matches_blend_mask_at_constant_coverage`).
#[allow(clippy::too_many_arguments)]
#[inline]
fn dispatch_runs(
    surface: &mut Surface,
    kernels: &KernelSet,
    y: usize,
    x0: usize,
    x1: usize,
    cov: &[u8],
    runs: &[CovRun],
    bx0: usize,
    bx1: usize,
    rgb: [u8; 3],
    alpha: u8,
    opaque: bool,
    premul: [u8; 4],
) {
    let cxa = x0.max(bx0);
    let cxb = x1.min(bx1.saturating_sub(1));
    if cxa > cxb {
        return;
    }
    let ox = surface.origin_x;
    let row = surface.row_mut(y);
    for r in runs {
        let s = (r.x0 as usize).max(cxa);
        let e = (r.x1 as usize).min(cxb + 1);
        if s >= e {
            continue;
        }
        match r.fill {
            None => classify_spans(row, ox, cov, s, e - 1, kernels, rgb, alpha, opaque, premul),
            Some(0) => {}
            Some(255) => {
                let dst = &mut row[(s - ox) * 4..(e - ox) * 4];
                if opaque {
                    (kernels.fill_opaque)(dst, premul);
                } else {
                    (kernels.blend_const)(dst, rgb, alpha);
                }
            }
            Some(c) => {
                let a = if alpha == 255 {
                    c
                } else {
                    mul_div_255(c as u16, alpha as u16) as u8
                };
                (kernels.blend_const)(&mut row[(s - ox) * 4..(e - ox) * 4], rgb, a);
            }
        }
    }
}

/// Classify `cov[cxa..=cxb]` into empty, full and partial spans and dispatch
/// one kernel per span onto `row` (a surface row whose column 0 is device
/// column `ox`).
#[allow(clippy::too_many_arguments)]
#[inline]
fn classify_spans(
    row: &mut [u8],
    ox: usize,
    cov: &[u8],
    cxa: usize,
    cxb: usize,
    kernels: &KernelSet,
    rgb: [u8; 3],
    alpha: u8,
    opaque: bool,
    premul: [u8; 4],
) {
    // Span classification. Runs of empty or full coverage are the common case
    // (the interior of any shape wider than a few pixels), so both are walked
    // eight bytes at a time before the per-byte tail.
    const CHUNK: usize = 8;
    let mut x = cxa;
    while x <= cxb {
        let c = cov[x];
        if c == 0 {
            x += 1;
            while x + CHUNK <= cxb + 1 && cov[x..x + CHUNK] == [0u8; CHUNK] {
                x += CHUNK;
            }
            while x <= cxb && cov[x] == 0 {
                x += 1;
            }
            continue;
        }
        if c == 255 {
            let start = x;
            x += 1;
            while x + CHUNK <= cxb + 1 && cov[x..x + CHUNK] == [255u8; CHUNK] {
                x += CHUNK;
            }
            while x <= cxb && cov[x] == 255 {
                x += 1;
            }
            let dst = &mut row[(start - ox) * 4..(x - ox) * 4];
            if opaque {
                (kernels.fill_opaque)(dst, premul);
            } else {
                (kernels.blend_const)(dst, rgb, alpha);
            }
        } else {
            let start = x;
            while x <= cxb && cov[x] != 0 && cov[x] != 255 {
                x += 1;
            }
            let dst = &mut row[(start - ox) * 4..(x - ox) * 4];
            (kernels.blend_mask)(dst, &cov[start..x], rgb, alpha);
        }
    }
}

#[cfg(test)]
mod rgb8_area_min_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;
    use crate::page_ir::{BlendMode, DeviceRect, ImageColorSpace, InterpolationMode, Matrix};
    use crate::render_api::Background;
    use crate::render_cpu::image::PreparedImage;
    use crate::render_cpu::surface::Surface;
    use std::sync::Arc;

    /// Tiny deterministic xorshift, so the fuzz is reproducible.
    struct Rng(u64);
    impl Rng {
        fn next(&mut self) -> u64 {
            let mut x = self.0;
            x ^= x << 13;
            x ^= x >> 7;
            x ^= x << 17;
            self.0 = x;
            x
        }
        fn byte(&mut self) -> u8 {
            (self.next() >> 24) as u8
        }
    }

    fn make_image_cs(
        sw: u32,
        sh: u32,
        dev_w: u32,
        dev_h: u32,
        color_space: ImageColorSpace,
        samples: Vec<u8>,
    ) -> PreparedImage {
        let mut img = make_image(sw, sh, dev_w, dev_h, Vec::new());
        img.color_space = color_space;
        img.samples = Arc::from(samples);
        img
    }

    fn make_image(sw: u32, sh: u32, dev_w: u32, dev_h: u32, samples: Vec<u8>) -> PreparedImage {
        // Image unit square maps to device [0,dev_w)x[0,dev_h): u = dx/dev_w,
        // v = dy/dev_h, off-diagonals exactly zero. Footprint = source texels
        // per device pixel, exactly as lowering computes it.
        let inv = Matrix {
            a: 1.0 / dev_w as f64,
            b: 0.0,
            c: 0.0,
            d: 1.0 / dev_h as f64,
            e: 0.0,
            f: 0.0,
        };
        PreparedImage {
            origin: crate::page_ir::PaintOrigin::PageContent,
            bounds: DeviceRect {
                x: 0,
                y: 0,
                width: dev_w,
                height: dev_h,
            },
            clip: None,
            clip_has_mask: false,
            inv,
            width: sw,
            height: sh,
            bpc: 8,
            color_space: ImageColorSpace::Rgb,
            decode: None,
            samples: Arc::from(samples),
            sample_lut: None,
            smask: None,
            mask: None,
            interpolation: InterpolationMode::Nearest,
            footprint: [sw as f64 / dev_w as f64, sh as f64 / dev_h as f64],
            is_stencil: false,
            stencil_rgb: [0, 0, 0],
            alpha: 255,
            blend: BlendMode::Normal,
        }
    }

    /// The fast path must reproduce, byte for byte, the generic per-pixel
    /// `shade()` area-average + opaque write, over a fuzzed image and several
    /// minifying footprints.
    #[test]
    fn fast_path_matches_generic_shade() {
        let mut rng = Rng(0x1234_5678_9abc_def0);
        // A spread of source sizes and device sizes (all minifying: dev < src).
        let cases = [
            (7u32, 5u32, 3u32, 3u32),
            (16, 16, 5, 7),
            (33, 9, 8, 4),
            (9, 33, 4, 8),
            (64, 48, 20, 15),
            (5, 5, 4, 2), // one axis barely minified, other strongly
        ];
        for &(sw, sh, dev_w, dev_h) in &cases {
            for _trial in 0..8 {
                let samples: Vec<u8> = (0..(sw * sh * 3)).map(|_| rng.byte()).collect();
                let img = make_image(sw, sh, dev_w, dev_h, samples);
                // Fast path renders into `fast`.
                let mut fast =
                    Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                let (painted, taps) = paint_axis_aligned_rgb8_area_min_opaque(
                    &img,
                    &mut fast,
                    0,
                    0,
                    dev_w as usize,
                    dev_h as usize,
                );
                // Reference: generic `shade()` + opaque source-over over a
                // transparent surface (which reduces to a direct copy).
                let mut reference =
                    Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                let mut ref_painted = 0u64;
                let _ = taps; // profiling-only telemetry; not asserted here
                for y in 0..dev_h as usize {
                    let row = reference.row_mut(y);
                    for x in 0..dev_w as usize {
                        let color = img.shade(x as f64 + 0.5, y as f64 + 0.5);
                        if let Some(c) = color {
                            let a = mul_div_255(mul_div_255(c[3] as u16, 255), 255);
                            if a == 0 {
                                continue;
                            }
                            let ia = 255 - a;
                            let px = &mut row[x * 4..x * 4 + 4];
                            px[0] =
                                (mul_div_255(c[0] as u16, a) + mul_div_255(px[0] as u16, ia)) as u8;
                            px[1] =
                                (mul_div_255(c[1] as u16, a) + mul_div_255(px[1] as u16, ia)) as u8;
                            px[2] =
                                (mul_div_255(c[2] as u16, a) + mul_div_255(px[2] as u16, ia)) as u8;
                            px[3] = (a + mul_div_255(px[3] as u16, ia)) as u8;
                            ref_painted += 1;
                        }
                    }
                }
                assert_eq!(
                    painted, ref_painted,
                    "painted count sw={sw} sh={sh} dev={dev_w}x{dev_h}"
                );
                for y in 0..dev_h as usize {
                    let fr = fast.row_mut(y).to_vec();
                    let rr = reference.row_mut(y).to_vec();
                    assert_eq!(
                        fr, rr,
                        "row {y} differs sw={sw} sh={sh} dev={dev_w}x{dev_h}"
                    );
                }
            }
        }
    }

    /// A packed one-bit mask bitmap of `w x h`, byte-aligned rows.
    fn bilevel(w: u32, h: u32, rng: &mut Rng) -> Arc<crate::page_ir::ImageSMask> {
        let row_bytes = (w as usize).div_ceil(8);
        let samples: Vec<u8> = (0..row_bytes * h as usize).map(|_| rng.byte()).collect();
        Arc::new(crate::page_ir::ImageSMask {
            width: w,
            height: h,
            bits_per_component: 1,
            decode: None,
            samples: Arc::from(samples),
            codec: None,
            codec_data: None,
            codec_parms: None,
        })
    }

    /// The generic `paint_image` body for the shape the masked area-min path
    /// serves: no clip mask, no soft clip, opaque `alpha`, Normal blend.
    fn generic_masked_reference(img: &PreparedImage, dev_w: u32, dev_h: u32) -> (Surface, u64) {
        let mut reference = Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
        let mut painted = 0u64;
        for y in 0..dev_h as usize {
            let row = reference.row_mut(y);
            for x in 0..dev_w as usize {
                let (dx, dy) = (x as f64 + 0.5, y as f64 + 0.5);
                let edge = img.edge_coverage(dx, dy);
                if edge == Some(0) {
                    continue;
                }
                let color = match edge {
                    None => img.shade(dx, dy),
                    Some(_) => img.shade_clamped(dx, dy),
                };
                let Some(c) = color else { continue };
                let cov = match edge {
                    Some(ec) => mul_div_255(255, ec),
                    None => 255,
                };
                let a = mul_div_255(mul_div_255(c[3] as u16, 255), cov);
                if a == 0 {
                    continue;
                }
                let px = &mut row[x * 4..x * 4 + 4];
                composite_px_blended(px, [c[0], c[1], c[2]], a as u8, BlendChoice::Normal);
                painted += 1;
            }
        }
        (reference, painted)
    }

    /// The MRC path — minified RGB8 cut out by a bilevel layer — must reproduce
    /// the generic per-pixel body byte for byte, in **both** mask encodings and
    /// including the anti-aliased border band. Mask dimensions are varied
    /// independently of the base image's, as MRC producers do.
    #[test]
    fn masked_fast_path_matches_generic_shade() {
        let mut rng = Rng(0x00c0_ffee_0bad_f00d);
        let cases = [
            (7u32, 5u32, 3u32, 3u32),
            (16, 16, 5, 7),
            (33, 9, 8, 4),
            (9, 33, 4, 8),
            (64, 48, 20, 15),
            (5, 5, 4, 2),
        ];
        for &(sw, sh, dev_w, dev_h) in &cases {
            // Mask geometries: same as the base, coarser, and finer.
            for &(mw, mh) in &[(sw, sh), (sw * 2, sh * 2), (sw.div_ceil(2), sh.div_ceil(2))] {
                for trial in 0..6 {
                    let samples: Vec<u8> = (0..(sw * sh * 3)).map(|_| rng.byte()).collect();
                    let mut img = make_image(sw, sh, dev_w, dev_h, samples);
                    let mask = bilevel(mw, mh, &mut rng);
                    // Alternate the two encodings, and exercise `/Decode [1 0]`
                    // polarity on the soft-mask side.
                    let soft = trial % 2 == 0;
                    if soft {
                        let mut sm = (*mask).clone();
                        if trial % 4 == 0 {
                            sm.decode = Some(Arc::from(vec![[1.0f32, 0.0f32]]));
                        }
                        img.smask = Some(Arc::new(sm));
                    } else {
                        img.mask = Some(crate::page_ir::ImageMask::Stencil(mask));
                    }

                    let Some(kind) = area_min_mask(&img) else {
                        // Only a non-minifying soft mask is turned away, and
                        // then the generic path is already what runs.
                        assert!(soft, "a stencil mask is always eligible");
                        continue;
                    };
                    let mut fast =
                        Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                    let (painted, _taps) = paint_axis_aligned_rgb8_area_min_masked(
                        &img,
                        kind,
                        &mut fast,
                        0,
                        0,
                        dev_w as usize,
                        dev_h as usize,
                    );

                    let (mut reference, ref_painted) = generic_masked_reference(&img, dev_w, dev_h);
                    let what = if soft { "smask" } else { "stencil" };
                    assert_eq!(
                        painted, ref_painted,
                        "{what} painted count sw={sw} sh={sh} mask={mw}x{mh} dev={dev_w}x{dev_h}"
                    );
                    for y in 0..dev_h as usize {
                        assert_eq!(
                            fast.row_mut(y).to_vec(),
                            reference.row_mut(y).to_vec(),
                            "{what} row {y} differs sw={sw} sh={sh} mask={mw}x{mh} dev={dev_w}x{dev_h}"
                        );
                    }
                }
            }
        }
    }

    /// The eight-bit soft-mask variant of the MRC path must reproduce the
    /// generic per-pixel body byte for byte — the f64 box filter, the
    /// `/Decode` remap, the alpha narrowing and the source-over composite —
    /// including the anti-aliased border band, over mask geometries that
    /// differ from the base image's.
    #[test]
    fn masked8_fast_path_matches_generic_shade() {
        let mut rng = Rng(0x8b17_5caf_e000_0001);
        let cases = [
            (7u32, 5u32, 3u32, 3u32),
            (16, 16, 5, 7),
            (33, 9, 8, 4),
            (9, 33, 4, 8),
            (64, 48, 20, 15),
            (5, 5, 4, 2),
        ];
        for &(sw, sh, dev_w, dev_h) in &cases {
            for &(mw, mh) in &[(sw, sh), (sw * 2, sh * 2), (sw.div_ceil(2), sh.div_ceil(2))] {
                for trial in 0..4 {
                    let samples: Vec<u8> = (0..(sw * sh * 3)).map(|_| rng.byte()).collect();
                    let mut img = make_image(sw, sh, dev_w, dev_h, samples);
                    // Mostly opaque with transparent holes, like a cover's
                    // transparency layer, so both the skip and the composite
                    // run; odd trials invert through `/Decode [1 0]`.
                    let mask: Vec<u8> = (0..mw * mh)
                        .map(|_| if rng.byte() < 40 { rng.byte() } else { 255 })
                        .collect();
                    img.smask = Some(Arc::new(crate::page_ir::ImageSMask {
                        width: mw,
                        height: mh,
                        bits_per_component: 8,
                        decode: (trial % 2 == 1).then(|| Arc::from(vec![[1.0f32, 0.0f32]])),
                        samples: Arc::from(mask),
                        codec: None,
                        codec_data: None,
                        codec_parms: None,
                    }));
                    let Some(kind) = area_min_mask(&img) else {
                        // A non-minifying mask is turned away; the generic
                        // path is then already what runs.
                        continue;
                    };
                    assert!(matches!(kind, AreaMinMask::Soft8(_)));
                    let mut fast =
                        Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                    let (painted, _taps) = paint_axis_aligned_rgb8_area_min_masked(
                        &img,
                        kind,
                        &mut fast,
                        0,
                        0,
                        dev_w as usize,
                        dev_h as usize,
                    );
                    let (mut reference, ref_painted) = generic_masked_reference(&img, dev_w, dev_h);
                    let what = format!(
                        "smask8 sw={sw} sh={sh} mask={mw}x{mh} dev={dev_w}x{dev_h} trial={trial}"
                    );
                    assert_eq!(painted, ref_painted, "{what}: painted count");
                    assert_surfaces_equal(&mut fast, &mut reference, &what);
                }
            }
        }
    }

    /// A blocky mask like a scanned page's foreground layer or a cover's
    /// opacity layer: large clear and set regions, a band of noise, so the
    /// uniform-box shortcuts and the per-tap filters both run, at one and
    /// eight bits, both `/Decode` polarities, mask geometries narrower and
    /// much wider than the base (boxes wider than one 57-bit window), and
    /// placements offset into the surface.
    #[test]
    fn masked_uniform_boxes_match_generic_shade() {
        let mut rng = Rng(0x5eed_b10c_4a11_0001);
        let cases = [
            (7u32, 5u32, 3u32, 3u32),
            (33, 9, 8, 4),
            (64, 48, 20, 15),
            (90, 70, 31, 23),
            (40, 40, 3, 2),
        ];
        for &(sw, sh, dev_w, dev_h) in &cases {
            for &(mw, mh) in &[
                (sw, sh),
                (sw * 3, sh * 3),
                (sw * 8 + 5, sh * 2 + 1),
                (sw.div_ceil(2), sh.div_ceil(2)),
            ] {
                for trial in 0..8 {
                    let samples: Vec<u8> = (0..(sw * sh * 3)).map(|_| rng.byte()).collect();
                    let mut img = make_image(sw, sh, dev_w, dev_h, samples);
                    let one_bit = trial % 2 == 0;
                    // Blocks of 16x8 mask texels: clear, set, or noisy, with
                    // every fourth band of rows clear across the whole width
                    // (a blank line).
                    let block = |x: u32, y: u32, rng: &mut Rng| -> u8 {
                        if (y / 8) % 4 == 3 {
                            return 0;
                        }
                        let kind = ((x / 16) * 7 + (y / 8) * 3 + trial) % 5;
                        match kind {
                            0 | 1 => 0,
                            2 | 3 => 255,
                            _ => rng.byte(),
                        }
                    };
                    let samples: Vec<u8> = if one_bit {
                        let row_bytes = (mw as usize).div_ceil(8);
                        let mut packed = vec![0u8; row_bytes * mh as usize];
                        for y in 0..mh {
                            for x in 0..mw {
                                if block(x, y, &mut rng) >= 128 {
                                    packed[y as usize * row_bytes + x as usize / 8] |=
                                        0x80 >> (x % 8);
                                }
                            }
                        }
                        packed
                    } else {
                        (0..mh)
                            .flat_map(|y| (0..mw).map(move |x| (x, y)))
                            .map(|(x, y)| block(x, y, &mut rng))
                            .collect()
                    };
                    img.smask = Some(Arc::new(crate::page_ir::ImageSMask {
                        width: mw,
                        height: mh,
                        bits_per_component: if one_bit { 1 } else { 8 },
                        decode: (trial % 4 >= 2).then(|| Arc::from(vec![[1.0f32, 0.0f32]])),
                        samples: Arc::from(samples),
                        codec: None,
                        codec_data: None,
                        codec_parms: None,
                    }));
                    let Some(kind) = area_min_mask(&img) else {
                        continue;
                    };
                    let what = format!(
                        "bits={} sw={sw} sh={sh} mask={mw}x{mh} dev={dev_w}x{dev_h} trial={trial}",
                        if one_bit { 1 } else { 8 }
                    );
                    let mut fast =
                        Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                    let (painted, _taps) = paint_axis_aligned_rgb8_area_min_masked(
                        &img,
                        kind,
                        &mut fast,
                        0,
                        0,
                        dev_w as usize,
                        dev_h as usize,
                    );
                    let (mut reference, ref_painted) = generic_masked_reference(&img, dev_w, dev_h);
                    assert_eq!(painted, ref_painted, "{what}: painted count");
                    assert_surfaces_equal(&mut fast, &mut reference, &what);
                }
            }
        }
    }

    /// The windowed one-bit coverage and the regrouped RGB8 box sum must equal
    /// the per-tap originals for arbitrary tap boxes: every phase of `lo`
    /// within a byte, widths from one texel to past the 57-bit window, rows
    /// at the very end of a truncated buffer.
    #[test]
    fn windowed_mask_and_box_sum_match_per_tap_reference() {
        let mut rng = Rng(0x0dd5_eed5_7a95_0002);
        for _ in 0..4000 {
            let mw = 1 + (rng.next() % 150) as u32;
            let mh = 1 + (rng.next() % 12) as u32;
            let row_bytes = (mw as usize).div_ceil(8);
            let density = rng.byte();
            let mut samples: Vec<u8> = (0..row_bytes * mh as usize)
                .map(|_| {
                    let mut b = 0u8;
                    for bit in 0..8 {
                        if rng.byte() < density {
                            b |= 1 << bit;
                        }
                    }
                    b
                })
                .collect();
            if rng.byte() < 32 {
                // A truncated payload: the filters read missing bytes as zero.
                let keep = (rng.next() as usize) % (samples.len() + 1);
                samples.truncate(keep);
            }
            let sm = crate::page_ir::ImageSMask {
                width: mw,
                height: mh,
                bits_per_component: 1,
                decode: None,
                samples: Arc::from(samples),
                codec: None,
                codec_data: None,
                codec_parms: None,
            };
            let f =
                |len: u32, rng: &mut Rng| (rng.next() % (len as u64 * 100)) as f64 / 100.0 - 0.5;
            let half = |rng: &mut Rng| 0.5 + (rng.next() % 4000) as f64 / 100.0;
            let Some(tx) =
                crate::render_cpu::image::axis_box_taps(f(mw, &mut rng), half(&mut rng), mw)
            else {
                continue;
            };
            let Some(ty) =
                crate::render_cpu::image::axis_box_taps(f(mh, &mut rng), half(&mut rng), mh)
            else {
                continue;
            };
            let fast = bilevel_smask_coverage_windowed(&sm, &tx, &ty);
            let reference = crate::render_cpu::image::bilevel_smask_coverage(&sm, &tx, &ty);
            assert_eq!(
                fast.to_bits(),
                reference.to_bits(),
                "coverage {tx:?} {ty:?}"
            );

            // The same boxes over an RGB8 image of the mask's size.
            let rgb: Vec<u8> = (0..mw * mh * 3).map(|_| rng.byte()).collect();
            let stride = mw as usize * 3;
            let weight = tx.total * ty.total;
            let mut acc = [0u64; 3];
            for sr in ty.lo..=ty.hi {
                for col in tx.lo..=tx.hi {
                    let w = ty.weight_at(sr) * tx.weight_at(col);
                    let o = sr as usize * stride + col as usize * 3;
                    for c in 0..3 {
                        acc[c] += w * rgb[o + c] as u64;
                    }
                }
            }
            let expect = acc.map(|a| ((a + weight / 2) / weight).min(255) as u8);
            assert_eq!(
                rgb8_box_average(&rgb, stride, &tx, &ty, weight),
                expect,
                "box {tx:?} {ty:?}"
            );
        }
    }

    /// The row filter must reproduce the per-pixel box average byte for byte
    /// with every kernel: boxes of one to dozens of texels on either axis
    /// (the three-tap and the looped horizontal sums), rows revisited in
    /// both directions and out of order (the cache), boxes taller than the
    /// filter serves (it declines), and the near-white sums where the
    /// rounding division lands on exact multiples.
    #[test]
    fn row_box_filter_matches_per_pixel_box_average() {
        let mut rng = Rng(0x0b0c_5f11_7e40_0004);
        for kernel in available_kernels() {
            for trial in 0..60 {
                let sw = 1 + (rng.next() % 90) as u32;
                let sh = 1 + (rng.next() % 90) as u32;
                let rgb: Vec<u8> = (0..sw * sh * 3)
                    .map(|_| match trial % 3 {
                        0 => rng.byte(),
                        1 => 255 - (rng.byte() & 3),
                        _ => [0, 255][(rng.byte() & 1) as usize],
                    })
                    .collect();
                let stride = sw as usize * 3;
                let half = |rng: &mut Rng| 0.5 + (rng.next() % 1200) as f64 / 100.0;
                let (hx, hy) = (half(&mut rng), half(&mut rng));
                let pos =
                    |len: u32, rng: &mut Rng| (rng.next() % (len as u64 * 64)) as f64 / 64.0 - 0.5;
                let n = 1 + (rng.next() % 40) as usize;
                let mut cols: Vec<crate::render_cpu::image::AxisTaps> = (0..n)
                    .filter_map(|_| {
                        crate::render_cpu::image::axis_box_taps(pos(sw, &mut rng), hx, sw)
                    })
                    .collect();
                if cols.is_empty() {
                    continue;
                }
                cols.sort_by_key(|t| t.lo);
                let rows: Vec<crate::render_cpu::image::AxisTaps> = (0..30)
                    .filter_map(|_| {
                        crate::render_cpu::image::axis_box_taps(pos(sh, &mut rng), hy, sh)
                    })
                    .collect();
                let max_row_total = rows.iter().map(|t| t.total).max().unwrap_or(1);
                let mut filter = RowBoxFilter::new(&rgb, stride, &cols, max_row_total).unwrap();
                filter.kernel = kernel;
                let mut dst = vec![0u8; cols.len() * 4];
                for ty in &rows {
                    let served = filter.average_row(ty, &mut dst);
                    assert_eq!(
                        served,
                        ((ty.hi - ty.lo) as usize) < RowBoxFilter::MAX_ROWS,
                        "{kernel:?} {ty:?}"
                    );
                    if !served {
                        continue;
                    }
                    for (x, tx) in cols.iter().enumerate() {
                        let expect = rgb8_box_average(&rgb, stride, tx, ty, tx.total * ty.total);
                        assert_eq!(
                            dst[x * 4..x * 4 + 4],
                            [expect[0], expect[1], expect[2], 255],
                            "{kernel:?} trial={trial} col={tx:?} row={ty:?}"
                        );
                    }
                }
            }
        }
    }

    /// The CMYK fast path (convert source to RGB8 once, then box-average) must
    /// reproduce the generic per-tap `pixel()`→`cmyk_to_rgb`→average, byte for
    /// byte, over a fuzzed CMYK image and several minifying footprints.
    #[test]
    fn cmyk_fast_path_matches_generic_shade() {
        let mut rng = Rng(0x0fee_1dea_dbad_c0de);
        let cases = [
            (7u32, 5u32, 3u32, 3u32),
            (16, 16, 5, 7),
            (33, 9, 8, 4),
            (64, 48, 20, 15),
            (5, 5, 4, 2),
        ];
        for &(sw, sh, dev_w, dev_h) in &cases {
            for _trial in 0..8 {
                let samples: Vec<u8> = (0..(sw * sh * 4)).map(|_| rng.byte()).collect();
                let img = make_image_cs(sw, sh, dev_w, dev_h, ImageColorSpace::Cmyk, samples);
                let mut fast =
                    Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                let (painted, _taps) = paint_axis_aligned_cmyk_area_min_opaque(
                    &img,
                    &mut fast,
                    0,
                    0,
                    dev_w as usize,
                    dev_h as usize,
                )
                .expect("cmyk fast path applies to this small image");
                let mut reference =
                    Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                let mut ref_painted = 0u64;
                for y in 0..dev_h as usize {
                    let row = reference.row_mut(y);
                    for x in 0..dev_w as usize {
                        if let Some(c) = img.shade(x as f64 + 0.5, y as f64 + 0.5) {
                            let a = mul_div_255(mul_div_255(c[3] as u16, 255), 255);
                            if a == 0 {
                                continue;
                            }
                            let ia = 255 - a;
                            let px = &mut row[x * 4..x * 4 + 4];
                            px[0] =
                                (mul_div_255(c[0] as u16, a) + mul_div_255(px[0] as u16, ia)) as u8;
                            px[1] =
                                (mul_div_255(c[1] as u16, a) + mul_div_255(px[1] as u16, ia)) as u8;
                            px[2] =
                                (mul_div_255(c[2] as u16, a) + mul_div_255(px[2] as u16, ia)) as u8;
                            px[3] = (a + mul_div_255(px[3] as u16, ia)) as u8;
                            ref_painted += 1;
                        }
                    }
                }
                assert_eq!(
                    painted, ref_painted,
                    "cmyk painted count sw={sw} sh={sh} dev={dev_w}x{dev_h}"
                );
                for y in 0..dev_h as usize {
                    assert_eq!(
                        fast.row_mut(y).to_vec(),
                        reference.row_mut(y).to_vec(),
                        "cmyk row {y} differs sw={sw} sh={sh} dev={dev_w}x{dev_h}"
                    );
                }
            }
        }
    }

    /// The summed-area-table weighted ones count must agree exactly with the
    /// direct per-box weighted popcount (`binary_box_average`) — both are
    /// integer arithmetic over the same fractional tap weights, so equality
    /// is exact, over fuzzed bilevel images and minifying footprints.
    #[test]
    fn sat_weighted_ones_matches_direct_binary_average() {
        let mut rng = Rng(0xfeed_beef_dead_cafe);
        let cases = [(13u32, 7u32, 5u32, 3u32), (32, 32, 9, 11), (7, 19, 3, 6)];
        for &(sw, sh, dev_w, dev_h) in &cases {
            let row_bytes = (sw as usize).div_ceil(8);
            let samples: Vec<u8> = (0..row_bytes * sh as usize).map(|_| rng.byte()).collect();
            let mut img = make_image(sw, sh, dev_w, dev_h, samples);
            img.bpc = 1;
            img.color_space = ImageColorSpace::Gray;
            img.sample_lut =
                crate::render_cpu::image::build_sample_lut(1, &ImageColorSpace::Gray, None, false);
            assert!(img.is_binary_box_filterable());
            let (zero, one) = img.binary_box_lut().unwrap();

            let cols: Vec<Option<crate::render_cpu::image::AxisTaps>> = (0..dev_w)
                .map(|x| {
                    let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
                    let fx = u * img.width as f64 - 0.5;
                    img.box_taps_x(fx)
                })
                .collect();
            let rows: Vec<Option<crate::render_cpu::image::AxisTaps>> = (0..dev_h)
                .map(|y| {
                    let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
                    let fy = (1.0 - v) * img.height as f64 - 0.5;
                    img.box_taps_y(fy)
                })
                .collect();
            let sat = BilevelIntegral::build(&img, &cols, &rows).unwrap();

            for ty in rows.iter().flatten() {
                for tx in cols.iter().flatten() {
                    let weight = tx.total * ty.total;
                    let via_sat = crate::render_cpu::image::mix_bilevel(
                        zero,
                        one,
                        sat.weighted_ones(tx, ty),
                        weight,
                    );
                    let (direct, _) = img.binary_box_average(tx, ty).unwrap();
                    assert_eq!(via_sat, direct, "sw={sw} sh={sh} tx={tx:?} ty={ty:?}");
                }
            }
        }
    }

    /// Magnified / 1:1 bilinear fast path must match generic `shade()`
    /// byte-for-byte (continuous-tone JPEG/JPX magnification policy).
    #[test]
    fn bilinear_fast_path_matches_generic_shade() {
        let mut rng = Rng(0xc0ff_ee12_3456_789a);
        // All magnifying or 1:1: dest ≥ source on both axes.
        let cases = [
            (2u32, 1u32, 8u32, 8u32),
            (3, 3, 3, 3),
            (4, 4, 16, 16),
            (7, 5, 21, 15),
            (16, 12, 32, 24),
            (5, 9, 11, 19),
            (1, 1, 8, 8),
        ];
        for &(sw, sh, dev_w, dev_h) in &cases {
            for _trial in 0..8 {
                let samples: Vec<u8> = (0..(sw * sh * 3)).map(|_| rng.byte()).collect();
                let mut img = make_image(sw, sh, dev_w, dev_h, samples);
                img.interpolation = InterpolationMode::Bilinear;
                let mut fast =
                    Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                let (painted, taps) = paint_axis_aligned_rgb8_bilinear_opaque(
                    &img,
                    &mut fast,
                    0,
                    0,
                    dev_w as usize,
                    dev_h as usize,
                );
                assert_eq!(taps, painted * 4, "tap accounting");
                let mut reference =
                    Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                let mut ref_painted = 0u64;
                for y in 0..dev_h as usize {
                    let row = reference.row_mut(y);
                    for x in 0..dev_w as usize {
                        if let Some(c) = img.shade(x as f64 + 0.5, y as f64 + 0.5) {
                            let a = mul_div_255(mul_div_255(c[3] as u16, 255), 255);
                            if a == 0 {
                                continue;
                            }
                            // Opaque over transparent → direct write.
                            let px = &mut row[x * 4..x * 4 + 4];
                            px[0] = c[0];
                            px[1] = c[1];
                            px[2] = c[2];
                            px[3] = 255;
                            ref_painted += 1;
                        }
                    }
                }
                assert_eq!(
                    painted, ref_painted,
                    "bilinear painted count sw={sw} sh={sh} dev={dev_w}x{dev_h}"
                );
                for y in 0..dev_h as usize {
                    assert_eq!(
                        fast.row_mut(y).to_vec(),
                        reference.row_mut(y).to_vec(),
                        "bilinear row {y} differs sw={sw} sh={sh} dev={dev_w}x{dev_h}"
                    );
                }
            }
        }
    }

    /// Generic reference: `shade()` + opaque source-over onto a transparent
    /// surface (a direct write for an opaque sample). Returns the painted count.
    fn generic_reference(img: &PreparedImage, dev_w: u32, dev_h: u32) -> (Surface, u64) {
        let mut reference = Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
        let mut painted = 0u64;
        for y in 0..dev_h as usize {
            let row = reference.row_mut(y);
            for x in 0..dev_w as usize {
                if let Some(c) = img.shade(x as f64 + 0.5, y as f64 + 0.5) {
                    let a = mul_div_255(mul_div_255(c[3] as u16, 255), 255);
                    if a == 0 {
                        continue;
                    }
                    let ia = 255 - a;
                    let px = &mut row[x * 4..x * 4 + 4];
                    px[0] = (mul_div_255(c[0] as u16, a) + mul_div_255(px[0] as u16, ia)) as u8;
                    px[1] = (mul_div_255(c[1] as u16, a) + mul_div_255(px[1] as u16, ia)) as u8;
                    px[2] = (mul_div_255(c[2] as u16, a) + mul_div_255(px[2] as u16, ia)) as u8;
                    px[3] = (a + mul_div_255(px[3] as u16, ia)) as u8;
                    painted += 1;
                }
            }
        }
        (reference, painted)
    }

    fn assert_surfaces_equal(a: &mut Surface, b: &mut Surface, what: &str) {
        for y in 0..a.height {
            assert_eq!(
                a.row_mut(y).to_vec(),
                b.row_mut(y).to_vec(),
                "{what}: row {y} differs"
            );
        }
    }

    /// The kernels the image painters can run on this host.
    fn available_kernels() -> Vec<ImageKernel> {
        let mut kernels = vec![ImageKernel::Scalar];
        #[cfg(target_arch = "x86_64")]
        if is_x86_feature_detected!("avx2") {
            kernels.push(ImageKernel::Avx2);
        }
        kernels
    }

    /// A packed Indexed source: `bpc`-bit MSB-first samples, byte-aligned rows.
    fn packed_indexed_samples(sw: u32, sh: u32, bpc: u8, rng: &mut Rng) -> Vec<u8> {
        let row_bytes = (sw as usize * bpc as usize).div_ceil(8);
        (0..row_bytes * sh as usize).map(|_| rng.byte()).collect()
    }

    /// The Indexed fast path (resolve the palette once, expand to RGB8, then
    /// box-average) must reproduce the generic per-tap lookup + average, byte
    /// for byte: at 8 bpc the generic path resolves each tap through
    /// `pixel()`, at 2/4 bpc through the prepared `sample_lut`; with and
    /// without a `/Decode` remap; over Gray, RGB and CMYK palettes.
    #[test]
    fn indexed_fast_path_matches_generic_shade() {
        let mut rng = Rng(0x1d1d_1d1d_5eed_0001);
        let cases = [
            (7u32, 5u32, 3u32, 3u32),
            (16, 16, 5, 7),
            (33, 9, 8, 4),
            (64, 48, 20, 15),
            (5, 5, 4, 2),
        ];
        let bases: [ImageColorSpace; 3] = [
            ImageColorSpace::Gray,
            ImageColorSpace::Rgb,
            ImageColorSpace::Cmyk,
        ];
        for &bpc in &[2u8, 4, 8] {
            for base in &bases {
                for &(sw, sh, dev_w, dev_h) in &cases {
                    for &with_decode in &[false, true] {
                        // A palette shorter than `2^bpc` exercises the `hival` clamp.
                        let hival = ((1u32 << bpc) - 1).min(200 + (rng.byte() as u32 % 56));
                        let lookup: Vec<u8> = (0..(hival as usize + 1) * base.components())
                            .map(|_| rng.byte())
                            .collect();
                        let color_space = ImageColorSpace::Indexed {
                            base: Box::new(base.clone()),
                            hival,
                            lookup: Arc::from(lookup),
                        };
                        let samples = packed_indexed_samples(sw, sh, bpc, &mut rng);
                        let mut img =
                            make_image_cs(sw, sh, dev_w, dev_h, color_space.clone(), samples);
                        img.bpc = bpc;
                        img.decode = with_decode.then(|| {
                            // `/Decode [hi lo]`: inverts the index range, in index units.
                            Arc::from(vec![[hival as f32, 0.0f32]])
                        });
                        // What prepared.rs attaches: a LUT for 1/2/4 bpc, none at 8.
                        img.sample_lut = crate::render_cpu::image::build_sample_lut(
                            bpc,
                            &color_space,
                            img.decode.as_deref(),
                            false,
                        );
                        assert_eq!(img.sample_lut.is_some(), bpc <= 4);
                        let promoted = img
                            .indexed_promoted_to_rgb8()
                            .expect("indexed promotion applies to this small image");
                        let what = format!(
                            "indexed bpc={bpc} base={base:?} decode={with_decode} sw={sw} sh={sh} dev={dev_w}x{dev_h}"
                        );
                        // Unmasked: the promoted image takes the RGB8 area path.
                        let mut fast =
                            Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                        let (painted, _taps) = paint_axis_aligned_rgb8_area_min_opaque(
                            &promoted,
                            &mut fast,
                            0,
                            0,
                            dev_w as usize,
                            dev_h as usize,
                        );
                        let (mut reference, ref_painted) = generic_reference(&img, dev_w, dev_h);
                        assert_eq!(painted, ref_painted, "{what}: painted count");
                        assert_surfaces_equal(&mut fast, &mut reference, &what);
                        // Cut out by a bilevel soft mask: the promoted image
                        // takes the masked MRC path.
                        let mut masked = img.clone();
                        masked.smask = Some(bilevel(sw, sh, &mut rng));
                        let promoted_masked = masked.indexed_promoted_to_rgb8().unwrap();
                        let kind = area_min_mask(&promoted_masked).expect("bilevel mask");
                        let mut fast =
                            Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                        let (painted, _taps) = paint_axis_aligned_rgb8_area_min_masked(
                            &promoted_masked,
                            kind,
                            &mut fast,
                            0,
                            0,
                            dev_w as usize,
                            dev_h as usize,
                        );
                        let (mut reference, ref_painted) =
                            generic_masked_reference(&masked, dev_w, dev_h);
                        assert_eq!(painted, ref_painted, "{what} smask: painted count");
                        assert_surfaces_equal(&mut fast, &mut reference, &format!("{what} smask"));
                        // Under an 8-bit soft mask no fast path applies; the
                        // generic sampler itself must see the same image.
                        let mut soft8 = img.clone();
                        soft8.smask = Some(Arc::new(crate::page_ir::ImageSMask {
                            width: sw,
                            height: sh,
                            bits_per_component: 8,
                            decode: None,
                            samples: Arc::from(
                                (0..sw * sh).map(|_| rng.byte()).collect::<Vec<u8>>(),
                            ),
                            codec: None,
                            codec_data: None,
                            codec_parms: None,
                        }));
                        let promoted_soft8 = soft8.indexed_promoted_to_rgb8().unwrap();
                        let (mut a, pa) = generic_masked_reference(&promoted_soft8, dev_w, dev_h);
                        let (mut b, pb) = generic_masked_reference(&soft8, dev_w, dev_h);
                        assert_eq!(pa, pb, "{what} smask8: painted count");
                        assert_surfaces_equal(&mut a, &mut b, &format!("{what} smask8"));
                    }
                }
            }
        }
    }

    /// A per-pixel-transform image (non-sRGB ICC RGB, Lab, one- and
    /// two-colorant tint tables), with and without `/Decode`, resolved to
    /// RGB8 once must draw byte-identically to the generic per-tap
    /// transform: the promoted image through the generic sampler and through
    /// the RGB8 area-min fast path, each against the original image through
    /// the generic sampler.
    #[test]
    fn generic_promotion_matches_generic_shade() {
        let mut rng = Rng(0x1cc0_1cc0_5eed_0003);
        let cases = [
            (7u32, 5u32, 3u32, 3u32),
            (16, 16, 5, 7),
            (33, 9, 8, 4),
            (40, 30, 13, 11),
        ];
        for variant in 0..4 {
            for &(sw, sh, dev_w, dev_h) in &cases {
                for &with_decode in &[false, true] {
                    let (color_space, ncomp) = match variant {
                        0 => {
                            let trc: Vec<f32> =
                                (0..768).map(|_| rng.byte() as f32 / 255.0).collect();
                            let mut matrix = [0f32; 9];
                            for m in matrix.iter_mut() {
                                *m = rng.byte() as f32 / 255.0;
                            }
                            (
                                ImageColorSpace::IccRgb {
                                    trc: Arc::from(trc),
                                    matrix,
                                },
                                3,
                            )
                        }
                        1 => (
                            ImageColorSpace::Lab {
                                white_point: [0.9505, 1.0, 1.089],
                                range: [-100.0, 100.0, -100.0, 100.0],
                            },
                            3,
                        ),
                        2 => {
                            let rgb: Vec<u8> = (0..768).map(|_| rng.byte()).collect();
                            (
                                ImageColorSpace::TintLut {
                                    rgb: Arc::from(rgb),
                                },
                                1,
                            )
                        }
                        _ => {
                            let rgb: Vec<u8> = (0..256 * 256 * 3).map(|_| rng.byte()).collect();
                            (
                                ImageColorSpace::TintLut2 {
                                    rgb: Arc::from(rgb),
                                },
                                2,
                            )
                        }
                    };
                    let samples: Vec<u8> = (0..(sw * sh) as usize * ncomp)
                        .map(|_| rng.byte())
                        .collect();
                    let mut img = make_image_cs(sw, sh, dev_w, dev_h, color_space, samples);
                    img.decode = with_decode.then(|| {
                        Arc::from((0..ncomp).map(|_| [1.0f32, 0.0f32]).collect::<Vec<_>>())
                    });
                    assert!(img.generic_promotion_eligible());
                    let promoted = img.generic_promoted_to_rgb8().expect("eligible");
                    let what = format!(
                        "variant {variant} decode={with_decode} sw={sw} sh={sh} dev={dev_w}x{dev_h}"
                    );
                    let (mut reference, ref_painted) = generic_reference(&img, dev_w, dev_h);
                    let (mut via_promoted, promoted_painted) =
                        generic_reference(&promoted, dev_w, dev_h);
                    assert_eq!(promoted_painted, ref_painted, "{what}: painted (generic)");
                    assert_surfaces_equal(
                        &mut via_promoted,
                        &mut reference,
                        &format!("{what} (generic over promoted)"),
                    );
                    let mut fast =
                        Surface::new(dev_w as usize, dev_h as usize, Background::Transparent);
                    let (painted, _taps) = paint_axis_aligned_rgb8_area_min_opaque(
                        &promoted,
                        &mut fast,
                        0,
                        0,
                        dev_w as usize,
                        dev_h as usize,
                    );
                    assert_eq!(painted, ref_painted, "{what}: painted (fast)");
                    assert_surfaces_equal(
                        &mut fast,
                        &mut reference,
                        &format!("{what} (fast over promoted)"),
                    );
                }
            }
        }
    }

    /// An image placed at `(tx, ty)` device pixels, magnifying/1:1 by
    /// `dev_w / sw` on X and `dev_h / sh` on Y, inside a `surf_w x surf_h`
    /// surface. Off-diagonals exactly zero, as lowering computes them.
    fn make_image_placed(
        sw: u32,
        sh: u32,
        dev_w: u32,
        dev_h: u32,
        tx: f64,
        ty: f64,
        samples: Vec<u8>,
    ) -> PreparedImage {
        let mut img = make_image(sw, sh, dev_w, dev_h, samples);
        img.inv = Matrix {
            a: 1.0 / dev_w as f64,
            b: 0.0,
            c: 0.0,
            d: 1.0 / dev_h as f64,
            e: -tx / dev_w as f64,
            f: -ty / dev_h as f64,
        };
        img
    }

    /// Magnified / 1:1 bilinear draws — wide enough for the eight-lane
    /// kernels plus a ragged tail, placed on integer translations (the widened
    /// 1:1 blit), on fractional translations (two-tap lerps with tiny weights)
    /// and partly off the surface — must match generic `shade()` byte for
    /// byte on every kernel this host has, and every kernel must agree.
    #[test]
    fn bilinear_kernels_match_generic_shade_and_each_other() {
        let mut rng = Rng(0xb111_4ea8_0000_0042);
        // (sw, sh, dev_w, dev_h, tx, ty, surf_w, surf_h)
        let cases: [(u32, u32, u32, u32, f64, f64, u32, u32); 9] = [
            (64, 8, 64, 8, 0.0, 0.0, 64, 8),     // 1:1, exact blit
            (64, 8, 64, 8, 16.0, 4.0, 96, 16),   // 1:1, integer offset (exact)
            (37, 5, 37, 5, 3.0, 2.0, 48, 9),     // 1:1, non-power-of-two width
            (64, 8, 64, 8, 0.5, 0.25, 80, 12),   // 1:1, fractional offset
            (40, 7, 97, 13, 2.0, 1.0, 101, 15),  // non-integer magnification
            (33, 9, 66, 18, 0.0, 0.0, 66, 18),   // 2x
            (33, 9, 66, 18, -7.0, -3.0, 50, 12), // 2x, partly off the surface
            (9, 3, 9, 3, 0.0, 0.0, 9, 3),        // 1:1, narrower than one group
            (1, 1, 8, 8, 0.0, 0.0, 8, 8),        // degenerate source
        ];
        for &(sw, sh, dev_w, dev_h, tx, ty, surf_w, surf_h) in &cases {
            for _trial in 0..4 {
                let samples: Vec<u8> = (0..(sw * sh * 3)).map(|_| rng.byte()).collect();
                let mut img = make_image_placed(sw, sh, dev_w, dev_h, tx, ty, samples);
                img.interpolation = InterpolationMode::Bilinear;
                let what = format!("bilinear sw={sw} sh={sh} dev={dev_w}x{dev_h} at ({tx},{ty})");
                let (mut reference, ref_painted) = generic_reference(&img, surf_w, surf_h);
                for kernel in available_kernels() {
                    let Some(columns) = bilinear_columns(&img, 0, surf_w as usize) else {
                        panic!("{what}: no columns");
                    };
                    let Some(rows) = bilinear_rows(&img, 0, surf_h as usize) else {
                        panic!("{what}: no rows");
                    };
                    let mut fast =
                        Surface::new(surf_w as usize, surf_h as usize, Background::Transparent);
                    let painted = paint_bilinear_rows(kernel, &img, &mut fast, &columns, &rows);
                    assert_eq!(painted, ref_painted, "{what} {kernel:?}: painted count");
                    assert_surfaces_equal(&mut fast, &mut reference, &format!("{what} {kernel:?}"));
                }
            }
        }
    }

    /// The nearest fast path — widened runs at 1:1, texel-by-texel copies when
    /// magnified — must match generic `shade()` byte for byte.
    #[test]
    fn nearest_fast_path_matches_generic_shade() {
        let mut rng = Rng(0x4ea7_e570_0000_0007);
        let cases: [(u32, u32, u32, u32, f64, f64, u32, u32); 5] = [
            (64, 8, 64, 8, 0.0, 0.0, 64, 8),
            (37, 5, 37, 5, 3.0, 2.0, 48, 9),
            (64, 8, 64, 8, 0.5, 0.25, 80, 12),
            (33, 9, 66, 18, -7.0, -3.0, 50, 12),
            (40, 7, 97, 13, 2.0, 1.0, 101, 15),
        ];
        for &(sw, sh, dev_w, dev_h, tx, ty, surf_w, surf_h) in &cases {
            for _trial in 0..4 {
                let samples: Vec<u8> = (0..(sw * sh * 3)).map(|_| rng.byte()).collect();
                let img = make_image_placed(sw, sh, dev_w, dev_h, tx, ty, samples);
                let what = format!("nearest sw={sw} sh={sh} dev={dev_w}x{dev_h} at ({tx},{ty})");
                let (mut reference, ref_painted) = generic_reference(&img, surf_w, surf_h);
                let mut fast =
                    Surface::new(surf_w as usize, surf_h as usize, Background::Transparent);
                let (painted, _) = paint_axis_aligned_rgb8_nearest_opaque(
                    &img,
                    &mut fast,
                    0,
                    0,
                    surf_w as usize,
                    surf_h as usize,
                );
                assert_eq!(painted, ref_painted, "{what}: painted count");
                assert_surfaces_equal(&mut fast, &mut reference, &what);
            }
        }
    }

    /// The lookup-table nearest path — a packed 1-, 2- or 4-bit
    /// single-component source read through its prepared table — must match
    /// generic `shade()` byte for byte at 1:1, magnified, fractionally placed
    /// and partly off the surface, with and without an inverting `/Decode`.
    #[test]
    fn lut_nearest_fast_path_matches_generic_shade() {
        let mut rng = Rng(0x1b17_4ea7_0000_0011);
        let cases: [(u32, u32, u32, u32, f64, f64, u32, u32); 6] = [
            (64, 8, 64, 8, 0.0, 0.0, 64, 8),
            (37, 5, 37, 5, 3.0, 2.0, 48, 9),
            (64, 8, 64, 8, 0.5, 0.25, 80, 12),
            (33, 9, 66, 18, -7.0, -3.0, 50, 12),
            (40, 7, 97, 13, 2.0, 1.0, 101, 15),
            (21, 4, 63, 12, 0.0, 0.0, 63, 12),
        ];
        let inverting = [[1.0f32, 0.0]];
        for &(sw, sh, dev_w, dev_h, tx, ty, surf_w, surf_h) in &cases {
            for bpc in [1u8, 2, 4] {
                for invert in [false, true] {
                    let row_bytes = (sw as usize * bpc as usize).div_ceil(8);
                    let samples: Vec<u8> =
                        (0..row_bytes * sh as usize).map(|_| rng.byte()).collect();
                    let mut img = make_image_placed(sw, sh, dev_w, dev_h, tx, ty, samples);
                    img.bpc = bpc;
                    img.color_space = ImageColorSpace::Gray;
                    img.sample_lut = crate::render_cpu::image::build_sample_lut(
                        bpc,
                        &ImageColorSpace::Gray,
                        invert.then_some(&inverting[..]),
                        false,
                    );
                    let what = format!(
                        "lut nearest bpc={bpc} invert={invert} sw={sw} sh={sh} dev={dev_w}x{dev_h} at ({tx},{ty})"
                    );
                    let lut = img.lut_nearest_opaque().expect("complete opaque table");
                    let (mut reference, ref_painted) = generic_reference(&img, surf_w, surf_h);
                    let mut fast =
                        Surface::new(surf_w as usize, surf_h as usize, Background::Transparent);
                    let (painted, _) = paint_axis_aligned_lut_nearest_opaque(
                        &img,
                        lut,
                        &mut fast,
                        0,
                        0,
                        surf_w as usize,
                        surf_h as usize,
                    );
                    assert_eq!(painted, ref_painted, "{what}: painted count");
                    assert_surfaces_equal(&mut fast, &mut reference, &what);
                }
            }
        }
    }

    /// The vector widen must equal the scalar one over every run length and
    /// offset, including runs ending at the very end of the buffer where the
    /// vector loads cannot run and the scalar tail takes over.
    #[test]
    fn widen_kernels_match_scalar_bit_exact() {
        let mut rng = Rng(0x71de_0000_0000_0001);
        let src: Vec<u8> = (0..4096).map(|_| rng.byte()).collect();
        for kernel in available_kernels() {
            for &n in &[0usize, 1, 3, 7, 8, 9, 15, 16, 17, 31, 64, 100] {
                for &off in &[
                    0usize,
                    1,
                    5,
                    4096 - n * 3 - 40,
                    4096 - n * 3 - 1,
                    4096 - n * 3,
                ] {
                    if off + n * 3 > src.len() {
                        continue;
                    }
                    let mut expected = vec![0xAAu8; n * 4];
                    widen_rgb8_to_rgba8_scalar(&src[off..off + n * 3], &mut expected);
                    let mut got = vec![0xAAu8; n * 4];
                    widen_rgb8_to_rgba8_opaque(kernel, &src, off, &mut got);
                    assert_eq!(got, expected, "{kernel:?} n={n} off={off}");
                }
            }
        }
    }

    /// Known truncation sample from the integration bilinear fixture:
    /// 2×1 red/blue magnified to 8×8, dest x=2 → [223, 0, 31, 255].
    #[test]
    fn bilinear_fast_path_truncates_like_reference_stretchers() {
        let mut img = make_image(2, 1, 8, 8, vec![255, 0, 0, 0, 0, 255]);
        img.interpolation = InterpolationMode::Bilinear;
        let mut surface = Surface::new(8, 8, Background::Transparent);
        let _ = paint_axis_aligned_rgb8_bilinear_opaque(&img, &mut surface, 0, 0, 8, 8);
        let row = surface.row_mut(4);
        let px = &row[2 * 4..2 * 4 + 4];
        assert_eq!(px, [223, 0, 31, 255]);
    }

    /// The shortcut in `composite_layer_px` must be what the general path
    /// computes: an opaque source at full opacity under Normal yields the
    /// source byte for every channel value, backdrop value and backdrop alpha
    /// (the general path's result depends on nothing else).
    #[test]
    fn opaque_normal_layer_composite_is_a_copy() {
        for s in 0..=255u8 {
            for da in 0..=255u8 {
                for d in 0..=255u8 {
                    let src = [s, s, s, 255];
                    let mut dst = [d, d, d, da];
                    composite_layer_px_general(&mut dst, &src, 255, BlendChoice::Normal);
                    assert_eq!(dst, src, "source {s}, backdrop {d}, backdrop alpha {da}");
                }
            }
        }
    }

    #[test]
    fn rect_contains_is_inclusive_and_treats_empty_as_contained() {
        let r = |x, y, width, height| DeviceRect {
            x,
            y,
            width,
            height,
        };
        let outer = r(2, 3, 10, 5);
        assert!(rect_contains(outer, outer));
        assert!(rect_contains(outer, r(5, 4, 7, 4)));
        assert!(
            !rect_contains(outer, r(5, 4, 8, 4)),
            "one column past the right edge"
        );
        assert!(!rect_contains(outer, r(1, 4, 2, 2)), "left of it");
        assert!(!rect_contains(outer, r(3, 2, 2, 2)), "above it");
        assert!(rect_contains(outer, r(100, 100, 0, 3)), "empty");
    }

    /// A one-bit `/ImageMask` stencil of `sw x sh` random texels, painted in
    /// a fixed colour, re-placed at device `(ox, oy)` with size `w x h`.
    /// `inverted` gives it `/Decode [1 0]` (a set bit paints).
    #[allow(clippy::too_many_arguments)]
    fn stencil_image(
        sw: u32,
        sh: u32,
        ox: f64,
        oy: f64,
        w: f64,
        h: f64,
        inverted: bool,
        rng: &mut Rng,
    ) -> PreparedImage {
        let row_bytes = (sw as usize).div_ceil(8);
        let samples: Vec<u8> = (0..row_bytes * sh as usize).map(|_| rng.byte()).collect();
        let mut img = place(make_image(sw, sh, 1, 1, samples), ox, oy, w, h);
        img.is_stencil = true;
        img.bpc = 1;
        img.color_space = ImageColorSpace::Gray;
        img.stencil_rgb = [200, 40, 90];
        img.decode = inverted.then(|| Arc::from([[1.0f32, 0.0]]));
        img
    }

    /// A clip mask over most of a `side x side` surface with random coverage:
    /// zero, full and partial bytes.
    fn random_clip(side: u32, rng: &mut Rng) -> ClipMask {
        let bounds = DeviceRect {
            x: 1,
            y: 0,
            width: side - 2,
            height: side - 1,
        };
        let data = (0..bounds.width * bounds.height)
            .map(|_| match rng.byte() % 4 {
                0 => 0,
                1 => 255,
                _ => rng.byte(),
            })
            .collect();
        ClipMask {
            bounds,
            data,
            outside: 0,
            all_opaque: false,
        }
    }

    /// A `side x side` surface with an arbitrary backdrop, so compositing at
    /// partial alpha is exercised.
    fn backdrop(side: u32, seed: u64) -> Surface {
        let mut rng = Rng(seed);
        let mut surface = Surface::new(side as usize, side as usize, Background::Transparent);
        for y in 0..side as usize {
            for b in surface.row_mut(y) {
                *b = rng.byte();
            }
        }
        surface
    }

    /// The `/ImageMask` stencil fast path (bilevel box filter when minified,
    /// transparent-skip nearest otherwise, on the interior; generic body on
    /// the border band) must equal the generic per-pixel body byte for byte:
    /// both `/Decode` polarities, with and without a clip mask, opaque and
    /// partial fill alpha, over a backdrop, at fractional placements.
    #[test]
    fn stencil_fast_path_matches_the_generic_body() {
        let mut rng = Rng(0x5a7e_c11a_0dd5_beef);
        // (source w, h, device x, y, w, h): minified, near 1:1 and magnified.
        let placements: [(u32, u32, f64, f64, f64, f64); 7] = [
            (37, 23, 1.3, 2.6, 9.4, 6.2),
            (64, 48, 2.5, 1.125, 20.3, 14.7),
            (9, 33, 3.7, 0.2, 4.6, 11.9),
            (200, 150, 0.4, 0.7, 30.2, 22.9),
            (16, 16, 0.25, 0.75, 15.5, 15.5),
            (5, 7, 0.6, 1.4, 17.8, 21.3),
            (13, 11, 2.0, 3.0, 26.0, 22.0),
        ];
        let mut minified = 0;
        let mut nearest = 0;
        for &(sw, sh, ox, oy, w, h) in &placements {
            let side = (ox + w).max(oy + h).ceil() as u32 + 2;
            for inverted in [false, true] {
                for clipped in [false, true] {
                    for alpha in [255u8, 170] {
                        let mut img = stencil_image(sw, sh, ox, oy, w, h, inverted, &mut rng);
                        img.alpha = alpha;
                        let clip = clipped.then(|| random_clip(side, &mut rng));
                        let lut = stencil_fast_lut(&img).expect("an axis-aligned stencil");
                        assert!(
                            interior_span(img.inv.a, img.inv.e, 0, side as usize).is_some()
                                && interior_span(img.inv.d, img.inv.f, 0, side as usize).is_some(),
                            "the placement must have an interior for the fast path"
                        );
                        let b = img.bounds;
                        let (x0, y0) = (b.x as usize, b.y as usize);
                        let (x1, y1) = (x0 + b.width as usize, y0 + b.height as usize);
                        let seed = rng.next();
                        let mut got = backdrop(side, seed);
                        let fast = paint_axis_aligned_stencil(
                            &img,
                            lut,
                            &mut got,
                            clip.as_ref(),
                            BlendChoice::Normal,
                            x0,
                            y0,
                            x1,
                            y1,
                        );
                        let mut want = backdrop(side, seed);
                        let generic = paint_image_generic(
                            &img,
                            &mut want,
                            clip.as_ref(),
                            None,
                            BlendChoice::Normal,
                            x0,
                            y0,
                            x1,
                            y1,
                            None,
                        );
                        let what = format!(
                            "stencil {sw}x{sh} at ({ox}, {oy}) size {w}x{h} inverted {inverted} \
                             clipped {clipped} alpha {alpha}"
                        );
                        assert_surfaces_equal(&mut got, &mut want, &what);
                        assert_eq!(fast.0, generic.0, "{what}: covered pixels");
                        if img.footprint[0] > 1.0 || img.footprint[1] > 1.0 {
                            minified += 1;
                        } else {
                            nearest += 1;
                        }
                    }
                }
            }
        }
        assert!(
            minified > 0 && nearest > 0,
            "{minified} minified, {nearest} nearest"
        );
    }

    /// What keeps a stencil on the generic body: a rotated or sheared
    /// placement, a magnified Bilinear draw, and sample data shorter than its
    /// packed rows (the fast paths index rows directly; `pixel()` reads the
    /// missing bytes as zero, which paints). Each still renders, through the
    /// dispatcher, exactly as the generic body does.
    #[test]
    fn stencil_fast_path_eligibility_and_generic_fallbacks() {
        let mut rng = Rng(0x0bad_5eed_1234_4321);
        let side = 24u32;

        // Eligible: minified, magnified Nearest, minified Bilinear, inverted.
        let img = stencil_image(40, 30, 1.5, 2.25, 17.3, 12.8, false, &mut rng);
        assert!(stencil_fast_lut(&img).is_some());
        let mut img = stencil_image(5, 4, 1.5, 2.25, 17.3, 12.8, true, &mut rng);
        assert!(stencil_fast_lut(&img).is_some());
        img.interpolation = InterpolationMode::Bilinear;
        assert!(
            stencil_fast_lut(&img).is_none(),
            "magnified Bilinear stays generic"
        );
        let mut img = stencil_image(40, 30, 1.5, 2.25, 17.3, 12.8, false, &mut rng);
        img.interpolation = InterpolationMode::Bilinear;
        assert!(
            stencil_fast_lut(&img).is_some(),
            "minification ignores the hint"
        );

        // Polarity: the painting entry is opaque, the masking one clear.
        let plain = stencil_image(8, 8, 0.0, 0.0, 4.0, 4.0, false, &mut rng);
        let (zero, one) = plain.stencil_bilevel_lut().unwrap();
        assert_eq!((zero, one), ([200, 40, 90, 255], [200, 40, 90, 0]));
        let inverted = stencil_image(8, 8, 0.0, 0.0, 4.0, 4.0, true, &mut rng);
        let (zero, one) = inverted.stencil_bilevel_lut().unwrap();
        assert_eq!((zero, one), ([200, 40, 90, 0], [200, 40, 90, 255]));

        let mut cases: Vec<(&str, PreparedImage)> = Vec::new();
        // Rotated a few degrees about the draw's centre.
        let mut rotated = stencil_image(40, 30, 3.0, 3.0, 17.0, 13.0, false, &mut rng);
        let (s, c) = (0.1f64.sin(), 0.1f64.cos());
        let (cx, cy) = (11.5, 9.5);
        // Device -> unit square: rotate back about the centre, then scale.
        rotated.inv = Matrix {
            a: c / 17.0,
            b: -s / 13.0,
            c: s / 17.0,
            d: c / 13.0,
            e: (-c * cx - s * cy) / 17.0 + 0.5,
            f: (s * cx - c * cy) / 13.0 + 0.5,
        };
        rotated.bounds = DeviceRect {
            x: 0,
            y: 0,
            width: side,
            height: side,
        };
        assert!(
            stencil_fast_lut(&rotated).is_none(),
            "rotated stays generic"
        );
        cases.push(("rotated", rotated));
        // Truncated: the last two packed rows are missing.
        let mut short = stencil_image(40, 30, 1.5, 2.25, 17.3, 12.8, false, &mut rng);
        let full = short.samples.len();
        short.samples = Arc::from(&short.samples[..full - 2 * 5]);
        assert!(
            stencil_fast_lut(&short).is_none(),
            "a short buffer stays generic"
        );
        cases.push(("short", short));
        let mut short_magnified = stencil_image(6, 5, 1.5, 2.25, 17.3, 12.8, true, &mut rng);
        short_magnified.samples = Arc::from(&short_magnified.samples[..3]);
        assert!(stencil_fast_lut(&short_magnified).is_none());
        cases.push(("short magnified", short_magnified));

        for (what, img) in &cases {
            let mut got = dispatched(img, side);
            let (mut want, _) = generic_masked_reference(img, side, side);
            assert_surfaces_equal(&mut got, &mut want, what);
        }
    }

    /// A one-bit gray image of `sw x sh` packed bits from `bits`, placed at
    /// device `(ox, oy)` with size `w x h` (a negative size mirrors that axis).
    #[allow(clippy::too_many_arguments)]
    fn bilevel_image(
        sw: u32,
        sh: u32,
        bits: Vec<u8>,
        ox: f64,
        oy: f64,
        w: f64,
        h: f64,
    ) -> PreparedImage {
        let mut img = make_image(sw, sh, 1, 1, bits);
        img.bpc = 1;
        img.color_space = ImageColorSpace::Gray;
        img.sample_lut =
            crate::render_cpu::image::build_sample_lut(1, &ImageColorSpace::Gray, None, false);
        // Device -> unit square, either orientation.
        img.inv = Matrix {
            a: 1.0 / w,
            b: 0.0,
            c: 0.0,
            d: 1.0 / h,
            e: -ox / w,
            f: -oy / h,
        };
        let (lx, hx) = (ox.min(ox + w), ox.max(ox + w));
        let (ly, hy) = (oy.min(oy + h), oy.max(oy + h));
        img.bounds = DeviceRect {
            x: lx.floor() as i32,
            y: ly.floor() as i32,
            width: (hx.ceil() - lx.floor()) as u32,
            height: (hy.ceil() - ly.floor()) as u32,
        };
        img.footprint = [sw as f64 / w.abs(), sh as f64 / h.abs()];
        img
    }

    /// The per-column and per-row taps `paint_axis_aligned_binary_box` builds.
    fn binary_taps(
        img: &PreparedImage,
    ) -> (
        Vec<Option<crate::render_cpu::image::AxisTaps>>,
        Vec<Option<crate::render_cpu::image::AxisTaps>>,
    ) {
        let b = img.bounds;
        let cols = (b.x as usize..b.x as usize + b.width as usize)
            .map(|x| {
                let u = img.inv.a * (x as f64 + 0.5) + img.inv.e;
                (0.0..1.0)
                    .contains(&u)
                    .then(|| img.box_taps_x(u * img.width as f64 - 0.5))
                    .flatten()
            })
            .collect();
        let rows = (b.y as usize..b.y as usize + b.height as usize)
            .map(|y| {
                let v = img.inv.d * (y as f64 + 0.5) + img.inv.f;
                (0.0..1.0)
                    .contains(&v)
                    .then(|| img.box_taps_y((1.0 - v) * img.height as f64 - 0.5))
                    .flatten()
            })
            .collect();
        (cols, rows)
    }

    /// The row-band weighted ones count must equal the summed-area table's
    /// and the direct per-row weighted popcount, for every destination box of
    /// random bilevel images at random fractional (and mirrored) minifying
    /// placements, including widths that are not a whole number of bytes
    /// and windows that start mid-byte.
    #[test]
    fn row_band_weighted_ones_match_the_sat_and_the_direct_count() {
        let mut rng = Rng(0x2b0b_a11d_0e5e_1f00);
        let mut boxes = 0u64;
        for trial in 0..60 {
            let sw = 3 + (rng.next() % 140) as u32;
            let sh = 3 + (rng.next() % 120) as u32;
            let row_bytes = (sw as usize).div_ceil(8);
            // Mostly sparse, sometimes dense, so the zero-row shortcut and
            // full bytes are both exercised.
            let dense = trial % 3 == 0;
            let bits: Vec<u8> = (0..row_bytes * sh as usize)
                .map(|_| {
                    let b = rng.byte();
                    if dense || b < 40 { rng.byte() } else { 0 }
                })
                .collect();
            let scale = 1.05 + (rng.next() % 1000) as f64 / 150.0;
            let (w, h) = (sw as f64 / scale, sh as f64 / (scale * 0.8 + 0.3));
            let (w, h) = if trial % 4 == 1 { (-w, h) } else { (w, h) };
            let (w, h) = if trial % 5 == 2 { (w, -h) } else { (w, h) };
            let ox = 1.0 + (rng.next() % 100) as f64 / 37.0 + if w < 0.0 { -w } else { 0.0 };
            let oy = 0.5 + (rng.next() % 100) as f64 / 41.0 + if h < 0.0 { -h } else { 0.0 };
            let img = bilevel_image(sw, sh, bits, ox, oy, w, h);
            let (cols, rows) = binary_taps(&img);
            if cols.iter().all(Option::is_none) || rows.iter().all(Option::is_none) {
                // No destination pixel centre lands in the image.
                assert!(BilevelWindow::new(&img, &cols, &rows).is_none());
                assert!(BilevelIntegral::build(&img, &cols, &rows).is_none());
                continue;
            }
            let window = BilevelWindow::new(&img, &cols, &rows).expect("complete samples");
            let sat = BilevelIntegral::build(&img, &cols, &rows).expect("small table");
            let base = (window.byte_lo * 8) as u32;
            let mut colw = vec![0u32; window.nbytes * 8];
            let mut prefix = vec![0u64; window.nbytes * 8 + 1];
            let row_bits = img.packed_row_bits();
            for ty in rows.iter().flatten() {
                let any = window.column_sums(ty, &mut colw, &mut prefix);
                for tx in cols.iter().flatten() {
                    let banded = if any {
                        row_band_weighted_ones(tx, base, &colw, &prefix)
                    } else {
                        0
                    };
                    let direct: u64 = (ty.lo..=ty.hi)
                        .map(|y| {
                            ty.weight_at(y)
                                * crate::render_cpu::image::weighted_row_ones_in(
                                    &img.samples,
                                    y as usize * row_bits,
                                    tx,
                                )
                        })
                        .sum();
                    assert_eq!(banded, direct, "trial {trial} tx={tx:?} ty={ty:?}");
                    assert_eq!(sat.weighted_ones(tx, ty), direct, "trial {trial}");
                    boxes += 1;
                }
            }
        }
        assert!(boxes > 10_000, "{boxes} boxes");
    }

    /// The row-band painter must leave the same bytes as the per-pixel loop
    /// it replaced the summed-area table in front of: gray and stencil
    /// tables, with and without a clip mask, opaque and partial alpha, over a
    /// backdrop.
    #[test]
    fn row_band_paint_matches_the_per_pixel_loop() {
        let mut rng = Rng(0x0dd_ba11_c0de_5eed);
        for trial in 0..24 {
            let (sw, sh) = (40 + (rng.next() % 90) as u32, 30 + (rng.next() % 90) as u32);
            let row_bytes = (sw as usize).div_ceil(8);
            let bits: Vec<u8> = (0..row_bytes * sh as usize).map(|_| rng.byte()).collect();
            let scale = 1.2 + (rng.next() % 100) as f64 / 25.0;
            let (w, h) = (sw as f64 / scale, sh as f64 / scale);
            let (ox, oy) = (
                1.3 + (trial % 3) as f64 * 0.27,
                0.6 + (trial % 4) as f64 * 0.21,
            );
            let mut img = bilevel_image(sw, sh, bits, ox, oy, w, h);
            img.alpha = if trial % 2 == 0 { 255 } else { 140 };
            let lut = if trial % 3 == 2 {
                img.is_stencil = true;
                img.sample_lut = None;
                img.stencil_rgb = [10, 120, 230];
                img.stencil_bilevel_lut().unwrap()
            } else {
                img.binary_box_lut().unwrap()
            };
            let side = (ox + w).max(oy + h).ceil() as u32 + 2;
            let clip = (trial % 4 >= 2).then(|| random_clip(side, &mut rng));
            let (cols, rows) = binary_taps(&img);
            let (x0, y0) = (img.bounds.x as usize, img.bounds.y as usize);
            let (x1, y1) = (
                x0 + img.bounds.width as usize,
                y0 + img.bounds.height as usize,
            );
            let seed = rng.next();
            let mut got = backdrop(side, seed);
            let banded =
                paint_axis_aligned_binary_box(&img, lut, &mut got, clip.as_ref(), x0, y0, x1, y1);
            let mut want = backdrop(side, seed);
            let serial =
                paint_binary_box_serial(&img, lut, &mut want, clip.as_ref(), &cols, &rows, x0, y0);
            let what = format!("trial {trial}: {sw}x{sh} at ({ox}, {oy}) size {w}x{h}");
            assert_surfaces_equal(&mut got, &mut want, &what);
            assert_eq!(banded.0, serial.0, "{what}: painted");
        }
    }

    /// A 600-dpi Letter page (5100 x 6600 = 33.7M bits) is over the summed-area
    /// table's 32M-entry cap, so before the row-band filter it fell to the
    /// serial per-pixel loop. The row-band filter takes it and paints the same
    /// bytes. A truncated buffer still takes the per-pixel loop (which reads
    /// the missing bytes as zero) instead of indexing past the end.
    #[test]
    fn row_band_paints_a_600_dpi_page_and_declines_a_truncated_one() {
        let mut rng = Rng(0x600d_0600_d0d0_6006);
        let (sw, sh) = (5100u32, 6600u32);
        let row_bytes = (sw as usize).div_ceil(8);
        let bits: Vec<u8> = (0..row_bytes * sh as usize)
            .map(|i| {
                if (i / row_bytes) % 40 < 25 {
                    rng.byte() & rng.byte()
                } else {
                    0
                }
            })
            .collect();
        // 72 dpi: 612 x 792 device pixels at a fractional offset.
        let img = bilevel_image(sw, sh, bits, 0.4, 0.3, 612.0, 792.0);
        let (cols, rows) = binary_taps(&img);
        assert!(
            BilevelIntegral::build(&img, &cols, &rows).is_none(),
            "over the old table cap"
        );
        assert!(BilevelWindow::new(&img, &cols, &rows).is_some());
        let lut = img.binary_box_lut().unwrap();
        let side = 794u32;
        let mut got = backdrop(side, 7);
        paint_axis_aligned_binary_box(&img, lut, &mut got, None, 0, 0, 613, 793);
        let mut want = backdrop(side, 7);
        paint_binary_box_serial(&img, lut, &mut want, None, &cols, &rows, 0, 0);
        assert_surfaces_equal(&mut got, &mut want, "600 dpi");

        // Truncated: drop the last 100 rows' bytes.
        let mut short = bilevel_image(400, 300, vec![0x5a; 50 * 300], 0.5, 0.5, 61.0, 47.0);
        short.samples = Arc::from(&short.samples[..50 * 200]);
        let (cols, rows) = binary_taps(&short);
        assert!(BilevelWindow::new(&short, &cols, &rows).is_none());
        let lut = short.binary_box_lut().unwrap();
        let mut got = backdrop(64, 9);
        paint_axis_aligned_binary_box(&short, lut, &mut got, None, 0, 0, 62, 48);
        let mut want = backdrop(64, 9);
        paint_binary_box_serial(&short, lut, &mut want, None, &cols, &rows, 0, 0);
        assert_surfaces_equal(&mut got, &mut want, "truncated");
    }

    /// `img` re-placed at device `(ox, oy)` with device size `w x h`, all
    /// fractional, so the draw has a partially covered border ring.
    fn place(mut img: PreparedImage, ox: f64, oy: f64, w: f64, h: f64) -> PreparedImage {
        img.inv = Matrix {
            a: 1.0 / w,
            b: 0.0,
            c: 0.0,
            d: 1.0 / h,
            e: -ox / w,
            f: -oy / h,
        };
        let (x0, y0) = (ox.floor() as i32, oy.floor() as i32);
        img.bounds = DeviceRect {
            x: x0,
            y: y0,
            width: ((ox + w).ceil() as i32 - x0) as u32,
            height: ((oy + h).ceil() as i32 - y0) as u32,
        };
        img.footprint = [img.width as f64 / w, img.height as f64 / h];
        img
    }

    /// Run `img` through the real image dispatcher (`execute` → `paint_image`,
    /// with whatever promotion and fast path it picks) onto a transparent
    /// `side x side` surface.
    fn dispatched(img: &PreparedImage, side: u32) -> Surface {
        let page = crate::render_cpu::prepared::CpuPreparedPage {
            size: crate::page_ir::DeviceSize {
                width: side,
                height: side,
            },
            ops: vec![PreparedOp::Image(Box::new(img.clone()))],
            clips: Vec::new(),
            points: Vec::new(),
            subpaths: Vec::new(),
            codecs: crate::image::CodecRegistry::default(),
            decode_limits: crate::image::DecodeLimits::default(),
            hinting: crate::font::HintingPolicy::None,
            color_policy: crate::render_api::RenderColorPolicy::Original,
            diagnostics: Default::default(),
            image_cache: None,
            decode_floor: None,
            sanity_extent: 64.0,
            #[cfg(feature = "profiling")]
            profile: Default::default(),
            #[cfg(feature = "profiling")]
            decode_cache: None,
            #[cfg(feature = "profiling")]
            lower_prof: Default::default(),
        };
        let mut surface = Surface::new(side as usize, side as usize, Background::Transparent);
        let mut ctx = CpuWorkerContext::default();
        let mut stats = RenderStats::default();
        execute(&page, &mut surface, &mut ctx, &mut stats);
        surface
    }

    /// Every image fast path must equal the full generic body — interior
    /// *and* the border ring — when the image lands on fractional device
    /// coordinates. The other equivalence tests here place images on whole
    /// pixels, where the ring does not exist, or compare against a
    /// `shade()`-only reference that has no edge coverage, so a fast path
    /// that got the ring wrong passed them.
    ///
    /// Covers RGB8, Gray8 (promoted), Indexed (expanded) and CMYK sources,
    /// unmasked and under a stencil, a one-bit and an eight-bit soft mask;
    /// minified, near 1:1 and magnified; nearest and bilinear. Also covers
    /// `/ImageMask` stencils in both `/Decode` polarities and one-bit gray
    /// images.
    ///
    /// Every path matches byte for byte on the whole surface, masked or not.
    /// The ring is the pixel-centre rule for an axis-aligned image: a border
    /// pixel is painted at full weight when its centre lies inside the
    /// destination rectangle and not at all otherwise. The opaque
    /// unmasked fast paths paint it that way themselves; the masked ones
    /// leave it to the generic body, whose `edge_coverage` gives axis-aligned
    /// draws exactly that rule
    /// (`axis_aligned_masked_edges_follow_the_pixel_centre_rule` checks the
    /// generic body against it directly). Until 2026-11-08 the generic body
    /// painted A10 fractional coverage there, so masked draws had a soft ring
    /// and unmasked ones a hard one; see `image-edge-ring-pdfium-probe-20261108.md`
    /// and `masked-image-ring-20261108.md` in the scoping notes.
    #[test]
    fn fractional_placements_match_the_generic_body_including_the_border_ring() {
        let mut rng = Rng(0xb0d5_7a11_0f0f_1234);
        // (source w, h, device x, y, w, h)
        let placements: [(u32, u32, f64, f64, f64, f64); 5] = [
            (37, 23, 1.3, 2.6, 9.4, 6.2),
            (16, 16, 0.25, 0.75, 15.5, 15.5),
            (64, 48, 2.5, 1.125, 20.3, 14.7),
            (5, 7, 0.6, 1.4, 17.8, 21.3),
            (9, 33, 3.7, 0.2, 4.6, 11.9),
        ];
        let spaces: [(&str, ImageColorSpace, usize); 4] = [
            ("rgb", ImageColorSpace::Rgb, 3),
            ("gray", ImageColorSpace::Gray, 1),
            ("cmyk", ImageColorSpace::Cmyk, 4),
            (
                "indexed",
                ImageColorSpace::Indexed {
                    base: Box::new(ImageColorSpace::Rgb),
                    hival: 255,
                    lookup: Arc::from(
                        (0..256 * 3)
                            .map(|i| (i * 73 % 256) as u8)
                            .collect::<Vec<_>>(),
                    ),
                },
                1,
            ),
        ];
        let mut checked = 0;
        for &(sw, sh, ox, oy, w, h) in &placements {
            let side = (ox + w).max(oy + h).ceil() as u32 + 2;
            for (space_name, space, comps) in &spaces {
                for mask_kind in ["none", "stencil", "smask1", "smask8"] {
                    for interpolation in [InterpolationMode::Nearest, InterpolationMode::Bilinear] {
                        let samples: Vec<u8> = (0..sw as usize * sh as usize * comps)
                            .map(|_| rng.byte())
                            .collect();
                        let mut img = place(
                            make_image_cs(sw, sh, 1, 1, space.clone(), samples),
                            ox,
                            oy,
                            w,
                            h,
                        );
                        img.interpolation = interpolation;
                        let (mw, mh) = (sw.div_ceil(2) + 1, sh + 3);
                        match mask_kind {
                            "stencil" => {
                                img.mask = Some(crate::page_ir::ImageMask::Stencil(bilevel(
                                    mw, mh, &mut rng,
                                )));
                            }
                            "smask1" => img.smask = Some(bilevel(mw, mh, &mut rng)),
                            "smask8" => {
                                let mask: Vec<u8> = (0..mw * mh)
                                    .map(|_| if rng.byte() < 60 { rng.byte() } else { 255 })
                                    .collect();
                                img.smask = Some(Arc::new(crate::page_ir::ImageSMask {
                                    width: mw,
                                    height: mh,
                                    bits_per_component: 8,
                                    decode: None,
                                    samples: Arc::from(mask),
                                    codec: None,
                                    codec_data: None,
                                    codec_parms: None,
                                }));
                            }
                            _ => {}
                        }
                        let mut got = dispatched(&img, side);
                        // `paint_image` turns a minified hard stencil into a
                        // coverage soft mask before choosing any path.
                        let generic_img = img
                            .minified_stencil_as_coverage()
                            .unwrap_or_else(|| img.clone());
                        let (mut want, _) = generic_masked_reference(&generic_img, side, side);
                        let what = format!(
                            "{space_name} {mask_kind} {interpolation:?} src {sw}x{sh} at \
                             ({ox}, {oy}) size {w}x{h}"
                        );
                        assert_surfaces_equal(&mut got, &mut want, &what);
                        checked += 1;
                    }
                }
            }
        }
        assert_eq!(checked, 5 * 4 * 4 * 2);

        // `/ImageMask` stencils: the fast path paints only the interior and
        // leaves the ring to the generic body.
        for &(sw, sh, ox, oy, w, h) in &placements {
            let side = (ox + w).max(oy + h).ceil() as u32 + 2;
            for inverted in [false, true] {
                for interpolation in [InterpolationMode::Nearest, InterpolationMode::Bilinear] {
                    let mut img = stencil_image(sw, sh, ox, oy, w, h, inverted, &mut rng);
                    img.interpolation = interpolation;
                    let mut got = dispatched(&img, side);
                    let (mut want, _) = generic_masked_reference(&img, side, side);
                    let what = format!(
                        "imagemask inverted {inverted} {interpolation:?} src {sw}x{sh} at                          ({ox}, {oy}) size {w}x{h}"
                    );
                    assert_surfaces_equal(&mut got, &mut want, &what);
                    checked += 1;
                }
            }
        }
        assert_eq!(checked, 5 * 4 * 4 * 2 + 5 * 2 * 2);

        // One-bit gray images: the low-bit LUT nearest path when magnified,
        // the bilevel box filter when minified; both paint the ring by pixel
        // centre themselves.
        for &(sw, sh, ox, oy, w, h) in &placements {
            let side = (ox + w).max(oy + h).ceil() as u32 + 2;
            for interpolation in [InterpolationMode::Nearest, InterpolationMode::Bilinear] {
                let bits: Vec<u8> = (0..(sw as usize).div_ceil(8) * sh as usize)
                    .map(|_| rng.byte())
                    .collect();
                let mut img = bilevel_image(sw, sh, bits, ox, oy, w, h);
                img.interpolation = interpolation;
                let mut got = dispatched(&img, side);
                let (mut want, _) = generic_masked_reference(&img, side, side);
                let what =
                    format!("gray1 {interpolation:?} src {sw}x{sh} at ({ox}, {oy}) size {w}x{h}");
                assert_surfaces_equal(&mut got, &mut want, &what);
                checked += 1;
            }
        }
        assert_eq!(checked, 5 * 4 * 4 * 2 + 5 * 2 * 2 + 5 * 2);
    }

    /// `img` re-placed by the forward map `[a b c d e f]` from its unit
    /// square to device space (any orientation, rotation or mirror), with its
    /// device bounds and footprint recomputed to match.
    fn place_forward(mut img: PreparedImage, forward: Matrix) -> PreparedImage {
        img.inv = forward.invert().expect("an invertible placement");
        let corners = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)]
            .map(|(u, v)| forward.apply(crate::page_ir::Point { x: u, y: v }));
        let lx = corners.iter().map(|p| p.x).fold(f64::INFINITY, f64::min);
        let hx = corners
            .iter()
            .map(|p| p.x)
            .fold(f64::NEG_INFINITY, f64::max);
        let ly = corners.iter().map(|p| p.y).fold(f64::INFINITY, f64::min);
        let hy = corners
            .iter()
            .map(|p| p.y)
            .fold(f64::NEG_INFINITY, f64::max);
        img.bounds = DeviceRect {
            x: lx.floor() as i32,
            y: ly.floor() as i32,
            width: (hx.ceil() - lx.floor()) as u32,
            height: (hy.ceil() - ly.floor()) as u32,
        };
        let du = forward.a.hypot(forward.b);
        let dv = forward.c.hypot(forward.d);
        img.footprint = [img.width as f64 / du, img.height as f64 / dv];
        img
    }

    /// The forward map of a `w x h` device rectangle at `(ox, oy)` rotated by
    /// `deg` degrees about its origin corner; a negative `w` or `h` mirrors.
    fn forward_rect(ox: f64, oy: f64, w: f64, h: f64, deg: f64) -> Matrix {
        let (s, c) = deg.to_radians().sin_cos();
        Matrix {
            a: w * c,
            b: w * s,
            c: -h * s,
            d: h * c,
            e: ox,
            f: oy,
        }
    }

    /// `backdrop_px` after `img` paints the device pixel `(x, y)` at full
    /// geometric weight: `shade()` at the pixel centre composited over it, or
    /// the backdrop untouched where the centre maps outside the image. This
    /// is the pixel-centre rule the axis-aligned opaque fast paths follow.
    fn pixel_centre_expected(
        img: &PreparedImage,
        backdrop_px: &[u8],
        x: usize,
        y: usize,
    ) -> Vec<u8> {
        let mut out = backdrop_px.to_vec();
        if let Some(c) = img.shade(x as f64 + 0.5, y as f64 + 0.5) {
            let a = mul_div_255(c[3] as u16, img.alpha as u16);
            if a > 0 {
                composite_px_blended(&mut out, [c[0], c[1], c[2]], a as u8, BlendChoice::Normal);
            }
        }
        out
    }

    /// Paint `img` with the generic body over a seeded backdrop. Returns
    /// `(mismatches, partial, border)`: the pixels that differ from the
    /// pixel-centre expectation, the border pixels (those `edge_coverage`
    /// does not call interior) that are partial blends — neither the
    /// untouched backdrop nor a full-weight composite of the centre sample
    /// or of the nearest edge sample — and the border pixel count.
    fn generic_edge_census(img: &PreparedImage, side: u32, seed: u64) -> (usize, usize, usize) {
        let mut before = backdrop(side, seed);
        let mut got = backdrop(side, seed);
        let b = img.bounds;
        let (x0, y0) = (b.x.max(0) as usize, b.y.max(0) as usize);
        let x1 = ((b.x + b.width as i32) as usize).min(side as usize);
        let y1 = ((b.y + b.height as i32) as usize).min(side as usize);
        paint_image_generic(
            img,
            &mut got,
            None,
            None,
            BlendChoice::Normal,
            x0,
            y0,
            x1,
            y1,
            None,
        );
        let (mut mismatches, mut partial, mut border) = (0, 0, 0);
        for y in 0..side as usize {
            let (g, r) = (got.row_mut(y).to_vec(), before.row_mut(y).to_vec());
            for x in 0..side as usize {
                let (gp, rp) = (&g[x * 4..x * 4 + 4], &r[x * 4..x * 4 + 4]);
                let full = pixel_centre_expected(img, rp, x, y);
                if gp != full.as_slice() {
                    mismatches += 1;
                }
                if img.edge_coverage(x as f64 + 0.5, y as f64 + 0.5).is_some() {
                    border += 1;
                    let mut clamped = rp.to_vec();
                    if let Some(c) = img.shade_clamped(x as f64 + 0.5, y as f64 + 0.5) {
                        let a = mul_div_255(c[3] as u16, img.alpha as u16);
                        if a > 0 {
                            composite_px_blended(
                                &mut clamped,
                                [c[0], c[1], c[2]],
                                a as u8,
                                BlendChoice::Normal,
                            );
                        }
                    }
                    if gp != rp && gp != full.as_slice() && gp != clamped.as_slice() {
                        partial += 1;
                    }
                }
            }
        }
        (mismatches, partial, border)
    }

    /// Masked images on an axis-aligned placement with fractional device
    /// edges (`/ImageMask` stencils, also mirrored on either axis, `/SMask`
    /// soft masks, `/Mask` stencil masks and one-bit gray images: everything
    /// the generic body paints) follow the pixel-centre rule at their outer
    /// edge. A boundary pixel is the full image/mask result when its centre
    /// lies inside the destination rectangle and the untouched backdrop
    /// otherwise, never a blend, as the axis-aligned opaque fast paths paint
    /// it (`masked-image-ring-20261108.md` compares both with PDFium, which
    /// is never a blend either). The mask itself still applies per
    /// sampled pixel. The same draws rotated by 15 degrees keep A10's
    /// fractional edge coverage.
    #[test]
    fn axis_aligned_masked_edges_follow_the_pixel_centre_rule() {
        let mut rng = Rng(0x71c3_e05e_a117_0001);
        // (source w, h, device x, y, w, h): magnified, near 1:1, minified.
        let placements: [(u32, u32, f64, f64, f64, f64); 4] = [
            (5, 7, 2.6, 1.4, 17.8, 21.3),
            (16, 16, 2.25, 2.75, 15.5, 15.5),
            (64, 48, 2.5, 3.125, 20.3, 14.7),
            (37, 23, 3.3, 2.6, 9.4, 6.2),
        ];
        let side = 40u32;
        let mut cases = 0;
        for &(sw, sh, ox, oy, w, h) in &placements {
            let mut images: Vec<(String, PreparedImage)> = Vec::new();
            for inverted in [false, true] {
                let img = stencil_image(sw, sh, ox, oy, w, h, inverted, &mut rng);
                images.push((format!("imagemask inverted {inverted}"), img));
            }
            let img = stencil_image(sw, sh, ox, oy, w, h, false, &mut rng);
            images.push((
                "imagemask mirrored x".into(),
                place_forward(img, forward_rect(ox + w, oy, -w, h, 0.0)),
            ));
            let img = stencil_image(sw, sh, ox, oy, w, h, false, &mut rng);
            images.push((
                "imagemask mirrored y".into(),
                place_forward(img, forward_rect(ox, oy + h, w, -h, 0.0)),
            ));
            let rgb: Vec<u8> = (0..sw as usize * sh as usize * 3)
                .map(|_| rng.byte())
                .collect();
            let base = place(
                make_image_cs(sw, sh, 1, 1, ImageColorSpace::Rgb, rgb),
                ox,
                oy,
                w,
                h,
            );
            let (mw, mh) = (sw.div_ceil(2) + 1, sh + 3);
            let mut smask8 = base.clone();
            let mask: Vec<u8> = (0..mw * mh)
                .map(|_| if rng.byte() < 60 { rng.byte() } else { 255 })
                .collect();
            smask8.smask = Some(Arc::new(crate::page_ir::ImageSMask {
                width: mw,
                height: mh,
                bits_per_component: 8,
                decode: None,
                samples: Arc::from(mask),
                codec: None,
                codec_data: None,
                codec_parms: None,
            }));
            images.push(("smask8".into(), smask8));
            let mut smask1 = base.clone();
            smask1.smask = Some(bilevel(mw, mh, &mut rng));
            images.push(("smask1".into(), smask1));
            let mut stencil_mask = base.clone();
            stencil_mask.mask = Some(crate::page_ir::ImageMask::Stencil(bilevel(
                mw, mh, &mut rng,
            )));
            // `paint_image` turns a minified hard stencil mask into coverage.
            let stencil_mask = stencil_mask
                .minified_stencil_as_coverage()
                .unwrap_or(stencil_mask);
            images.push(("mask stencil".into(), stencil_mask));
            let bits: Vec<u8> = (0..(sw as usize).div_ceil(8) * sh as usize)
                .map(|_| rng.byte())
                .collect();
            images.push(("gray1".into(), bilevel_image(sw, sh, bits, ox, oy, w, h)));

            for (name, img) in &images {
                for interpolation in [InterpolationMode::Nearest, InterpolationMode::Bilinear] {
                    let mut img = img.clone();
                    img.interpolation = interpolation;
                    let what = format!(
                        "{name} {interpolation:?} src {sw}x{sh} at ({ox}, {oy}) size {w}x{h}"
                    );
                    let seed = rng.next();
                    let (mismatches, partial, border) = generic_edge_census(&img, side, seed);
                    assert!(border > 0, "{what}: the placement must have a border ring");
                    assert_eq!(
                        (mismatches, partial),
                        (0, 0),
                        "{what}: axis-aligned edge pixels must be all-or-nothing by pixel centre"
                    );

                    // The same draw rotated 15 degrees about its first corner
                    // keeps fractional edge coverage.
                    let unit = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)].map(|(u, v)| {
                        let m = img.inv.invert().expect("invertible");
                        m.apply(crate::page_ir::Point { x: u, y: v })
                    });
                    let forward = forward_rect(
                        unit[0].x + 6.0,
                        unit[0].y,
                        unit[1].x - unit[0].x,
                        unit[2].y - unit[0].y,
                        15.0,
                    );
                    let rotated = place_forward(img.clone(), forward);
                    let (_, partial, _) = generic_edge_census(&rotated, side + 8, seed);
                    assert!(
                        partial > 0,
                        "{what} rotated 15 degrees: no partial edge pixels"
                    );
                    cases += 1;
                }
            }
        }
        assert_eq!(cases, 4 * 8 * 2);
    }
}

#[cfg(test)]
mod cancel_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;
    use crate::page_ir::DeviceSize;
    use crate::render_api::Background;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// A prepared page of `n` identical opaque square fills.
    fn page_with_fills(
        n: usize,
        cancel: Option<Arc<dyn Fn() -> bool + Send + Sync>>,
    ) -> crate::render_cpu::prepared::CpuPreparedPage {
        let points = vec![[10.0f32, 10.0], [50.0, 10.0], [50.0, 50.0], [10.0, 50.0]];
        let subpaths = vec![(0usize, 4usize)];
        let cmd = crate::render_cpu::prepared::PreparedCommand {
            origin: crate::page_ir::PaintOrigin::PageContent,
            class: crate::render_cpu::prepared::DrawClass::SolidPath,
            subpath_range: (0, 1),
            rule: crate::render_cpu::raster::FillRule::NonZero,
            rgb: [0, 0, 0],
            premul: [0, 0, 0, 255],
            alpha: 255,
            opaque: true,
            bounds: crate::page_ir::DeviceRect {
                x: 10,
                y: 10,
                width: 40,
                height: 40,
            },
            clip: None,
            clip_has_mask: false,
            blend: crate::page_ir::BlendMode::Normal,
            shading: None,
            stencil: None,
        };
        let ops = (0..n).map(|_| PreparedOp::Draw(cmd.clone())).collect();
        crate::render_cpu::prepared::CpuPreparedPage {
            size: DeviceSize {
                width: 64,
                height: 64,
            },
            ops,
            clips: Vec::new(),
            points,
            subpaths,
            codecs: crate::image::CodecRegistry::default(),
            decode_limits: crate::image::DecodeLimits {
                should_cancel: cancel,
                ..Default::default()
            },
            hinting: crate::font::HintingPolicy::None,
            color_policy: crate::render_api::RenderColorPolicy::Original,
            diagnostics: Default::default(),
            image_cache: None,
            decode_floor: None,
            sanity_extent: 64.0,
            #[cfg(feature = "profiling")]
            profile: Default::default(),
            #[cfg(feature = "profiling")]
            decode_cache: None,
            #[cfg(feature = "profiling")]
            lower_prof: Default::default(),
        }
    }

    #[test]
    fn mid_render_cancellation_stops_between_ops() {
        // The token fires from the very first check: execution must stop at
        // an op boundary with the cancelled flag set, not run all 64 draws.
        let checks = Arc::new(AtomicUsize::new(0));
        let seen = checks.clone();
        let cancel: Arc<dyn Fn() -> bool + Send + Sync> = Arc::new(move || {
            seen.fetch_add(1, Ordering::Relaxed);
            true
        });
        let page = page_with_fills(64, Some(cancel));
        let mut surface = Surface::new(64, 64, Background::White);
        let mut ctx = CpuWorkerContext::default();
        let mut stats = RenderStats::default();
        execute(&page, &mut surface, &mut ctx, &mut stats);
        assert!(stats.cancelled, "mid-render cancellation must be recorded");
        assert_eq!(stats.commands, 0, "no command runs after the flag fires");
        assert!(checks.load(Ordering::Relaxed) >= 1);
    }

    #[test]
    fn cancellation_stops_inside_a_single_coverage_command() {
        // Let the pre-pass and op-boundary probes pass, then fire from the
        // RasterKernel checkpoints while the first (and only) draw is active.
        let checks = Arc::new(AtomicUsize::new(0));
        let seen = checks.clone();
        let cancel: Arc<dyn Fn() -> bool + Send + Sync> =
            Arc::new(move || seen.fetch_add(1, Ordering::Relaxed) >= 3);
        let page = page_with_fills(1, Some(cancel));
        let mut surface = Surface::new(64, 64, Background::White);
        let mut ctx = CpuWorkerContext::default();
        let mut stats = RenderStats::default();
        execute(&page, &mut surface, &mut ctx, &mut stats);
        assert!(stats.cancelled);
        assert_eq!(
            stats.commands, 1,
            "the command began, so cancellation was not merely an op-boundary check"
        );
        assert!(checks.load(Ordering::Relaxed) >= 4);
    }

    #[test]
    fn uncancelled_render_executes_every_op() {
        let page = page_with_fills(64, None);
        let mut surface = Surface::new(64, 64, Background::White);
        let mut ctx = CpuWorkerContext::default();
        let mut stats = RenderStats::default();
        execute(&page, &mut surface, &mut ctx, &mut stats);
        assert!(!stats.cancelled);
        assert_eq!(stats.commands, 64);
    }
}

#[cfg(test)]
mod bilevel_sat_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
    use super::*;

    /// The serial reference walk from `BilevelIntegral::build`, verbatim.
    #[allow(clippy::too_many_arguments)]
    fn serial_fill(
        sat: &mut [u32],
        samples: &[u8],
        stride: usize,
        sw: usize,
        sh: usize,
        row_bits: usize,
        col_lo: u32,
        row_lo: u32,
    ) {
        for ly in 0..sh {
            let source_row = row_lo as usize + ly;
            let base_bit = source_row * row_bits + col_lo as usize;
            let (prev, cur) = sat.split_at_mut((ly + 1) * stride);
            let prev = &prev[ly * stride..ly * stride + stride];
            let cur = &mut cur[..stride];
            let mut rowsum = 0u32;
            for (lx, bitpos) in (base_bit..base_bit + sw).enumerate() {
                let byte = samples[bitpos >> 3];
                rowsum += ((byte >> (7 - (bitpos & 7))) & 1) as u32;
                cur[lx + 1] = prev[lx + 1] + rowsum;
            }
        }
    }

    /// The blocked parallel fill must reproduce the serial table exactly —
    /// including its zero sentinel row and column — for row counts that fall
    /// short of, land on, and overrun the block boundary.
    #[test]
    fn parallel_sat_fill_matches_serial_bit_exact() {
        let mut state = 0x2545_F491_4F6C_DD1Du64;
        let mut next = move || {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            state
        };
        for &(width, height) in &[
            (1usize, 1usize),
            (7, 3),
            (8, 8),
            (13, 1),
            (1, 97),
            (64, 64),
            (129, 251),
            (255, 129),
        ] {
            let row_bits = width.next_multiple_of(8);
            let samples: Vec<u8> = (0..(row_bits / 8) * height).map(|_| next() as u8).collect();
            // Exercise both a full-image window and an offset sub-window.
            for &(want_col_lo, want_row_lo) in &[(0usize, 0usize), (1, 1)] {
                let (col_lo, row_lo) = (
                    if want_col_lo < width { want_col_lo } else { 0 },
                    if want_row_lo < height { want_row_lo } else { 0 },
                );
                let (sw, sh) = (width - col_lo, height - row_lo);
                let (col_lo, row_lo) = (col_lo as u32, row_lo as u32);
                let stride = sw + 1;
                let entries = stride * (sh + 1);
                let mut want = vec![0u32; entries];
                serial_fill(
                    &mut want, &samples, stride, sw, sh, row_bits, col_lo, row_lo,
                );
                let mut got = vec![0u32; entries];
                BilevelIntegral::fill_parallel(
                    &mut got, &samples, stride, sw, sh, row_bits, col_lo, row_lo,
                );
                assert_eq!(got, want, "{width}x{height} window ({col_lo},{row_lo})");
            }
        }
    }
}

#[cfg(test)]
mod tiling_cull_tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

    //! Tile culling must not change a byte: every case renders once with
    //! culling and once rendering every tile instance, and compares pixels.

    use std::sync::Arc;

    use super::RENDER_ALL_TILES;
    use crate::page_ir::{
        BlendMode, Color, CompiledPage, DeviceSize, DisplayOp, FillRule, LineCap, LineJoin, Matrix,
        PageBounds, PageComplexity, PageFeatures, Paint, PaintId, PathData, PathId, PathVerb,
        Point, Rect, StrokeStyle, StrokeStyleId, TilingId, TilingPattern,
    };
    use crate::render_api::{
        AnnotationMode, Background, OutputFormat, OutputResidency, PageTransform, RenderLimits,
        RenderQuality, RenderRequest,
    };
    use crate::render_cpu::CpuBackend;

    struct Rng(u64);

    impl Rng {
        fn next(&mut self) -> u64 {
            self.0 ^= self.0 << 13;
            self.0 ^= self.0 >> 7;
            self.0 ^= self.0 << 17;
            self.0
        }
        fn unit(&mut self) -> f64 {
            (self.next() >> 11) as f64 / (1u64 << 53) as f64
        }
        fn range(&mut self, lo: f64, hi: f64) -> f64 {
            lo + (hi - lo) * self.unit()
        }
        fn pick(&mut self, n: u64) -> u64 {
            self.next() % n
        }
    }

    fn polyline(points: &[(f64, f64)], close: bool) -> PathData {
        let mut verbs = vec![PathVerb::MoveTo];
        verbs.extend(std::iter::repeat_n(PathVerb::LineTo, points.len() - 1));
        if close {
            verbs.push(PathVerb::Close);
        }
        PathData {
            verbs: Arc::from(verbs),
            points: points.iter().map(|&(x, y)| Point { x, y }).collect(),
        }
    }

    fn curve(points: [(f64, f64); 4]) -> PathData {
        PathData {
            verbs: Arc::from([PathVerb::MoveTo, PathVerb::CurveTo]),
            points: points.iter().map(|&(x, y)| Point { x, y }).collect(),
        }
    }

    fn page(
        size: f64,
        operations: Vec<DisplayOp>,
        paths: Vec<PathData>,
        paints: Vec<Paint>,
        stroke_styles: Vec<StrokeStyle>,
        tilings: Vec<TilingPattern>,
    ) -> CompiledPage {
        CompiledPage {
            schema_version: crate::page_ir::IR_SCHEMA_VERSION,
            content_bounds: None,
            bounds: PageBounds {
                crop: Rect {
                    x0: 0.0,
                    y0: 0.0,
                    x1: size,
                    y1: size,
                },
                rotate: 0,
            },
            operations: Arc::from(operations),
            paths: Arc::from(paths),
            paints: Arc::from(paints),
            stroke_styles: Arc::from(stroke_styles),
            glyph_runs: Arc::from([]),
            fonts: Arc::from([]),
            images: Arc::from([]),
            masks: Arc::from([]),
            groups: Arc::from([]),
            shadings: Arc::from([]),
            tilings: Arc::from(tilings),
            features: PageFeatures::BASIC_PATHS | PageFeatures::PATTERNS,
            complexity: PageComplexity::default(),
        }
    }

    fn style(rng: &mut Rng, width: f64) -> StrokeStyle {
        StrokeStyle {
            width,
            cap: [LineCap::Butt, LineCap::Round, LineCap::Square][rng.pick(3) as usize],
            join: [LineJoin::Miter, LineJoin::Round, LineJoin::Bevel][rng.pick(3) as usize],
            miter_limit: rng.range(1.0, 12.0),
            dash_pattern: Arc::from([]),
            dash_phase: 0.0,
        }
    }

    /// A random cell: one to three fills and strokes whose geometry may poke
    /// well outside the cell's bounding box (cells are not clipped to it).
    fn random_cell(rng: &mut Rng, cell: f64) -> CompiledPage {
        let mut operations = Vec::new();
        let mut paths = Vec::new();
        let mut paints = Vec::new();
        let mut styles = Vec::new();
        for _ in 0..=rng.pick(3) {
            let color = Color {
                r: rng.unit() as f32,
                g: rng.unit() as f32,
                b: rng.unit() as f32,
                a: 1.0,
            };
            paints.push(Paint::Solid(color));
            let paint = PaintId(paints.len() as u32 - 1);
            let alpha = if rng.pick(2) == 0 { 1.0 } else { 0.6 };
            let p = |rng: &mut Rng| (rng.range(-0.4 * cell, 1.4 * cell), rng.range(-0.4 * cell, 1.4 * cell));
            let path = match rng.pick(3) {
                0 => polyline(&[p(rng), p(rng), p(rng)], true),
                1 => polyline(&[p(rng), p(rng), p(rng), p(rng)], false),
                _ => curve([p(rng), p(rng), p(rng), p(rng)]),
            };
            paths.push(path);
            let path = PathId(paths.len() as u32 - 1);
            if rng.pick(2) == 0 {
                operations.push(DisplayOp::FillPath {
                    path,
                    paint,
                    rule: if rng.pick(2) == 0 { FillRule::NonZero } else { FillRule::EvenOdd },
                    alpha,
                    blend: BlendMode::Normal,
                });
            } else {
                // From sub-pixel hairlines to pens wider than the cell.
                let width = [0.0, 0.05, 0.4, 1.0, 2.5][rng.pick(5) as usize] * cell.min(4.0);
                styles.push(style(rng, width));
                operations.push(DisplayOp::Save);
                operations.push(DisplayOp::ConcatTransform(Matrix {
                    a: rng.range(0.5, 2.0),
                    b: rng.range(-0.3, 0.3),
                    c: rng.range(-0.3, 0.3),
                    d: rng.range(0.5, 2.0),
                    e: 0.0,
                    f: 0.0,
                }));
                operations.push(DisplayOp::StrokePath {
                    path,
                    paint,
                    style: StrokeStyleId(styles.len() as u32 - 1),
                    alpha,
                    blend: BlendMode::Normal,
                });
                operations.push(DisplayOp::Restore);
            }
        }
        page(cell, operations, paths, paints, styles, Vec::new())
    }

    fn render(page: &Arc<CompiledPage>, dim: u32, scale: f64) -> (Arc<[u8]>, u32) {
        let request = RenderRequest {
            page: Arc::clone(page),
            transform: PageTransform {
                matrix: Matrix {
                    a: scale,
                    b: 0.0,
                    c: 0.0,
                    d: scale,
                    e: 0.0,
                    f: 0.0,
                },
            },
            crop: None,
            output_size: DeviceSize {
                width: dim,
                height: dim,
            },
            output_format: OutputFormat::Rgba8PremultipliedSrgb,
            background: Background::White,
            annotations: AnnotationMode::None,
            color_policy: crate::render_api::RenderColorPolicy::Original,
            quality: RenderQuality::Normal,
            limits: RenderLimits::default(),
            residency: OutputResidency::HostRequired,
        };
        let (host, stats) = CpuBackend::default().render_to_host(&request).unwrap();
        (host.pixels, stats.commands)
    }

    #[test]
    fn culled_tiles_never_change_pixels() {
        let mut rng = Rng(0x9e37_79b9_7f4a_7c15);
        let mut culled_cases = 0;
        let mut painted_cases = 0;
        for case in 0..160 {
            let size = 96.0;
            let cell = rng.range(1.5, 14.0);
            let tiling = TilingPattern {
                key: crate::page_ir::ResourceKey {
                    object_number: case,
                    generation: 0,
                    variant: 0,
                },
                uncolored: rng.pick(4) == 0,
                under_color: Color {
                    r: 0.1,
                    g: 0.5,
                    b: 0.9,
                    a: 1.0,
                },
                bbox: [0.0, 0.0, cell as f32, cell as f32],
                // Steps below the cell size make neighbouring tiles overlap.
                x_step: (cell * rng.range(0.6, 1.6)) as f32,
                y_step: (cell * rng.range(0.6, 1.6)) as f32,
                cell: Arc::new(random_cell(&mut rng, cell)),
            };
            let angle = rng.range(0.0, std::f64::consts::TAU);
            let (sx, sy) = (rng.range(0.4, 2.2), rng.range(0.4, 2.2));
            let matrix = Matrix {
                a: sx * angle.cos(),
                b: sx * angle.sin(),
                c: -sy * angle.sin(),
                d: sy * angle.cos(),
                e: rng.range(-20.0, 20.0),
                f: rng.range(-20.0, 20.0),
            };
            let paints = vec![Paint::Pattern {
                tiling: TilingId(0),
                matrix,
            }];
            let p = |rng: &mut Rng| (rng.range(-10.0, size + 10.0), rng.range(-10.0, size + 10.0));
            // Pattern-painted strokes and slivers leave most of the tiled
            // box uncovered; a full-page fill leaves nothing to cull.
            let (operations, paths, styles) = match rng.pick(4) {
                0 => {
                    let line = polyline(&[p(&mut rng), p(&mut rng), p(&mut rng)], false);
                    let width = rng.range(0.3, 5.0);
                    (
                        vec![DisplayOp::StrokePath {
                            path: PathId(0),
                            paint: PaintId(0),
                            style: StrokeStyleId(0),
                            alpha: 1.0,
                            blend: BlendMode::Normal,
                        }],
                        vec![line],
                        vec![style(&mut rng, width)],
                    )
                }
                1 => (
                    vec![DisplayOp::FillPath {
                        path: PathId(0),
                        paint: PaintId(0),
                        rule: FillRule::EvenOdd,
                        alpha: 0.8,
                        blend: BlendMode::Multiply,
                    }],
                    vec![polyline(&[p(&mut rng), p(&mut rng), p(&mut rng), p(&mut rng)], true)],
                    Vec::new(),
                ),
                2 => (
                    vec![DisplayOp::FillPath {
                        path: PathId(0),
                        paint: PaintId(0),
                        rule: FillRule::NonZero,
                        alpha: 1.0,
                        blend: BlendMode::Normal,
                    }],
                    vec![polyline(&[(0.0, 0.0), (size, 0.0), (size, size), (0.0, size)], true)],
                    Vec::new(),
                ),
                _ => (
                    vec![DisplayOp::FillPath {
                        path: PathId(0),
                        paint: PaintId(0),
                        rule: FillRule::NonZero,
                        alpha: 1.0,
                        blend: BlendMode::Normal,
                    }],
                    vec![polyline(&[p(&mut rng), p(&mut rng), p(&mut rng)], true)],
                    Vec::new(),
                ),
            };
            let compiled = Arc::new(page(size, operations, paths, paints, styles, vec![tiling]));
            let scale = [1.0, 0.37, 2.13][case as usize % 3];
            let dim = (size * scale).ceil() as u32;

            RENDER_ALL_TILES.with(|flag| flag.set(true));
            let (reference, reference_commands) = render(&compiled, dim, scale);
            RENDER_ALL_TILES.with(|flag| flag.set(false));
            let (culled, culled_commands) = render(&compiled, dim, scale);

            assert!(
                reference == culled,
                "case {case}: tile culling changed pixels (scale {scale})"
            );
            assert!(culled_commands <= reference_commands, "case {case}");
            if culled_commands < reference_commands {
                culled_cases += 1;
            }
            if reference.iter().any(|&byte| byte != 255) {
                painted_cases += 1;
            }
        }
        // The comparison is vacuous unless tiles are really skipped and the
        // pattern really paints.
        assert!(culled_cases >= 40, "only {culled_cases} cases culled a tile");
        assert!(painted_cases >= 100, "only {painted_cases} cases painted");
    }

    /// A cell this cannot bound (here, a nested pattern paint) is never culled.
    #[test]
    fn unbounded_cells_are_not_culled() {
        let inner = page(
            4.0,
            vec![DisplayOp::FillPath {
                path: PathId(0),
                paint: PaintId(0),
                rule: FillRule::NonZero,
                alpha: 1.0,
                blend: BlendMode::Normal,
            }],
            vec![polyline(&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)], true)],
            vec![Paint::Pattern {
                tiling: TilingId(0),
                matrix: Matrix::IDENTITY,
            }],
            Vec::new(),
            Vec::new(),
        );
        assert!(super::cell_paint_extent(&inner).is_none());

        let empty = page(4.0, Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new());
        assert!(super::cell_paint_extent(&empty).is_none());
    }
}