exprim 0.4.1

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
//! The CPU raster backend — the engine's **normative implementation** of
//! rendering semantics (roadmap §2.3) and permanent fallback/oracle for the
//! GPU backend.
//!
//! Architecture (Phase 4): a tiled rasterizer; `CompiledPage` lowers to
//! per-tile operation lists preserving painter order; every worker owns a
//! [`CpuWorkerContext`] with all scratch buffers — no shared mutable state,
//! no global allocator pressure.
//!
//! This is the **production scalar raster engine**, not a throwaway reference:
//! it is designed for speed from the first commit, and its scalar kernels are
//! the reference for later SIMD kernels. The pipeline (per the performance
//! architecture) is:
//!
//! ```text
//! CompiledPage + RenderRequest
//!   → CpuPreparedPage      (transform, cull, classify, flatten — once/request)
//!   → executor             (compact commands; no Arc/lookup in the hot loop)
//!   → RasterKernel         (analytic scanline coverage → u8 rows)
//!   → KernelSet spans      (opaque-fill / const-blend / mask-blend, chosen once/span)
//!   → Surface / HostPage
//! ```
//!
//! Current state (Phase 4a): **solid fills with constant alpha**, with an
//! opaque-integer-rect fast path and per-render instrumentation
//! ([`RenderStats`]). Clipping, strokes, images, text, blend modes, and
//! transparency arrive in later 4x checkpoints (advice §16 order); preflight
//! (`supports()`) advertises exactly what is implemented so unsupported pages
//! route elsewhere. Adaptive band/tile execution is deferred until direct-page
//! rendering is competitive (advice §2).

use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use crate::page_ir::{CompiledPage, DeviceSize, ImageMask, Matrix, PageFeatures};
use crate::render_api::{
    BackendCapabilities, BackendId, HostPage, OutputFormat, PostprocessCapabilities, RenderBackend,
    RenderError, RenderLimits, RenderRequest, RenderTicket, RenderedPage, SubmitError,
    SupportLevel, UnsupportedFeature,
};

pub mod attribution;
mod exec;
mod image;
mod kernels;
mod mask;
mod prepared;
mod raster;
mod stats;
mod stroke;
mod surface;

pub use exec::CpuWorkerContext;
pub use kernels::KernelSet;
#[cfg(feature = "profiling")]
pub use prepared::DecodedImageCache;
pub use prepared::{CpuPreparedPage, DrawClass};
pub use stats::RenderStats;
pub use surface::surface_slot_stats;

use surface::Surface;
use {
    mask::{ClipGeom, build_clip_mask_cancellable},
    raster::RasterKernel,
};

fn image_decode_limits(limits: &RenderLimits) -> crate::image::DecodeLimits {
    let defaults = crate::image::DecodeLimits::default();
    crate::image::DecodeLimits {
        // A request may tighten the codec defaults, but must not silently raise
        // their defensive encoded-input or scratch-memory ceilings.
        max_input_bytes: defaults.max_input_bytes.min(limits.max_page_bytes),
        max_pixels: defaults.max_pixels,
        max_output_bytes: defaults.max_output_bytes.min(limits.max_page_bytes),
        max_working_bytes: defaults.max_working_bytes.min(limits.max_page_bytes),
        should_cancel: limits.cancellation.clone().map(|token| {
            std::sync::Arc::new(move || token.is_cancelled())
                as std::sync::Arc<dyn Fn() -> bool + Send + Sync>
        }),
    }
}

/// One image draw lowered to RGB8 plus optional independent opacity for a
/// non-CPU raster backend.
///
/// This deliberately exposes only the small, semantics-neutral subset used
/// by the experimental GPU image renderer. PDF image decoding, `/Decode`,
/// color-space conversion, clipping, and request transforms remain owned by
/// this crate.
#[derive(Debug, Clone)]
pub struct PreparedRgbImage {
    pub bounds: crate::page_ir::DeviceRect,
    /// Device coordinates to the image's normalized `[0, 1]²` square.
    pub device_to_image: Matrix,
    pub width: u32,
    pub height: u32,
    pub samples: Arc<[u8]>,
    pub interpolation: crate::page_ir::InterpolationMode,
    /// Source texels covered by one destination pixel on each image axis.
    pub footprint: [f64; 2],
    /// Independently sampled opacity for an image `/SMask`, explicit `/Mask`,
    /// or solid-colour `/ImageMask` stencil. The samples are tight alpha8 in
    /// top-down order.
    pub opacity: Option<PreparedImageOpacity>,
    /// Device-space analytic clip coverage. Unlike image opacity this plane is
    /// already rasterized at destination resolution and is addressed by
    /// absolute device coordinates.
    pub clip: Option<PreparedImageClip>,
    /// Active page-level `/SMask`, derived by the normative CPU group
    /// executor and sampled in absolute device coordinates. This is separate
    /// from `opacity` (an image-resource mask) and `clip` because all three
    /// coverages multiply independently.
    pub soft_mask: Option<PreparedImageSoftMask>,
    /// Constant graphics-state opacity for this image draw.
    pub alpha: u8,
    /// PDF compositing mode for this image draw.
    pub blend: crate::page_ir::BlendMode,
    /// Solid brush for `/ImageMask`; `None` means sample `samples` as RGB8.
    pub stencil_rgb: Option<[u8; 3]>,
}

/// One solid path draw in the ordered experimental GPU command stream.
#[derive(Debug, Clone)]
pub struct PreparedGpuPath {
    pub bounds: crate::page_ir::DeviceRect,
    /// Packed GPU raster data: four-word header, directed f32 edges, 16-row
    /// band offsets, then edge indices. Values are u32 so the same storage
    /// binding can carry float bits and integer lookup tables.
    pub raster_data: Arc<[u32]>,
    pub edge_count: u32,
    pub band_edge_references: u32,
    pub even_odd: bool,
    pub rgb: [u8; 3],
    pub alpha: u8,
    pub blend: crate::page_ir::BlendMode,
    pub clip: Option<PreparedImageClip>,
    pub soft_mask: Option<PreparedImageSoftMask>,
}

/// One active 8×8 destination tile and its painter-ordered path list.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PreparedGpuPathTile {
    pub x: u32,
    pub y: u32,
    pub path_offset: u32,
    pub path_count: u32,
}

/// A maximal painter-ordered path run prepared for one GPU dispatch.
#[derive(Debug, Clone)]
pub struct PreparedGpuPathBatch {
    pub paths: Arc<[PreparedGpuPath]>,
    pub tiles: Arc<[PreparedGpuPathTile]>,
    pub tile_path_indices: Arc<[u32]>,
    pub geometry_bytes: usize,
    pub mask_bytes: usize,
    pub max_tile_depth: u32,
}

/// Painter-ordered vocabulary accepted by the experimental GPU renderer.
#[derive(Debug, Clone)]
pub enum PreparedGpuCommand {
    Image(u32),
    /// Retained as an internal diagnostic/reference command. Normal
    /// preparation coalesces every such path into `PathBatch`.
    Path(PreparedGpuPath),
    PathBatch(Arc<PreparedGpuPathBatch>),
}

/// One normalized alpha8 plane sampled in the image's unit-square geometry.
#[derive(Debug, Clone)]
pub struct PreparedImageOpacity {
    pub width: u32,
    pub height: u32,
    pub samples: Arc<[u8]>,
    /// Mask texels covered by one destination pixel on each mask axis.
    pub footprint: [f64; 2],
    /// Soft masks and image stencils represent coverage and may be averaged
    /// during minification. Explicit hard `/Mask` values remain binary and
    /// are sampled at the destination pixel's source point.
    pub box_filter: bool,
}

/// A native-resolution grayscale opacity plane decoded from a one-bit image
/// `/SMask`.  This is intentionally narrower than the general image decode
/// seam: callers can preserve the encoded mask bytes separately while using
/// these samples for analysis or background cleanup.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DecodedBilevelSmask {
    pub width: u32,
    pub height: u32,
    pub stride: usize,
    /// Tight Gray8 opacity, top-down: 0 is transparent and 255 is opaque.
    pub opacity: Arc<[u8]>,
}

/// One exact anti-aliased path-clip mask over a bounded device rectangle.
#[derive(Debug, Clone)]
pub struct PreparedImageClip {
    pub bounds: crate::page_ir::DeviceRect,
    pub samples: Arc<[u8]>,
}

/// One derived page-level soft-mask coverage plane over a bounded device
/// rectangle. Pixels outside `bounds` use `outside`; this is normally zero,
/// but a luminosity mask with `/BC` (or `/TR`) can make it nonzero.
#[derive(Debug, Clone)]
pub struct PreparedImageSoftMask {
    pub bounds: crate::page_ir::DeviceRect,
    pub samples: Arc<[u8]>,
    pub outside: u8,
}

/// A patterned `/ImageMask` brush rasterized by the normative CPU pattern
/// executor into a bounded straight-RGB plane plus independent alpha.
///
/// Pattern cells may contain paths, text, images, groups, and nested patterns;
/// keeping that vocabulary on the CPU makes this a narrow image-compositor
/// bridge rather than an accidental mixed-content GPU renderer.
#[derive(Debug, Clone)]
pub(crate) struct PreparedPatternedStencil {
    pub bounds: crate::page_ir::DeviceRect,
    pub samples: Arc<[u8]>,
    pub opacity: Arc<[u8]>,
}

/// An image-only page prepared for an offscreen raster backend.
#[derive(Debug, Clone)]
pub struct PreparedRgbImagePage {
    pub size: DeviceSize,
    pub images: Vec<PreparedRgbImage>,
    /// Exact painter order. Image commands index `images`; path commands own
    /// their immutable flattened edge geometry.
    pub commands: Vec<PreparedGpuCommand>,
}

/// Maximum full-source RGB8 allocation made solely to prepare a non-RGB8
/// image for GPU upload. Larger converted sources stay on the CPU's
/// destination-driven sampler instead of multiplying a compact bilevel or
/// grayscale source into a very large transient/cache allocation.
pub const MAX_PREPARED_RGB_CONVERSION_BYTES: usize = 64 * 1024 * 1024;
pub const MAX_PREPARED_OPACITY_CONVERSION_BYTES: usize = 64 * 1024 * 1024;
pub const MAX_PREPARED_PATTERNED_STENCIL_BYTES: usize = 64 * 1024 * 1024;

/// Source-texel footprint above which automatic routing keeps packed
/// bilevel images on the CPU. The CPU has a destination-driven popcount/box
/// filter for this minifying case, while preparing RGB8 would expand the
/// source and add upload work. Forced GPU routing deliberately ignores this
/// policy boundary.
pub const AUTO_CPU_BILEVEL_MINIFICATION_FOOTPRINT: f64 = 1.0;
const PREPARED_SOFT_MASK_CACHE_BYTES: usize = 64 * 1024 * 1024;
const PREPARED_PATTERNED_STENCIL_CACHE_BYTES: usize = 64 * 1024 * 1024;
const PREPARED_GPU_PAGE_CACHE_BYTES: usize = 64 * 1024 * 1024;
const GPU_PATH_BAND_HEIGHT: f32 = 16.0;
const GPU_PATH_SIMPLIFY_TOLERANCE: f32 = 0.1;
pub const GPU_PATH_BATCH_TILE_EDGE: u32 = 8;
const GPU_PATH_BATCH_MAX_TILE_DEPTH: usize = 64;
const GPU_PATH_BATCH_MAX_PATHS: usize = 4096;
const GPU_PATH_BATCH_MAX_COMPONENT_BYTES: usize = 64 * 1024 * 1024;

/// Default logical tile size (roadmap §7 Phase 4); revisit after benchmarks.
pub const DEFAULT_TILE_SIZE: u32 = 512;

fn point_segment_distance_squared(point: [f32; 2], a: [f32; 2], b: [f32; 2]) -> f32 {
    let ab = [b[0] - a[0], b[1] - a[1]];
    let ap = [point[0] - a[0], point[1] - a[1]];
    let denominator = ab[0] * ab[0] + ab[1] * ab[1];
    if denominator <= f32::EPSILON {
        return ap[0] * ap[0] + ap[1] * ap[1];
    }
    let t = ((ap[0] * ab[0] + ap[1] * ab[1]) / denominator).clamp(0.0, 1.0);
    let dx = point[0] - (a[0] + t * ab[0]);
    let dy = point[1] - (a[1] + t * ab[1]);
    dx * dx + dy * dy
}

fn mark_rdp_points(
    points: &[[f32; 2]],
    first: usize,
    last: usize,
    tolerance_squared: f32,
    keep: &mut [bool],
) {
    if last <= first + 1 {
        return;
    }
    let mut farthest = first;
    let mut farthest_distance = 0.0f32;
    for index in first + 1..last {
        let distance = point_segment_distance_squared(points[index], points[first], points[last]);
        if distance > farthest_distance {
            farthest = index;
            farthest_distance = distance;
        }
    }
    if farthest_distance <= tolerance_squared {
        return;
    }
    keep[farthest] = true;
    mark_rdp_points(points, first, farthest, tolerance_squared, keep);
    mark_rdp_points(points, farthest, last, tolerance_squared, keep);
}

fn simplify_open_gpu_polyline(points: &[[f32; 2]], tolerance: f32) -> Vec<[f32; 2]> {
    if points.len() <= 2 {
        return points.to_vec();
    }
    let mut keep = vec![false; points.len()];
    keep[0] = true;
    keep[points.len() - 1] = true;
    mark_rdp_points(
        points,
        0,
        points.len() - 1,
        tolerance * tolerance,
        &mut keep,
    );
    points
        .iter()
        .zip(keep)
        .filter_map(|(point, keep)| keep.then_some(*point))
        .collect()
}

/// Reduce the CPU flattener's deliberately conservative 16-segment curves to
/// device-relevant geometry before GPU upload. Splitting a closed contour at
/// two distant vertices avoids the degenerate identical-endpoint case while
/// retaining winding direction and holes.
fn simplify_closed_gpu_contour(points: &[[f32; 2]], tolerance: f32) -> Vec<[f32; 2]> {
    let mut contour = Vec::with_capacity(points.len());
    for &point in points {
        if contour.last().copied() != Some(point) {
            contour.push(point);
        }
    }
    if contour.len() > 1 && contour.first() == contour.last() {
        contour.pop();
    }
    if contour.len() <= 3 {
        return contour;
    }

    let first = contour[0];
    let mut split = 1usize;
    let mut farthest = 0.0f32;
    for (index, &point) in contour.iter().enumerate().skip(1) {
        let dx = point[0] - first[0];
        let dy = point[1] - first[1];
        let distance = dx * dx + dy * dy;
        if distance > farthest {
            split = index;
            farthest = distance;
        }
    }
    if split == 0 || split >= contour.len() {
        return contour;
    }

    let first_arc = simplify_open_gpu_polyline(&contour[..=split], tolerance);
    let mut second_source = Vec::with_capacity(contour.len() - split + 1);
    second_source.extend_from_slice(&contour[split..]);
    second_source.push(contour[0]);
    let second_arc = simplify_open_gpu_polyline(&second_source, tolerance);

    let mut simplified = first_arc;
    let second_interior = second_arc.len().saturating_sub(2);
    simplified.extend(second_arc.into_iter().skip(1).take(second_interior));
    if simplified.len() < 3 {
        contour
    } else {
        simplified
    }
}

fn pack_gpu_path_raster(
    bounds: crate::page_ir::DeviceRect,
    edges: &[[f32; 4]],
) -> Option<(Arc<[u32]>, u32)> {
    let edge_count = u32::try_from(edges.len()).ok()?;
    let band_count = bounds.height.div_ceil(GPU_PATH_BAND_HEIGHT as u32).max(1);
    let mut bands = vec![Vec::<u32>::new(); band_count as usize];
    let origin_y = bounds.y as f32;
    for (edge_index, edge) in edges.iter().enumerate() {
        let min_y = edge[1].min(edge[3]);
        let max_y = edge[1].max(edge[3]);
        if !min_y.is_finite() || !max_y.is_finite() || max_y <= min_y {
            continue;
        }
        let first = (((min_y - origin_y) / GPU_PATH_BAND_HEIGHT).floor() as i32)
            .clamp(0, band_count as i32 - 1);
        let last = ((((max_y - origin_y - 1.0e-4) / GPU_PATH_BAND_HEIGHT).floor()) as i32)
            .clamp(0, band_count as i32 - 1);
        for band in first..=last {
            bands[band as usize].push(edge_index as u32);
        }
    }

    let offsets_base = 4usize.checked_add(edges.len().checked_mul(4)?)?;
    let indices_base = offsets_base.checked_add(bands.len().checked_add(1)?)?;
    let reference_count: usize = bands.iter().map(Vec::len).sum();
    let total = indices_base.checked_add(reference_count)?;
    let mut data = Vec::with_capacity(total);
    data.extend_from_slice(&[
        edge_count,
        band_count,
        u32::try_from(offsets_base).ok()?,
        u32::try_from(indices_base).ok()?,
    ]);
    for edge in edges {
        data.extend(edge.iter().map(|value| value.to_bits()));
    }
    let mut offset = 0u32;
    data.push(offset);
    for band in &bands {
        offset = offset.checked_add(u32::try_from(band.len()).ok()?)?;
        data.push(offset);
    }
    for band in bands {
        data.extend(band);
    }
    Some((data.into(), u32::try_from(reference_count).ok()?))
}

fn gpu_path_tiles(size: DeviceSize, bounds: crate::page_ir::DeviceRect) -> Option<Vec<(u32, u32)>> {
    let page_width = i64::from(size.width);
    let page_height = i64::from(size.height);
    let x0 = i64::from(bounds.x).clamp(0, page_width);
    let y0 = i64::from(bounds.y).clamp(0, page_height);
    let x1 = (i64::from(bounds.x) + i64::from(bounds.width)).clamp(0, page_width);
    let y1 = (i64::from(bounds.y) + i64::from(bounds.height)).clamp(0, page_height);
    if x0 >= x1 || y0 >= y1 {
        return Some(Vec::new());
    }
    let first_x = u32::try_from(x0).ok()? / GPU_PATH_BATCH_TILE_EDGE;
    let first_y = u32::try_from(y0).ok()? / GPU_PATH_BATCH_TILE_EDGE;
    let last_x = u32::try_from(x1).ok()?.div_ceil(GPU_PATH_BATCH_TILE_EDGE);
    let last_y = u32::try_from(y1).ok()?.div_ceil(GPU_PATH_BATCH_TILE_EDGE);
    let count = usize::try_from(last_x.checked_sub(first_x)?)
        .ok()?
        .checked_mul(usize::try_from(last_y.checked_sub(first_y)?).ok()?)?;
    let mut tiles = Vec::with_capacity(count);
    for tile_y in first_y..last_y {
        for tile_x in first_x..last_x {
            tiles.push((
                tile_x * GPU_PATH_BATCH_TILE_EDGE,
                tile_y * GPU_PATH_BATCH_TILE_EDGE,
            ));
        }
    }
    Some(tiles)
}

type GpuPathMaskKey = (usize, usize);

fn gpu_path_new_masks(
    path: &PreparedGpuPath,
    existing: &HashSet<GpuPathMaskKey>,
) -> Option<(usize, Vec<GpuPathMaskKey>)> {
    let mut new_keys = Vec::with_capacity(2);
    let mut bytes = 0usize;
    for samples in [
        path.clip.as_ref().map(|clip| &clip.samples),
        path.soft_mask.as_ref().map(|mask| &mask.samples),
    ]
    .into_iter()
    .flatten()
    {
        let key = (samples.as_ptr() as usize, samples.len());
        if !existing.contains(&key) && !new_keys.contains(&key) {
            bytes = bytes.checked_add(samples.len())?;
            new_keys.push(key);
        }
    }
    Some((bytes, new_keys))
}

fn flush_gpu_path_batch(
    commands: &mut Vec<PreparedGpuCommand>,
    paths: &mut Vec<PreparedGpuPath>,
    tile_paths: &mut BTreeMap<(u32, u32), Vec<u32>>,
    mask_planes: &mut HashSet<GpuPathMaskKey>,
    geometry_bytes: &mut usize,
    mask_bytes: &mut usize,
) -> Option<()> {
    if paths.is_empty() {
        return Some(());
    }
    let mut tiles = Vec::with_capacity(tile_paths.len());
    let reference_count = tile_paths.values().map(Vec::len).sum();
    let mut indices = Vec::with_capacity(reference_count);
    let mut max_tile_depth = 0u32;
    for (&(x, y), path_indices) in tile_paths.iter() {
        let path_offset = u32::try_from(indices.len()).ok()?;
        let path_count = u32::try_from(path_indices.len()).ok()?;
        max_tile_depth = max_tile_depth.max(path_count);
        indices.extend_from_slice(path_indices);
        tiles.push(PreparedGpuPathTile {
            x,
            y,
            path_offset,
            path_count,
        });
    }
    commands.push(PreparedGpuCommand::PathBatch(Arc::new(
        PreparedGpuPathBatch {
            paths: std::mem::take(paths).into(),
            tiles: tiles.into(),
            tile_path_indices: indices.into(),
            geometry_bytes: *geometry_bytes,
            mask_bytes: *mask_bytes,
            max_tile_depth,
        },
    )));
    tile_paths.clear();
    mask_planes.clear();
    *geometry_bytes = 0;
    *mask_bytes = 0;
    Some(())
}

fn batch_gpu_path_commands(
    size: DeviceSize,
    source: Vec<PreparedGpuCommand>,
    cancellation: Option<&crate::render_api::CancellationToken>,
) -> Option<Vec<PreparedGpuCommand>> {
    let mut commands = Vec::with_capacity(source.len());
    let mut paths = Vec::new();
    let mut tile_paths = BTreeMap::<(u32, u32), Vec<u32>>::new();
    let mut mask_planes = HashSet::<GpuPathMaskKey>::new();
    let mut geometry_bytes = 0usize;
    let mut mask_bytes = 0usize;

    for command in source {
        if cancellation.is_some_and(crate::render_api::CancellationToken::is_cancelled) {
            return None;
        }
        let PreparedGpuCommand::Path(path) = command else {
            flush_gpu_path_batch(
                &mut commands,
                &mut paths,
                &mut tile_paths,
                &mut mask_planes,
                &mut geometry_bytes,
                &mut mask_bytes,
            )?;
            commands.push(command);
            continue;
        };

        let path_tiles = gpu_path_tiles(size, path.bounds)?;
        if path_tiles.is_empty() {
            continue;
        }
        let path_geometry_bytes = path
            .raster_data
            .len()
            .checked_mul(std::mem::size_of::<u32>())?;
        let (mut path_mask_bytes, mut path_mask_keys) = gpu_path_new_masks(&path, &mask_planes)?;
        let existing_refs: usize = tile_paths.values().map(Vec::len).sum();
        let new_tile_count = path_tiles
            .iter()
            .filter(|tile| !tile_paths.contains_key(tile))
            .count();
        let exceeds = paths.len() >= GPU_PATH_BATCH_MAX_PATHS
            || geometry_bytes
                .checked_add(path_geometry_bytes)
                .is_none_or(|bytes| bytes > GPU_PATH_BATCH_MAX_COMPONENT_BYTES)
            || mask_bytes
                .checked_add(path_mask_bytes)
                .is_none_or(|bytes| bytes > GPU_PATH_BATCH_MAX_COMPONENT_BYTES)
            || existing_refs
                .checked_add(path_tiles.len())
                .and_then(|refs| refs.checked_mul(std::mem::size_of::<u32>()))
                .is_none_or(|bytes| bytes > GPU_PATH_BATCH_MAX_COMPONENT_BYTES)
            || tile_paths
                .len()
                .checked_add(new_tile_count)
                .and_then(|tiles| tiles.checked_mul(std::mem::size_of::<PreparedGpuPathTile>()))
                .is_none_or(|bytes| bytes > GPU_PATH_BATCH_MAX_COMPONENT_BYTES)
            || path_tiles.iter().any(|tile| {
                tile_paths
                    .get(tile)
                    .is_some_and(|indices| indices.len() >= GPU_PATH_BATCH_MAX_TILE_DEPTH)
            });
        if exceeds && !paths.is_empty() {
            flush_gpu_path_batch(
                &mut commands,
                &mut paths,
                &mut tile_paths,
                &mut mask_planes,
                &mut geometry_bytes,
                &mut mask_bytes,
            )?;
            (path_mask_bytes, path_mask_keys) = gpu_path_new_masks(&path, &mask_planes)?;
        }

        if path_geometry_bytes > GPU_PATH_BATCH_MAX_COMPONENT_BYTES
            || path_mask_bytes > GPU_PATH_BATCH_MAX_COMPONENT_BYTES
            || path_tiles
                .len()
                .checked_mul(std::mem::size_of::<u32>())
                .is_none_or(|bytes| bytes > GPU_PATH_BATCH_MAX_COMPONENT_BYTES)
        {
            return None;
        }
        let path_index = u32::try_from(paths.len()).ok()?;
        for tile in path_tiles {
            tile_paths.entry(tile).or_default().push(path_index);
        }
        geometry_bytes = geometry_bytes.checked_add(path_geometry_bytes)?;
        mask_bytes = mask_bytes.checked_add(path_mask_bytes)?;
        mask_planes.extend(path_mask_keys);
        paths.push(path);
    }
    flush_gpu_path_batch(
        &mut commands,
        &mut paths,
        &mut tile_paths,
        &mut mask_planes,
        &mut geometry_bytes,
        &mut mask_bytes,
    )?;
    Some(commands)
}

fn prepare_external_clip(
    page: &CpuPreparedPage,
    clip_masks: &mut [Option<Option<PreparedImageClip>>],
    raster: &mut RasterKernel,
    clip: Option<u32>,
    has_mask: bool,
) -> Result<Option<PreparedImageClip>, RenderError> {
    if !has_mask {
        return Ok(None);
    }
    let Some(active_clip) = clip else {
        return Err(RenderError::Unsupported(PageFeatures::CLIPPING));
    };
    let source = page.clips[active_clip as usize]
        .mask_source
        .unwrap_or(active_clip);
    if clip_masks[source as usize].is_none() {
        let Some(mask) = build_clip_mask_cancellable(
            raster,
            ClipGeom::of(page),
            source,
            page.decode_limits.should_cancel.as_deref(),
        ) else {
            return Err(RenderError::Cancelled);
        };
        clip_masks[source as usize] = Some(if mask.all_opaque {
            None
        } else {
            Some(PreparedImageClip {
                bounds: mask.bounds,
                samples: Arc::from(mask.data),
            })
        });
    }
    Ok(clip_masks[source as usize].clone().flatten())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PreparedSoftMaskCacheKey {
    page_ptr: usize,
    output_width: u32,
    output_height: u32,
    max_page_bytes: u64,
    color_policy: crate::render_api::RenderColorPolicy,
    matrix: [u64; 6],
}

impl PreparedSoftMaskCacheKey {
    fn new(request: &RenderRequest) -> Self {
        let matrix = request.transform.matrix;
        Self {
            page_ptr: Arc::as_ptr(&request.page) as usize,
            output_width: request.output_size.width,
            output_height: request.output_size.height,
            max_page_bytes: request.limits.max_page_bytes,
            color_policy: request.color_policy,
            matrix: [
                matrix.a.to_bits(),
                matrix.b.to_bits(),
                matrix.c.to_bits(),
                matrix.d.to_bits(),
                matrix.e.to_bits(),
                matrix.f.to_bits(),
            ],
        }
    }
}

#[derive(Debug)]
struct PreparedSoftMaskCacheEntry {
    // Retaining the page makes `page_ptr` collision-free for this entry's
    // lifetime without hashing a complete compiled page.
    page: Arc<CompiledPage>,
    masks: Vec<Option<PreparedImageSoftMask>>,
    charge: usize,
    last_used: u64,
}

#[derive(Debug, Default)]
struct PreparedSoftMaskCacheState {
    entries: HashMap<PreparedSoftMaskCacheKey, PreparedSoftMaskCacheEntry>,
    resident_bytes: usize,
    clock: u64,
}

#[derive(Debug, Default)]
struct SharedPreparedSoftMaskCache {
    state: Mutex<PreparedSoftMaskCacheState>,
}

impl SharedPreparedSoftMaskCache {
    fn get(&self, request: &RenderRequest) -> Option<Vec<Option<PreparedImageSoftMask>>> {
        let key = PreparedSoftMaskCacheKey::new(request);
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        let entry = state.entries.get_mut(&key)?;
        if !Arc::ptr_eq(&entry.page, &request.page) {
            return None;
        }
        entry.last_used = clock;
        Some(entry.masks.clone())
    }

    fn insert(
        &self,
        request: &RenderRequest,
        masks: Vec<Option<PreparedImageSoftMask>>,
    ) -> Vec<Option<PreparedImageSoftMask>> {
        let key = PreparedSoftMaskCacheKey::new(request);
        let charge = masks
            .iter()
            .filter_map(Option::as_ref)
            .map(|mask| mask.samples.len())
            .sum();
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        if let Some(previous) = state.entries.insert(
            key,
            PreparedSoftMaskCacheEntry {
                page: Arc::clone(&request.page),
                masks: masks.clone(),
                charge,
                last_used: clock,
            },
        ) {
            state.resident_bytes = state.resident_bytes.saturating_sub(previous.charge);
        }
        state.resident_bytes = state.resident_bytes.saturating_add(charge);
        // Keep one oversized page for an immediate revisit, matching the GPU
        // upload cache policy, but otherwise stay within the session budget.
        while state.resident_bytes > PREPARED_SOFT_MASK_CACHE_BYTES && state.entries.len() > 1 {
            let Some(victim) = state
                .entries
                .iter()
                .min_by_key(|(_, entry)| entry.last_used)
                .map(|(key, _)| *key)
            else {
                break;
            };
            if let Some(removed) = state.entries.remove(&victim) {
                state.resident_bytes = state.resident_bytes.saturating_sub(removed.charge);
            }
        }
        masks
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PreparedPatternedStencilCacheKey {
    request: PreparedSoftMaskCacheKey,
    op_index: usize,
}

#[derive(Debug)]
struct PreparedPatternedStencilCacheEntry {
    page: Arc<CompiledPage>,
    prepared: PreparedPatternedStencil,
    charge: usize,
    last_used: u64,
}

#[derive(Debug, Default)]
struct PreparedPatternedStencilCacheState {
    entries: HashMap<PreparedPatternedStencilCacheKey, PreparedPatternedStencilCacheEntry>,
    resident_bytes: usize,
    clock: u64,
}

#[derive(Debug, Default)]
struct SharedPreparedPatternedStencilCache {
    state: Mutex<PreparedPatternedStencilCacheState>,
}

impl SharedPreparedPatternedStencilCache {
    fn get(&self, request: &RenderRequest, op_index: usize) -> Option<PreparedPatternedStencil> {
        let key = PreparedPatternedStencilCacheKey {
            request: PreparedSoftMaskCacheKey::new(request),
            op_index,
        };
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        let entry = state.entries.get_mut(&key)?;
        if !Arc::ptr_eq(&entry.page, &request.page) {
            return None;
        }
        entry.last_used = clock;
        Some(entry.prepared.clone())
    }

    fn insert(
        &self,
        request: &RenderRequest,
        op_index: usize,
        prepared: PreparedPatternedStencil,
    ) -> PreparedPatternedStencil {
        let key = PreparedPatternedStencilCacheKey {
            request: PreparedSoftMaskCacheKey::new(request),
            op_index,
        };
        let charge = prepared
            .samples
            .len()
            .saturating_add(prepared.opacity.len());
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        if let Some(previous) = state.entries.insert(
            key,
            PreparedPatternedStencilCacheEntry {
                page: Arc::clone(&request.page),
                prepared: prepared.clone(),
                charge,
                last_used: clock,
            },
        ) {
            state.resident_bytes = state.resident_bytes.saturating_sub(previous.charge);
        }
        state.resident_bytes = state.resident_bytes.saturating_add(charge);
        while state.resident_bytes > PREPARED_PATTERNED_STENCIL_CACHE_BYTES
            && state.entries.len() > 1
        {
            let Some(victim) = state
                .entries
                .iter()
                .min_by_key(|(_, entry)| entry.last_used)
                .map(|(key, _)| *key)
            else {
                break;
            };
            if let Some(removed) = state.entries.remove(&victim) {
                state.resident_bytes = state.resident_bytes.saturating_sub(removed.charge);
            }
        }
        prepared
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct PreparedGpuPageCacheKey {
    request: PreparedSoftMaskCacheKey,
    automatic_routing: bool,
}

#[derive(Debug)]
struct PreparedGpuPageCacheEntry {
    page: Arc<CompiledPage>,
    prepared: PreparedRgbImagePage,
    charge: usize,
    last_used: u64,
}

#[derive(Debug, Default)]
struct PreparedGpuPageCacheState {
    entries: HashMap<PreparedGpuPageCacheKey, PreparedGpuPageCacheEntry>,
    resident_bytes: usize,
    clock: u64,
}

#[derive(Debug, Default)]
struct SharedPreparedGpuPageCache {
    state: Mutex<PreparedGpuPageCacheState>,
}

impl SharedPreparedGpuPageCache {
    fn get(
        &self,
        request: &RenderRequest,
        automatic_routing: bool,
    ) -> Option<PreparedRgbImagePage> {
        let key = PreparedGpuPageCacheKey {
            request: PreparedSoftMaskCacheKey::new(request),
            automatic_routing,
        };
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        let entry = state.entries.get_mut(&key)?;
        if !Arc::ptr_eq(&entry.page, &request.page) {
            return None;
        }
        entry.last_used = clock;
        Some(entry.prepared.clone())
    }

    fn insert(
        &self,
        request: &RenderRequest,
        automatic_routing: bool,
        prepared: PreparedRgbImagePage,
    ) -> PreparedRgbImagePage {
        let key = PreparedGpuPageCacheKey {
            request: PreparedSoftMaskCacheKey::new(request),
            automatic_routing,
        };
        let image_bytes = prepared.images.iter().fold(0usize, |total, image| {
            total
                .saturating_add(image.samples.len())
                .saturating_add(
                    image
                        .opacity
                        .as_ref()
                        .map_or(0, |opacity| opacity.samples.len()),
                )
                .saturating_add(image.clip.as_ref().map_or(0, |clip| clip.samples.len()))
                .saturating_add(
                    image
                        .soft_mask
                        .as_ref()
                        .map_or(0, |mask| mask.samples.len()),
                )
        });
        let path_bytes = prepared
            .commands
            .iter()
            .fold(0usize, |total, command| match command {
                PreparedGpuCommand::Path(path) => total
                    .saturating_add(
                        path.raster_data
                            .len()
                            .saturating_mul(std::mem::size_of::<u32>()),
                    )
                    .saturating_add(path.clip.as_ref().map_or(0, |clip| clip.samples.len()))
                    .saturating_add(path.soft_mask.as_ref().map_or(0, |mask| mask.samples.len())),
                PreparedGpuCommand::PathBatch(batch) => total
                    .saturating_add(batch.geometry_bytes)
                    .saturating_add(batch.mask_bytes)
                    .saturating_add(
                        batch
                            .tiles
                            .len()
                            .saturating_mul(std::mem::size_of::<PreparedGpuPathTile>()),
                    )
                    .saturating_add(
                        batch
                            .tile_path_indices
                            .len()
                            .saturating_mul(std::mem::size_of::<u32>()),
                    ),
                PreparedGpuCommand::Image(_) => total,
            });
        let charge = image_bytes.saturating_add(path_bytes);
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        state.clock = state.clock.wrapping_add(1);
        let clock = state.clock;
        if let Some(previous) = state.entries.insert(
            key,
            PreparedGpuPageCacheEntry {
                page: Arc::clone(&request.page),
                prepared: prepared.clone(),
                charge,
                last_used: clock,
            },
        ) {
            state.resident_bytes = state.resident_bytes.saturating_sub(previous.charge);
        }
        state.resident_bytes = state.resident_bytes.saturating_add(charge);
        while state.resident_bytes > PREPARED_GPU_PAGE_CACHE_BYTES && state.entries.len() > 1 {
            let Some(victim) = state
                .entries
                .iter()
                .min_by_key(|(_, entry)| entry.last_used)
                .map(|(key, _)| *key)
            else {
                break;
            };
            if let Some(removed) = state.entries.remove(&victim) {
                state.resident_bytes = state.resident_bytes.saturating_sub(removed.charge);
            }
        }
        prepared
    }
}

/// Scale an oversized render down uniformly so its RGBA8 surface fits
/// `max_bytes`, adjusting the page transform to match so content still fills
/// the (now smaller) device box.
///
/// A poster-sized MediaBox — e.g. a 9600×14400 pt foldout rendered at screen
/// DPI — would otherwise demand a multi-GB surface and fail the page outright.
/// Real viewers cap effective DPI for such pages; clamping does the same,
/// preserving the whole page at lower resolution instead of dropping it. The
/// downscale is uniform (aspect preserved); the exact per-axis ratios are
/// folded into the transform so the mapping stays consistent after flooring.
///
/// Returns the (possibly reduced) size, the adjusted matrix, and whether a
/// clamp occurred. A `max_bytes` of 0 disables clamping (no budget).
fn clamp_output_to_budget(
    size: DeviceSize,
    matrix: Matrix,
    max_bytes: u64,
) -> (DeviceSize, Matrix, bool) {
    let surface_bytes = (size.width as u64)
        .saturating_mul(size.height as u64)
        .saturating_mul(4);
    if max_bytes == 0 || surface_bytes <= max_bytes {
        return (size, matrix, false);
    }
    // Uniform factor k with (w·k)·(h·k)·4 == max_bytes. Flooring only ever
    // shrinks the result, so the clamped surface is guaranteed ≤ max_bytes.
    let k = ((max_bytes as f64) / (surface_bytes as f64)).sqrt();
    let new_w = ((size.width as f64 * k).floor() as u32).max(1);
    let new_h = ((size.height as f64 * k).floor() as u32).max(1);
    let kx = new_w as f64 / size.width as f64;
    let ky = new_h as f64 / size.height as f64;
    let adjusted = matrix.then(Matrix::scale(kx, ky));
    (
        DeviceSize {
            width: new_w,
            height: new_h,
        },
        adjusted,
        true,
    )
}

/// A page rendered by [`CpuBackend::render_rgb_with_options`] or
/// [`CpuBackend::render_packed_rgb_with_options`]: 8-bit RGB, three bytes per
/// pixel, rows top to bottom.
#[derive(Debug, Clone)]
pub struct PackedRgbPage {
    pub width: u32,
    pub height: u32,
    /// Bytes from one row to the next: `width * 3`.
    pub stride: usize,
    /// The pixels are the first `stride * height` bytes. From
    /// `render_rgb_with_options` that is the whole buffer. From
    /// `render_packed_rgb_with_options` the buffer may be the surface the
    /// page was rendered on, which is a third longer; the rest is
    /// unspecified.
    pub pixels: std::sync::Arc<[u8]>,
}

/// What a render hands back.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum OutputTarget {
    /// The request's own format: the RGBA surface itself, or Gray8.
    Request,
    /// RGB packed inside the RGBA surface it was rendered on.
    PackedRgb,
    /// RGB in a buffer of exactly `width * height * 3` bytes.
    ExactRgb,
}

/// The strip size a backend aims for by default: see
/// [`CpuBackend::with_strip_target_bytes`].
const STRIP_TARGET_BYTES: usize = 32 * 1024 * 1024;

/// No strip is shorter than this many rows, however wide the page.
const MIN_STRIP_ROWS: u64 = 256;

/// Per-request CPU rendering policy beyond the backend-neutral
/// [`RenderRequest`]; see [`CpuBackend::render_with_options`]. The default is
/// what [`CpuBackend::render_with`] does.
#[derive(Debug, Clone, Copy, Default)]
pub struct CpuRenderOptions {
    /// Decode every image at no less than the resolution its footprint under
    /// this transform selects: a page transform onto another raster of the
    /// same page, such as the main output a caller also renders smaller
    /// products alongside.
    ///
    /// Scaling codecs (DCT, JPX) decode a minified draw at a reduced
    /// resolution chosen from its footprint, so products of one page at
    /// different sizes would decode its images once per size. Products that
    /// share a reference decode each image once, at the reference's
    /// resolution, and draws larger than the reference keep their own. The
    /// decoded resolution follows from the request alone, so pixels do not
    /// depend on which product rendered first or on the decoded-image cache.
    ///
    /// `None`: each image decodes for its own footprint.
    pub image_decode_reference: Option<crate::render_api::PageTransform>,
}

/// CPU backend configuration.
#[derive(Debug, Clone)]
pub struct CpuBackendOptions {
    /// Rayon threads for intra-backend parallelism; `None` = rayon default.
    /// Page-level parallelism is the scheduler's job, so this mostly
    /// matters for tile parallelism inside very large single pages.
    pub threads: Option<usize>,
    pub tile_size: u32,
    /// The injected image-codec registry (codec.rs: never global). The
    /// default deployment bundles JPEG (in-house), JPEG 2000 (jp2lam), and
    /// JBIG2 (temporary, see `crate::image::jbig2`); pass
    /// [`crate::image::CodecRegistry::empty()`] for a codec-free build.
    pub codecs: crate::image::CodecRegistry,
    /// Glyph grid-fitting (fonts.md Font Phase 4).
    ///
    /// Defaults to [`HintingPolicy::None`](crate::font::HintingPolicy::None): this backend is the *normative*
    /// implementation of the frozen surface contract, and hinting moves glyph
    /// geometry, so it is opt-in rather than a silent default. A screen-facing
    /// caller wanting crisp small text sets [`HintingPolicy::Auto`](crate::font::HintingPolicy::Auto), which
    /// hints only where it pays (axis-aligned, at or below
    /// `crate::font::AUTO_HINT_MAX_PPEM`).
    pub hinting: crate::font::HintingPolicy,
}

impl Default for CpuBackendOptions {
    fn default() -> Self {
        let codecs = crate::image::CodecRegistry::new([
            std::sync::Arc::new(crate::image::JpegCodec)
                as std::sync::Arc<dyn crate::image::ImageCodec>,
            std::sync::Arc::new(crate::image::JpxCodec),
            std::sync::Arc::new(crate::image::Jbig2Codec::default()),
            std::sync::Arc::new(crate::image::CcittCodec),
        ]);
        Self {
            threads: None,
            tile_size: DEFAULT_TILE_SIZE,
            codecs,
            hinting: crate::font::HintingPolicy::None,
        }
    }
}

/// The CPU render backend.
#[derive(Debug)]
pub struct CpuBackend {
    options: CpuBackendOptions,
    job_counter: AtomicU64,
    /// Document/render-session-scoped parsed-font cache, shared by every worker
    /// that renders through this backend. One backend is created per document
    /// render (the scheduler owns it for the page range), so its lifetime scopes
    /// the cache to that document. See [`prepared::SharedFontProgramCache`].
    shared_fonts: Arc<prepared::SharedFontProgramCache>,
    /// Document/render-session-scoped rendered-glyph coverage cache (PDFium
    /// `CFX_GlyphCache` analog), shared by every worker. Scoped like
    /// `shared_fonts`. See [`prepared::SharedGlyphCache`].
    shared_glyphs: Arc<prepared::SharedGlyphCache>,
    /// Document/render-session-scoped decoded-image cache, shared by every
    /// worker. Scoped like `shared_fonts`. See [`prepared::SharedImageCache`].
    shared_images: Arc<prepared::SharedImageCache>,
    /// Document/render-session-scoped RGB8 conversion cache for the
    /// experimental GPU preparation seam. Stable Arc identity lets the GPU
    /// upload cache serve subsequent tiles without converting or uploading
    /// the same source again.
    shared_rgb_images: Arc<image::SharedRgbImageCache>,
    /// Normalized image `/SMask` and stencil coverage planes. Kept separate
    /// from RGB conversions so packed 1-bit masks remain compact until a GPU
    /// request actually needs an upload-ready alpha plane.
    shared_opacity_images: Arc<image::SharedOpacityImageCache>,
    /// Device-space page `/SMask` planes derived through the CPU executor for
    /// the GPU image seam. Stable sample Arcs preserve warm GPU uploads.
    shared_prepared_soft_masks: Arc<SharedPreparedSoftMaskCache>,
    /// Bounded device-space pattern brushes for patterned `/ImageMask` draws.
    /// Stable RGB/alpha Arcs feed the existing GPU upload cache on revisits.
    shared_prepared_patterned_stencils: Arc<SharedPreparedPatternedStencilCache>,
    /// Complete external-raster command pages. Besides removing repeated
    /// outline lowering, stable path/clip Arcs let the WGPU upload caches reuse
    /// immutable device buffers on page revisits.
    shared_prepared_gpu_pages: Arc<SharedPreparedGpuPageCache>,
    /// Page buffers of finished renders through a caller-owned worker context
    /// ([`Self::render_with`]), kept for the next render of the same size and
    /// released with the backend. See [`surface::SurfacePool`].
    surfaces: surface::SurfacePool,
    /// RGBA bytes per strip for pages rendered in strips; 0 never strips.
    strip_target_bytes: usize,
}

impl CpuBackend {
    pub fn new(options: CpuBackendOptions) -> Self {
        Self {
            options,
            job_counter: AtomicU64::new(0),
            shared_fonts: Arc::new(prepared::SharedFontProgramCache::default()),
            shared_glyphs: Arc::new(prepared::SharedGlyphCache::default()),
            shared_images: Arc::new(prepared::SharedImageCache::default()),
            shared_rgb_images: Arc::new(image::SharedRgbImageCache::default()),
            shared_opacity_images: Arc::new(image::SharedOpacityImageCache::default()),
            shared_prepared_soft_masks: Arc::new(SharedPreparedSoftMaskCache::default()),
            shared_prepared_patterned_stencils: Arc::new(
                SharedPreparedPatternedStencilCache::default(),
            ),
            shared_prepared_gpu_pages: Arc::new(SharedPreparedGpuPageCache::default()),
            surfaces: surface::SurfacePool::new(surface::SURFACE_POOL_BYTES),
            strip_target_bytes: default_strip_target_bytes(),
        }
    }

    /// Set the size of the strips large pages are rendered in (32 MiB of
    /// RGBA by default; 0 renders every page in one pass).
    ///
    /// A page whose output is not the RGBA surface itself (Gray8, RGB) needs
    /// that surface only as a working plane. When the surface would be more
    /// than twice this size the page is rendered as horizontal strips of at
    /// most this size, each converted straight into the output buffer, so the
    /// render holds the output plus one strip instead of the output plus the
    /// whole surface (five to seven bytes per pixel). Group and soft-mask
    /// intermediates shrink to the strip with it.
    ///
    /// An RGBA page of that size is rendered in strips, each copied into the
    /// page, only when its group and soft-mask intermediates would themselves
    /// exceed twice this size: then the render holds the page, one strip and
    /// strip-sized intermediates instead of the page and page-sized ones.
    ///
    /// The pixels are the same either way; strips cost render time, more on
    /// pages whose shapes cross many strip boundaries.
    pub fn with_strip_target_bytes(mut self, bytes: usize) -> Self {
        self.strip_target_bytes = bytes;
        self
    }

    /// Rows per strip for this render, or `None` for one pass: what
    /// [`strip_rows_override`] forces, else [`Self::auto_strip_rows`] when
    /// strips pay. The one place the choice is made, for the render and for
    /// the scheduler's estimate of it. `matrix` and the size are the ones the
    /// render uses, after any clamp to the page budget.
    ///
    /// Strips always pay for an output converted from the surface (Gray8,
    /// RGB): the whole surface is then never needed. An RGBA page is its own
    /// surface, so strips add a strip buffer and a copy; they pay only when
    /// they shrink the page's group and soft-mask offscreens by more than
    /// that, which is taken to be when those would exceed twice the strip
    /// target at page size. Tiling fills are not counted: a fill keeps its
    /// whole bounds in a strip.
    fn strip_rows_for(
        &self,
        rgba_out: bool,
        complexity: &crate::page_ir::PageComplexity,
        matrix: &Matrix,
        width: u32,
        height: u32,
    ) -> Option<u32> {
        strip_rows_override()
            .or_else(|| {
                let pays = !rgba_out || {
                    let surface = u64::from(width) * 4 * u64::from(height);
                    complexity.offscreen_bytes(matrix, surface)
                        > (self.strip_target_bytes as u64).saturating_mul(2)
                };
                pays.then(|| self.auto_strip_rows(width, height)).flatten()
            })
            .filter(|&rows| rows < height)
    }

    /// Rows per strip for a page of this size, or `None` to render it in one
    /// pass. A function of the size alone, so the choice never depends on
    /// thread count or cache state.
    fn auto_strip_rows(&self, width: u32, height: u32) -> Option<u32> {
        let target = self.strip_target_bytes as u64;
        if target == 0 {
            return None;
        }
        let surface = u64::from(width) * 4 * u64::from(height);
        if surface <= target.saturating_mul(2) {
            return None;
        }
        let strips = surface.div_ceil(target);
        let rows = u64::from(height).div_ceil(strips).max(MIN_STRIP_ROWS);
        (rows < u64::from(height)).then_some(rows as u32)
    }

    /// Cap the bytes of finished page buffers this backend keeps for reuse
    /// (256 MiB by default; 0 keeps none). A render whose buffer does not fit
    /// allocates and frees its surface, which costs time, never output.
    pub fn with_surface_pool_bytes(mut self, bytes: usize) -> Self {
        self.surfaces = surface::SurfacePool::new(bytes);
        self
    }

    /// Set the byte budgets of the decoded-image, parsed-font and glyph
    /// caches (96, 48 and 32 MiB by default). Every backend has its own
    /// caches, so a host with many documents open divides its allowance among
    /// them here. A smaller cache costs repeated decoding and rasterizing,
    /// never output. Call before rendering: the caches start empty.
    pub fn with_cache_bytes(mut self, images: usize, fonts: usize, glyphs: usize) -> Self {
        self.shared_images = Arc::new(prepared::SharedImageCache::new(images));
        self.shared_fonts = Arc::new(prepared::SharedFontProgramCache::new(fonts));
        self.shared_glyphs = Arc::new(prepared::SharedGlyphCache::new(glyphs));
        self
    }

    /// Drop everything the decoded-image, parsed-font and glyph caches hold.
    /// Renders in progress keep what they are using; later ones decode,
    /// parse and rasterize again, to the same bytes.
    pub fn clear_resource_caches(&self) {
        self.shared_images.clear();
        self.shared_fonts.clear();
        self.shared_glyphs.clear();
    }

    /// Bytes the decoded-image cache currently retains.
    pub fn image_cache_bytes(&self) -> usize {
        self.shared_images.retained_bytes()
    }

    /// Drop the page buffers kept for reuse. They are otherwise held until
    /// the backend is dropped; a long-lived idle session can call this to
    /// give the memory back. The next render allocates a fresh surface.
    pub fn release_idle_memory(&self) {
        self.surfaces.clear();
    }

    /// Bytes of page buffers this backend currently keeps alive for reuse.
    pub fn idle_surface_bytes(&self) -> usize {
        self.surfaces.idle_bytes()
    }

    /// Decode a codec-retained one-bit JBIG2 image `/SMask` without rendering
    /// its base image. The PDF `/Decode` polarity is applied while expanding
    /// the packed samples, yielding a native-grid opacity plane. Unsupported
    /// or malformed inputs decline with `Ok(None)` so document processing can
    /// use its ordinary per-page fallback; cancellation remains an error.
    pub fn decode_bilevel_jbig2_smask(
        &self,
        smask: &crate::page_ir::ImageSMask,
        limits: &RenderLimits,
    ) -> Result<Option<DecodedBilevelSmask>, RenderError> {
        use crate::image::{
            DecodeParameters, DecodedFormat, ImageDescriptor, ImageError, StreamFilter,
        };

        if limits
            .cancellation
            .as_ref()
            .is_some_and(|token| token.is_cancelled())
        {
            return Err(RenderError::Cancelled);
        }
        if smask.bits_per_component != 1
            || smask.codec != Some(crate::page_ir::ImageCodecKind::Jbig2)
            || smask.width == 0
            || smask.height == 0
        {
            return Ok(None);
        }
        let Some(data) = smask.codec_data.as_deref().filter(|data| !data.is_empty()) else {
            return Ok(None);
        };
        let decode_inverted = match smask.decode.as_deref() {
            None => false,
            Some([[lo, hi]]) if *lo == 0.0 && *hi == 1.0 => false,
            Some([[lo, hi]]) if *lo == 1.0 && *hi == 0.0 => true,
            _ => return Ok(None),
        };
        let Some(codec) = self.options.codecs.get(StreamFilter::Jbig2) else {
            return Ok(None);
        };
        let decode_limits = image_decode_limits(limits);
        let descriptor = ImageDescriptor {
            width: smask.width,
            height: smask.height,
            bits_per_component: 1,
            color_space: Some(crate::color::ColorSpaceDesc {
                family: crate::color::ColorSpaceFamily::DeviceGray,
                components: 1,
                object: None,
            }),
            is_mask: true,
            interpolate: false,
            filters: vec![StreamFilter::Jbig2],
            object: None,
        };
        let params = DecodeParameters {
            jbig2_globals: smask
                .codec_parms
                .as_ref()
                .and_then(|parms| parms.jbig2_globals.clone()),
            ..DecodeParameters::default()
        };
        let decoded = match codec.decode(data, &descriptor, &params, &decode_limits) {
            Ok(decoded) => decoded,
            Err(ImageError::Cancelled) => return Err(RenderError::Cancelled),
            Err(_) => return Ok(None),
        };
        if decoded.format != DecodedFormat::Mono1
            || decoded.validate(&decode_limits).is_err()
            || decoded.width != smask.width
            || decoded.height != smask.height
        {
            return Ok(None);
        }

        let width = decoded.width as usize;
        let height = decoded.height as usize;
        let Some(len) = width.checked_mul(height) else {
            return Ok(None);
        };
        if len as u64 > decode_limits.max_output_bytes {
            return Ok(None);
        }
        let mut opacity = surface::zeroed_arc(len);
        let opacity_data = surface::unique_arc_mut(&mut opacity);
        for y in 0..height {
            if y & 0xff == 0 && decode_limits.is_cancelled() {
                return Err(RenderError::Cancelled);
            }
            let row = &decoded.data[y * decoded.stride..y * decoded.stride + width.div_ceil(8)];
            for x in 0..width {
                let sample_is_one = row[x / 8] & (0x80 >> (x & 7)) != 0;
                let opaque = sample_is_one ^ decode_inverted;
                opacity_data[y * width + x] = if opaque { 255 } else { 0 };
            }
        }
        Ok(Some(DecodedBilevelSmask {
            width: decoded.width,
            height: decoded.height,
            stride: width,
            opacity,
        }))
    }

    /// Features the rasterizer implements today. Grows phase by phase; the
    /// scheduler routes pages by comparing this to `page.features`.
    ///
    /// Solid paths + constant alpha + clipping (rect and path). Alpha needs no
    /// feature flag; `TRANSPARENCY` denotes non-Normal blend / groups, not yet
    /// implemented.
    fn implemented_features() -> PageFeatures {
        PageFeatures::BASIC_PATHS
            | PageFeatures::CLIPPING
            | PageFeatures::DASHED_STROKES
            | PageFeatures::NONSEPARABLE_BLENDS
            | PageFeatures::TRANSPARENCY
            // Text renders as synthetic placement boxes (fonts.md Font Phase 1);
            // real glyph outlines are a later font phase.
            | PageFeatures::TEXT
            // Axial + radial shadings (`sh` and shading patterns).
            | PageFeatures::SHADINGS
            // Tiling patterns (PatternType 1) + shading patterns.
            | PageFeatures::PATTERNS
            // Images with Flate/RunLength/raw data (codec images route away
            // via the NEEDS_* flags, which stay outside this set).
            | PageFeatures::IMAGES
            | PageFeatures::STENCIL_MASKS
    }

    /// The full advertised feature set: the rasterizer's static
    /// capabilities plus `NEEDS_*` codec coverage from the injected
    /// registry (an empty registry advertises no codecs and codec pages
    /// keep routing away, exactly as before).
    pub fn features(&self) -> PageFeatures {
        Self::implemented_features() | crate::image::registry_features(&self.options.codecs)
    }

    /// Render into host memory, returning instrumentation. This is the direct
    /// entry point benchmarks and tests use; `submit` wraps it.
    pub fn render_to_host(
        &self,
        request: &RenderRequest,
    ) -> Result<(HostPage, RenderStats), RenderError> {
        // One-shot: the scheduler's path and the benchmarks'. Nothing is
        // taken from or parked in the surface pool, as nothing outlived this
        // call when buffers were parked in the (fresh) worker context.
        let mut ctx = CpuWorkerContext::new();
        self.render_impl(
            request,
            &CpuRenderOptions::default(),
            &mut ctx,
            false,
            OutputTarget::Request,
        )
    }

    /// Lower a request into the exact prepared representation consumed by the
    /// diagnostic attribution pass. Production painting should continue to
    /// use [`Self::render_to_host`]; this intentionally exposes preparation
    /// only for non-normative renderer diagnostics.
    pub fn prepare_attribution(
        &self,
        request: &RenderRequest,
    ) -> Result<CpuPreparedPage, RenderError> {
        self.prepare_page_for_external_raster(request, true)
    }

    /// Lower for a non-CPU raster backend. Disabling the rendered-glyph cache
    /// deliberately keeps glyphs as flattened outline paths, allowing the GPU
    /// to generate their coverage instead of uploading CPU-rasterized bitmaps.
    fn prepare_page_for_external_raster(
        &self,
        request: &RenderRequest,
        use_rendered_glyph_cache: bool,
    ) -> Result<CpuPreparedPage, RenderError> {
        if let Some(token) = &request.limits.cancellation
            && token.is_cancelled()
        {
            return Err(RenderError::Cancelled);
        }
        let DeviceSize { width, height } = request.output_size;
        if width == 0 || height == 0 {
            return Err(RenderError::LimitExceeded("zero output dimension"));
        }
        let surface_bytes = (width as usize)
            .checked_mul(height as usize)
            .and_then(|pixels| pixels.checked_mul(4))
            .ok_or(RenderError::LimitExceeded("output size overflow"))?;
        if surface_bytes as u64 > request.limits.max_page_bytes {
            return Err(RenderError::LimitExceeded("max_page_bytes"));
        }
        let decode_limits = image_decode_limits(&request.limits);
        let mut worker = CpuWorkerContext::new();
        let shared_fonts = shared_font_cache_enabled().then_some(self.shared_fonts.as_ref());
        let shared_images = image_cache_enabled().then_some(&self.shared_images);
        let prepared = if use_rendered_glyph_cache {
            prepared::lower_with_font_cache(
                &request.page,
                request.transform.matrix,
                request.output_size,
                &self.options.codecs,
                &decode_limits,
                self.options.hinting,
                request.color_policy,
                &mut worker.fonts,
                shared_fonts,
                glyph_cache_enabled().then_some(self.shared_glyphs.as_ref()),
                shared_images,
                None,
                None,
            )
        } else {
            prepared::lower_for_external_raster(
                &request.page,
                request.transform.matrix,
                request.output_size,
                &self.options.codecs,
                &decode_limits,
                self.options.hinting,
                request.color_policy,
                &mut worker.fonts,
                shared_fonts,
                shared_images,
            )
        };
        if request
            .limits
            .cancellation
            .as_ref()
            .is_some_and(|token| token.is_cancelled())
        {
            return Err(RenderError::Cancelled);
        }
        Ok(prepared)
    }

    /// Decode and lower an image-only request into the narrow RGB8 + optional
    /// alpha8 vocabulary consumed by the experimental GPU renderer.
    /// Color-space, `/Decode`, image `/SMask`, explicit hard `/Mask`, and solid
    /// stencil semantics are resolved here through the CPU renderer's
    /// normative preparation path.
    ///
    /// `Ok(None)` is a normal capability decline: the page contains another
    /// paint operation or an image requiring text clipping. The caller should
    /// route that request to the regular CPU renderer.
    pub fn prepare_rgb_image_page(
        &self,
        request: &RenderRequest,
    ) -> Result<Option<PreparedRgbImagePage>, RenderError> {
        self.prepare_rgb_image_page_with_policy(request, false)
    }

    /// Prepare an image-only request using the measured automatic routing
    /// policy. Minified 1-bit images decline before RGB expansion so the
    /// caller can use the CPU's packed-bilevel destination sampler.
    pub fn prepare_rgb_image_page_for_auto(
        &self,
        request: &RenderRequest,
    ) -> Result<Option<PreparedRgbImagePage>, RenderError> {
        self.prepare_rgb_image_page_with_policy(request, true)
    }

    fn prepare_rgb_image_page_with_policy(
        &self,
        request: &RenderRequest,
        automatic_routing: bool,
    ) -> Result<Option<PreparedRgbImagePage>, RenderError> {
        if request
            .limits
            .cancellation
            .as_ref()
            .is_some_and(|token| token.is_cancelled())
        {
            return Err(RenderError::Cancelled);
        }
        if let Some(prepared) = self
            .shared_prepared_gpu_pages
            .get(request, automatic_routing)
        {
            return Ok(Some(prepared));
        }
        let prepared = self.prepare_page_for_external_raster(request, false)?;
        let mut images = Vec::with_capacity(prepared.ops.len());
        let mut commands = Vec::with_capacity(prepared.ops.len());
        let mut clip_masks: Vec<Option<Option<PreparedImageClip>>> =
            vec![None; prepared.clips.len()];
        let mut clip_raster = RasterKernel::default();
        let has_soft_masks = prepared
            .ops
            .iter()
            .any(|op| matches!(op, prepared::PreparedOp::PushSoftMask { .. }));
        let mut derived_soft_masks = if has_soft_masks {
            if let Some(masks) = self.shared_prepared_soft_masks.get(request) {
                masks
            } else {
                let Some(masks) = exec::prepare_soft_masks(&prepared) else {
                    return Err(RenderError::Cancelled);
                };
                let masks = masks
                    .into_iter()
                    .map(|mask| {
                        mask.map(|mask| PreparedImageSoftMask {
                            bounds: mask.bounds,
                            samples: Arc::from(mask.data),
                            outside: mask.outside,
                        })
                    })
                    .collect();
                self.shared_prepared_soft_masks.insert(request, masks)
            }
        } else {
            std::iter::repeat_with(|| None)
                .take(prepared.ops.len())
                .collect()
        };
        let mut active_soft_masks: Vec<Option<PreparedImageSoftMask>> = Vec::new();
        let has_native_image_draw = {
            let mut scan = 0;
            let mut found = false;
            while scan < prepared.ops.len() {
                match &prepared.ops[scan] {
                    prepared::PreparedOp::Image(_) => {
                        found = true;
                        break;
                    }
                    prepared::PreparedOp::PushSoftMask { content_end, .. } => {
                        scan = *content_end as usize;
                    }
                    _ => scan += 1,
                }
            }
            found
        };

        let mut op_index = 0;
        while op_index < prepared.ops.len() {
            let op = &prepared.ops[op_index];
            let image = match op {
                prepared::PreparedOp::Image(image) => image,
                prepared::PreparedOp::Draw(command) => {
                    if command.alpha == 0 {
                        op_index += 1;
                        continue;
                    }
                    if command.shading.is_some() {
                        return Ok(None);
                    }
                    let mut edges = Vec::new();
                    for &(start, end) in &prepared.subpaths
                        [command.subpath_range.0 as usize..command.subpath_range.1 as usize]
                    {
                        let points = &prepared.points[start..end];
                        if points.len() < 2 {
                            continue;
                        }
                        let simplified =
                            simplify_closed_gpu_contour(points, GPU_PATH_SIMPLIFY_TOLERANCE);
                        for pair in simplified.windows(2) {
                            edges.push([pair[0][0], pair[0][1], pair[1][0], pair[1][1]]);
                        }
                        let first = simplified[0];
                        let last = simplified[simplified.len() - 1];
                        if first != last {
                            edges.push([last[0], last[1], first[0], first[1]]);
                        }
                    }
                    if edges.is_empty() {
                        op_index += 1;
                        continue;
                    }
                    let Some((raster_data, band_edge_references)) =
                        pack_gpu_path_raster(command.bounds, &edges)
                    else {
                        return Ok(None);
                    };
                    let clip = prepare_external_clip(
                        &prepared,
                        &mut clip_masks,
                        &mut clip_raster,
                        command.clip,
                        command.clip_has_mask,
                    )?;
                    commands.push(PreparedGpuCommand::Path(PreparedGpuPath {
                        bounds: command.bounds,
                        raster_data,
                        edge_count: edges.len() as u32,
                        band_edge_references,
                        even_odd: matches!(command.rule, raster::FillRule::EvenOdd),
                        rgb: command.rgb,
                        alpha: command.alpha,
                        blend: command.blend,
                        clip,
                        soft_mask: active_soft_masks.last().cloned().flatten(),
                    }));
                    op_index += 1;
                    continue;
                }
                prepared::PreparedOp::TiledFill(tiling) if tiling.stencil.is_some() => {
                    // Preparing a pattern brush already paints its complete
                    // bounded source on CPU. Auto uses this bridge only when
                    // the page also has a native image draw whose GPU gain can
                    // amortize that work; forced GPU remains available for
                    // semantic validation and experimentation.
                    if automatic_routing && !has_native_image_draw {
                        return Ok(None);
                    }
                    let patterned = if let Some(cached) = self
                        .shared_prepared_patterned_stencils
                        .get(request, op_index)
                    {
                        cached
                    } else {
                        let pattern_bytes = (tiling.bounds.width as usize)
                            .checked_mul(tiling.bounds.height as usize)
                            .and_then(|pixels| pixels.checked_mul(4));
                        if pattern_bytes
                            .is_none_or(|bytes| bytes > MAX_PREPARED_PATTERNED_STENCIL_BYTES)
                        {
                            return Ok(None);
                        }
                        let Some(prepared) = exec::prepare_patterned_stencil(&prepared, tiling)
                        else {
                            if request
                                .limits
                                .cancellation
                                .as_ref()
                                .is_some_and(|token| token.is_cancelled())
                            {
                                return Err(RenderError::Cancelled);
                            }
                            return Ok(None);
                        };
                        self.shared_prepared_patterned_stencils
                            .insert(request, op_index, prepared)
                    };
                    let bounds = patterned.bounds;
                    let width = f64::from(bounds.width);
                    let height = f64::from(bounds.height);
                    if width == 0.0 || height == 0.0 {
                        return Ok(None);
                    }
                    let image_index = images.len() as u32;
                    images.push(PreparedRgbImage {
                        bounds,
                        // The prepared brush is a top-down, one-texel-per-
                        // device-pixel plane. WGPU's image convention has v=1
                        // at the top, hence the negative d term.
                        device_to_image: Matrix {
                            a: 1.0 / width,
                            b: 0.0,
                            c: 0.0,
                            d: -1.0 / height,
                            e: -f64::from(bounds.x) / width,
                            f: 1.0 + f64::from(bounds.y) / height,
                        },
                        width: bounds.width,
                        height: bounds.height,
                        samples: patterned.samples,
                        interpolation: crate::page_ir::InterpolationMode::Nearest,
                        footprint: [1.0, 1.0],
                        opacity: Some(PreparedImageOpacity {
                            width: bounds.width,
                            height: bounds.height,
                            samples: patterned.opacity,
                            footprint: [1.0, 1.0],
                            box_filter: false,
                        }),
                        clip: None,
                        soft_mask: active_soft_masks.last().cloned().flatten(),
                        alpha: tiling.alpha,
                        blend: tiling.blend,
                        stencil_rgb: None,
                    });
                    commands.push(PreparedGpuCommand::Image(image_index));
                    op_index += 1;
                    continue;
                }
                prepared::PreparedOp::PushSoftMask { content_end, .. } => {
                    let Some(mask) = derived_soft_masks[op_index].take() else {
                        return Ok(None);
                    };
                    active_soft_masks.push(Some(mask));
                    op_index = *content_end as usize;
                    continue;
                }
                prepared::PreparedOp::PushSoftMaskNone => {
                    active_soft_masks.push(None);
                    op_index += 1;
                    continue;
                }
                prepared::PreparedOp::PopSoftMask => {
                    active_soft_masks.pop();
                    op_index += 1;
                    continue;
                }
                // Searchable scan PDFs often overlay zero-alpha OCR text.
                // It is semantically non-painting and may be discarded at
                // this narrow image-renderer seam just as the CPU executor's
                // alpha blend would discard it.
                prepared::PreparedOp::GlyphRun(run) if run.alpha == 0 => {
                    op_index += 1;
                    continue;
                }
                _ => return Ok(None),
            };
            if automatic_routing
                && !image.is_stencil
                && image.bpc == 1
                && image
                    .footprint
                    .iter()
                    .any(|axis| *axis > AUTO_CPU_BILEVEL_MINIFICATION_FOOTPRINT)
            {
                return Ok(None);
            }
            let samples = if image.is_stencil {
                Arc::from([])
            } else {
                let Some(samples) = self
                    .shared_rgb_images
                    .get_or_convert(image, request.limits.cancellation.as_ref())?
                else {
                    return Ok(None);
                };
                samples
            };
            let opacity = if image.is_stencil {
                let Some(samples) = self.shared_opacity_images.get_or_expand(
                    &image.samples,
                    image.width,
                    image.height,
                    image.bpc,
                    image.decode.as_ref(),
                    true,
                    request.limits.cancellation.as_ref(),
                )?
                else {
                    return Ok(None);
                };
                Some(PreparedImageOpacity {
                    width: image.width,
                    height: image.height,
                    samples,
                    footprint: image.footprint,
                    box_filter: true,
                })
            } else if let Some(mask) = image.smask.as_ref() {
                let Some(samples) = self.shared_opacity_images.get_or_expand(
                    &mask.samples,
                    mask.width,
                    mask.height,
                    mask.bits_per_component,
                    mask.decode.as_ref(),
                    false,
                    request.limits.cancellation.as_ref(),
                )?
                else {
                    return Ok(None);
                };
                Some(PreparedImageOpacity {
                    width: mask.width,
                    height: mask.height,
                    samples,
                    footprint: [
                        (image.inv.a.abs() + image.inv.c.abs()) * mask.width as f64,
                        (image.inv.b.abs() + image.inv.d.abs()) * mask.height as f64,
                    ],
                    box_filter: true,
                })
            } else if let Some(mask) = image.mask.as_ref() {
                match mask {
                    ImageMask::ColorKey(ranges) => {
                        let Some(samples) = self.shared_opacity_images.get_or_expand_color_key(
                            &image.samples,
                            image.width,
                            image.height,
                            image.bpc,
                            image.color_space.components(),
                            ranges,
                            request.limits.cancellation.as_ref(),
                        )?
                        else {
                            return Ok(None);
                        };
                        Some(PreparedImageOpacity {
                            width: image.width,
                            height: image.height,
                            samples,
                            footprint: image.footprint,
                            box_filter: false,
                        })
                    }
                    ImageMask::Stencil(mask) => {
                        let Some(samples) = self.shared_opacity_images.get_or_expand(
                            &mask.samples,
                            mask.width,
                            mask.height,
                            mask.bits_per_component,
                            mask.decode.as_ref(),
                            true,
                            request.limits.cancellation.as_ref(),
                        )?
                        else {
                            return Ok(None);
                        };
                        Some(PreparedImageOpacity {
                            width: mask.width,
                            height: mask.height,
                            samples,
                            footprint: [
                                (image.inv.a.abs() + image.inv.c.abs()) * mask.width as f64,
                                (image.inv.b.abs() + image.inv.d.abs()) * mask.height as f64,
                            ],
                            box_filter: false,
                        })
                    }
                }
            } else {
                None
            };
            let clip = prepare_external_clip(
                &prepared,
                &mut clip_masks,
                &mut clip_raster,
                image.clip,
                image.clip_has_mask,
            )?;

            let image_index = images.len() as u32;
            images.push(PreparedRgbImage {
                bounds: image.bounds,
                device_to_image: image.inv,
                width: image.width,
                height: image.height,
                samples,
                interpolation: image.interpolation,
                footprint: image.footprint,
                opacity,
                clip,
                soft_mask: active_soft_masks.last().cloned().flatten(),
                alpha: image.alpha,
                blend: image.blend,
                stencil_rgb: image.is_stencil.then_some(image.stencil_rgb),
            });
            commands.push(PreparedGpuCommand::Image(image_index));
            op_index += 1;
        }

        if commands.is_empty() || (automatic_routing && images.is_empty()) {
            return Ok(None);
        }
        let Some(commands) = batch_gpu_path_commands(
            prepared.size,
            commands,
            request.limits.cancellation.as_ref(),
        ) else {
            if request
                .limits
                .cancellation
                .as_ref()
                .is_some_and(|token| token.is_cancelled())
            {
                return Err(RenderError::Cancelled);
            }
            return Ok(None);
        };
        // Native vector coverage remains forced-GPU-only until the measured
        // cost gate has a corpus-backed crossover. Auto must never turn a
        // newly supported semantic shape into an unmeasured performance loss.
        if automatic_routing
            && commands.iter().any(|command| {
                matches!(
                    command,
                    PreparedGpuCommand::Path(_) | PreparedGpuCommand::PathBatch(_)
                )
            })
        {
            return Ok(None);
        }
        let prepared = PreparedRgbImagePage {
            size: prepared.size,
            images,
            commands,
        };
        Ok(Some(self.shared_prepared_gpu_pages.insert(
            request,
            automatic_routing,
            prepared,
        )))
    }

    /// Render reusing a caller-owned worker context (avoids reallocating the
    /// coverage/flatten scratch across pages).
    pub fn render_with(
        &self,
        request: &RenderRequest,
        ctx: &mut CpuWorkerContext,
    ) -> Result<(HostPage, RenderStats), RenderError> {
        self.render_with_options(request, &CpuRenderOptions::default(), ctx)
    }

    /// [`Self::render_with`] under an explicit [`CpuRenderOptions`] policy.
    pub fn render_with_options(
        &self,
        request: &RenderRequest,
        options: &CpuRenderOptions,
        ctx: &mut CpuWorkerContext,
    ) -> Result<(HostPage, RenderStats), RenderError> {
        self.render_impl(
            request,
            options,
            ctx,
            surface_reuse_enabled(),
            OutputTarget::Request,
        )
    }

    /// Render an RGBA request and return it as tightly packed 8-bit RGB in a
    /// buffer of exactly `width * height * 3` bytes.
    ///
    /// A large page is rendered in strips that are converted as they finish
    /// (see [`Self::with_strip_target_bytes`]), so the render holds the RGB
    /// page plus one strip. A page small enough for one pass is converted
    /// from its surface, both planes alive during the copy. The page should
    /// be composited over an opaque background, since the alpha byte is
    /// dropped.
    pub fn render_rgb_with_options(
        &self,
        request: &RenderRequest,
        options: &CpuRenderOptions,
        ctx: &mut CpuWorkerContext,
    ) -> Result<(PackedRgbPage, RenderStats), RenderError> {
        self.render_rgb(request, options, ctx, OutputTarget::ExactRgb)
    }

    /// Render an RGBA request and return it as tightly packed 8-bit RGB,
    /// never holding a second full plane.
    ///
    /// A page small enough for one pass is packed inside the surface it was
    /// rendered on: one buffer throughout (four bytes per pixel), which keeps
    /// the RGBA length, so only the first `stride * height` bytes are pixels
    /// and a caller that retains many pages retains a third more than it
    /// needs. A large page is rendered in strips exactly as by
    /// [`Self::render_rgb_with_options`], which holds less still. The page
    /// should be composited over an opaque background, since the alpha byte
    /// is dropped.
    pub fn render_packed_rgb_with_options(
        &self,
        request: &RenderRequest,
        options: &CpuRenderOptions,
        ctx: &mut CpuWorkerContext,
    ) -> Result<(PackedRgbPage, RenderStats), RenderError> {
        self.render_rgb(request, options, ctx, OutputTarget::PackedRgb)
    }

    fn render_rgb(
        &self,
        request: &RenderRequest,
        options: &CpuRenderOptions,
        ctx: &mut CpuWorkerContext,
        target: OutputTarget,
    ) -> Result<(PackedRgbPage, RenderStats), RenderError> {
        if request.output_format != OutputFormat::Rgba8PremultipliedSrgb {
            return Err(RenderError::Backend(
                "RGB output needs an RGBA request".into(),
            ));
        }
        let (host, stats) =
            self.render_impl(request, options, ctx, surface_reuse_enabled(), target)?;
        Ok((
            PackedRgbPage {
                width: host.width,
                height: host.height,
                stride: host.stride,
                pixels: host.pixels,
            },
            stats,
        ))
    }

    /// For an RGB `target` the `HostPage` carries a three-byte stride under
    /// the request's RGBA format, so that form never leaves this module
    /// ([`Self::render_rgb`] rewraps it).
    fn render_impl(
        &self,
        request: &RenderRequest,
        options: &CpuRenderOptions,
        ctx: &mut CpuWorkerContext,
        pool_surface: bool,
        target: OutputTarget,
    ) -> Result<(HostPage, RenderStats), RenderError> {
        if let Some(token) = &request.limits.cancellation
            && token.is_cancelled()
        {
            return Err(RenderError::Cancelled);
        }
        if request.output_size.width == 0 || request.output_size.height == 0 {
            return Err(RenderError::LimitExceeded("zero output dimension"));
        }
        // Clamp an oversized page down to the byte budget rather than failing
        // it (a poster-sized MediaBox at screen DPI). Output dimensions and the
        // transform shrink together; the page renders whole, at lower res.
        let (output_size, transform_matrix, was_clamped) = clamp_output_to_budget(
            request.output_size,
            request.transform.matrix,
            request.limits.max_page_bytes,
        );
        let DeviceSize { width, height } = output_size;
        let bpp = request.output_format.bytes_per_pixel();
        let out_stride = width as usize * bpp;
        let out_bytes = out_stride
            .checked_mul(height as usize)
            .ok_or(RenderError::LimitExceeded("output size overflow"))?;
        // The internal surface is always RGBA8; bound against that. After the
        // clamp the RGBA8 surface fits by construction — this stays a hard
        // backstop for an output format wider than 4 bytes/pixel.
        let surface_bytes = (width as usize)
            .checked_mul(height as usize)
            .and_then(|p| p.checked_mul(4))
            .ok_or(RenderError::LimitExceeded("output size overflow"))?;
        if surface_bytes.max(out_bytes) as u64 > request.limits.max_page_bytes {
            return Err(RenderError::LimitExceeded("max_page_bytes"));
        }

        let mut stats = RenderStats::default();
        if was_clamped {
            stats.recovery_notes.push(format!(
                "oversized page clamped to {width}x{height} to fit max_page_bytes"
            ));
        }

        // Request-specific lowering: transform, flatten, cull, classify, once.
        let decode_limits = image_decode_limits(&request.limits);
        let decode_floor = options
            .image_decode_reference
            .and_then(|reference| prepared::decode_floor_map(transform_matrix, reference.matrix));
        // The page is painted in chunks while it is lowered (see
        // `prepared::LowerSink`), so neither the whole page's flattened
        // geometry nor all of its decoded images are ever held at once. The
        // surface is allocated when the first chunk is painted, not before
        // lowering starts: a codec's working set while it decodes a scan is
        // several times the page, and for a page that lowers in one piece
        // (most pages) the surface must not sit beside it.
        #[cfg(feature = "profiling")]
        let prep_time = std::cell::Cell::new(std::time::Duration::ZERO);
        let new_surface = || {
            #[cfg(feature = "profiling")]
            let prep_start = std::time::Instant::now();
            let surface = Surface::new_recycled(
                width as usize,
                height as usize,
                request.background,
                pool_surface
                    .then(|| self.surfaces.take(width as usize, height as usize))
                    .flatten(),
            );
            #[cfg(feature = "profiling")]
            prep_time.set(prep_start.elapsed());
            surface
        };
        #[cfg(feature = "profiling")]
        let lower_start = std::time::Instant::now();

        // One pass over the whole page, or one pass per horizontal strip: the
        // same lowering in the same device coordinates with painting clamped
        // to the strip's rows (docs/plans/strip-rendering-2026-11-20.md).
        //
        // A page whose output is converted from the surface (Gray8, RGB) and
        // is large is rendered in strips, each converted straight into the
        // output buffer, so the full RGBA surface never exists. An RGBA page
        // is its own surface; it is rendered in strips, each copied into the
        // page, only when its group and soft-mask offscreens are large enough
        // for that to hold less (see `strip_rows_for`).
        let rgba_out = target == OutputTarget::Request
            && request.output_format == OutputFormat::Rgba8PremultipliedSrgb;
        let strip_rows = self.strip_rows_for(
            rgba_out,
            &request.page.complexity,
            &transform_matrix,
            width,
            height,
        );
        let windows: Vec<(u32, u32)> = match strip_rows {
            Some(rows) => (0..height)
                .step_by(rows as usize)
                .map(|first| (first, first.saturating_add(rows).min(height)))
                .collect(),
            _ => vec![(0, u32::MAX)],
        };
        let striped = windows.len() > 1;
        // Every strip is painted on a surface of the same height, the last
        // one using only its top rows: one buffer then serves the whole page
        // and, parked, the next page of the same size. A shorter last strip
        // needed a second buffer, and one of those was parked per render.
        let strip_height = strip_rows.map_or(0, |rows| rows.min(height)) as usize;
        // Strips written straight into the output, and its bytes per pixel.
        let direct = striped && !rgba_out;
        let direct_bpp = match target {
            OutputTarget::Request => bpp,
            OutputTarget::PackedRgb | OutputTarget::ExactRgb => 3,
        };
        let direct_stride = width as usize * direct_bpp;
        let mut direct_out: Option<Arc<[u8]>> = None;
        let mut strip_bytes = 0u64;
        let (fonts, raster, kernels) = ctx.parts();
        let mut page_surface: Option<Surface> = None;
        let mut kept: Option<prepared::CpuPreparedPage> = None;
        // Recorded by the first strip, read by the rest.
        let mut extents = prepared::OpExtents::default();
        // Decodes a later strip draws again, kept by the render itself.
        let decodes = striped.then(|| Arc::new(prepared::StripDecodes::default()));
        // The strip buffer between two strips.
        let strip_buffer: std::cell::Cell<Option<Arc<[u8]>>> = std::cell::Cell::new(None);
        for &(first_row, end_row) in &windows {
            let strip_surface = || {
                if striped {
                    let mut strip = Surface::new_recycled(
                        width as usize,
                        strip_height,
                        request.background,
                        strip_buffer.take().or_else(|| {
                            pool_surface
                                .then(|| self.surfaces.take(width as usize, strip_height))
                                .flatten()
                        }),
                    );
                    strip.origin_y = first_row as usize;
                    strip
                } else {
                    new_surface()
                }
            };
            let mut surface: Option<Surface> = None;
            let mut exec_state = exec::ExecState::new();
            let prepared = {
                let mut flush = |chunk: &prepared::CpuPreparedPage, live_clips: &[u32]| {
                    exec::execute_chunk(
                        chunk,
                        live_clips,
                        &mut exec_state,
                        surface.get_or_insert_with(&strip_surface),
                        raster,
                        kernels,
                        &mut stats,
                    );
                    !stats.cancelled
                };
                let mut sink = prepared::LowerSink {
                    chunk_bytes: prepared::lower_chunk_bytes(),
                    image_chunk_bytes: prepared::lower_image_chunk_bytes(),
                    rows: (first_row, end_row),
                    extents: striped.then_some(&mut extents),
                    decodes: decodes.clone(),
                    flush: &mut flush,
                };
                prepared::lower_with_font_cache(
                    &request.page,
                    transform_matrix,
                    output_size,
                    &self.options.codecs,
                    &decode_limits,
                    self.options.hinting,
                    request.color_policy,
                    fonts,
                    shared_font_cache_enabled().then_some(self.shared_fonts.as_ref()),
                    glyph_cache_enabled().then_some(self.shared_glyphs.as_ref()),
                    image_cache_enabled().then_some(&self.shared_images),
                    decode_floor,
                    Some(&mut sink),
                )
            };
            if stats.cancelled {
                return Err(RenderError::Cancelled);
            }
            // What was not flushed along the way: everything, when it is small.
            let mut strip = surface.unwrap_or_else(&strip_surface);
            exec::execute_chunk(
                &prepared,
                &[],
                &mut exec_state,
                &mut strip,
                raster,
                kernels,
                &mut stats,
            );
            if stats.cancelled {
                return Err(RenderError::Cancelled);
            }
            if let Some(decodes) = &decodes {
                decodes.release_through(end_row);
            }
            // The rows of this strip that belong to the page.
            let used_rows = if striped {
                (end_row - first_row) as usize
            } else {
                strip.height
            };
            if direct {
                // Convert this strip's rows into their place in the output.
                // The buffer is zero pages until written, so it grows with
                // the strips instead of sitting whole beside the first one.
                let out = direct_out
                    .get_or_insert_with(|| surface::zeroed_arc(direct_stride * height as usize));
                let rows = surface::unique_arc_mut(out)
                    .get_mut(first_row as usize * direct_stride..)
                    .and_then(|rest| rest.get_mut(..used_rows * direct_stride))
                    .ok_or_else(|| RenderError::Backend("strip outside the page".into()))?;
                let painted = strip
                    .pixels()
                    .get(..used_rows * width as usize * 4)
                    .ok_or_else(|| RenderError::Backend("strip shorter than its rows".into()))?;
                if direct_bpp == 1 {
                    surface::rgba_rows_to_gray8(painted, rows, exec::output_fan_out());
                } else {
                    surface::rgba_rows_to_rgb8(painted, rows);
                }
                strip_bytes = strip_bytes.max(strip.bytes());
                strip_buffer.set(Some(strip.into_buffer()));
            } else if striped {
                // The strips cover every row, so the page needs no background.
                let page = page_surface.get_or_insert_with(|| {
                    Surface::new_unpainted(
                        width as usize,
                        height as usize,
                        pool_surface
                            .then(|| self.surfaces.take(width as usize, height as usize))
                            .flatten(),
                    )
                });
                for local in 0..used_rows {
                    page.row_mut(first_row as usize + local)
                        .copy_from_slice(strip.local_row(local));
                }
                strip_buffer.set(Some(strip.into_buffer()));
            } else {
                page_surface = Some(strip);
            }
            // A dropped draw is noted by every strip it touches; report the
            // strip that saw the most rather than the sum.
            if kept.as_ref().is_none_or(|best| {
                prepared.diagnostics.degraded_draws() > best.diagnostics.degraded_draws()
            }) {
                kept = Some(prepared);
            }
        }
        stats.ops_total = request.page.operations.len() as u32;
        let Some(prepared) = kept else {
            return Err(RenderError::Backend("no strip was rendered".into()));
        };
        // The working plane: one strip, or the page surface.
        let surface = if direct {
            stats.surface_bytes = strip_bytes;
            None
        } else {
            let surface = page_surface.unwrap_or_else(&new_surface);
            stats.surface_bytes = surface.bytes();
            // An RGBA page painted in strips: keep the strip buffer for the
            // next one.
            if pool_surface && let Some(buffer) = strip_buffer.take() {
                self.surfaces.park(buffer);
            }
            Some(surface)
        };
        #[cfg(feature = "profiling")]
        {
            // Chunks were painted, and the surface made, inside the lowering
            // call.
            stats.prep = prep_time.get();
            stats.lower = lower_start
                .elapsed()
                .saturating_sub(stats.raster)
                .saturating_sub(stats.prep);
        }
        // Fold in codec draws dropped during top-level lowering (tiling-cell
        // drops are absorbed inside `execute`). A page left blank by an
        // undecodable image is now observable, never a silent clean pass.
        stats.absorb_diagnostics(&prepared.diagnostics);
        #[cfg(feature = "profiling")]
        stats.profile.merge(&prepared.profile_report());
        let _ = &self.options;

        #[cfg(feature = "profiling")]
        let output_start = std::time::Instant::now();
        let mut parked = None;
        let (stride, pixels) = match surface {
            Some(surface) => match target {
                OutputTarget::PackedRgb => surface.into_packed_rgb(&mut parked),
                OutputTarget::ExactRgb => surface.into_exact_rgb(&mut parked),
                OutputTarget::Request => {
                    surface.into_output_recycling(request.output_format, &mut parked)
                }
            },
            // Already converted, strip by strip; the strip buffer is what
            // there is to reuse.
            None => {
                parked = strip_buffer.take();
                let pixels = direct_out
                    .ok_or_else(|| RenderError::Backend("no strip was converted".into()))?;
                (direct_stride, pixels)
            }
        };
        if pool_surface && let Some(buffer) = parked {
            self.surfaces.park(buffer);
        }
        stats.output_bytes = pixels.len() as u64;
        #[cfg(feature = "profiling")]
        {
            stats.output = output_start.elapsed();
        }
        Ok((
            HostPage {
                width,
                height,
                stride,
                format: request.output_format,
                pixels,
            },
            stats,
        ))
    }

    /// Render with the same semantics as [`Self::render_with`] while returning
    /// the feature-gated performance report consumed by benchmark tooling.
    #[cfg(feature = "profiling")]
    pub fn render_profiled_with(
        &self,
        request: &RenderRequest,
        ctx: &mut CpuWorkerContext,
    ) -> Result<(HostPage, RenderStats, crate::profiling::ProfileReport), RenderError> {
        let total_start = std::time::Instant::now();
        let (host, stats) = self.render_with(request, ctx)?;
        let mut profile = profile_from_stats(&stats, total_start.elapsed());
        // RGBA output takes ownership of the surface allocation; it is no
        // longer a second simultaneously-live full-page buffer. Gray8 still
        // allocates its smaller output while reading the RGBA surface.
        let transient_render_bytes = match request.output_format {
            OutputFormat::Rgba8PremultipliedSrgb => stats.surface_bytes.max(stats.output_bytes),
            OutputFormat::Gray8 => stats.surface_bytes.saturating_add(stats.output_bytes),
        };
        profile.allocate_bytes(transient_render_bytes);
        profile.release_bytes(transient_render_bytes);
        Ok((host, stats, profile))
    }

    /// Lower a compiled page once for repeated prepared-page execution
    /// experiments. The opaque prepared page is intentionally feature-gated:
    /// production callers should keep using `render_with`.
    #[cfg(feature = "profiling")]
    pub fn prepare_profiled(
        &self,
        request: &RenderRequest,
    ) -> Result<(CpuPreparedPage, crate::profiling::ProfileReport), RenderError> {
        let DeviceSize { width, height } = request.output_size;
        if width == 0 || height == 0 {
            return Err(RenderError::LimitExceeded("zero output dimension"));
        }
        let surface_bytes = width as u64 * height as u64 * 4;
        if surface_bytes > request.limits.max_page_bytes {
            return Err(RenderError::LimitExceeded("max_page_bytes"));
        }
        let start = std::time::Instant::now();
        let decode_limits = image_decode_limits(&request.limits);
        let prepared = prepared::lower(
            &request.page,
            request.transform.matrix,
            request.output_size,
            &self.options.codecs,
            &decode_limits,
            self.options.hinting,
        );
        if decode_limits.is_cancelled() {
            return Err(RenderError::Cancelled);
        }
        let mut profile = prepared.profile_report();
        profile.add_duration("render.prepare", start.elapsed());
        Ok((prepared, profile))
    }

    /// Prepare using profiling-only decoded-image residency shared by the
    /// caller across repeated preparations.
    #[cfg(feature = "profiling")]
    pub fn prepare_with_decode_cache_profiled(
        &self,
        request: &RenderRequest,
        cache: DecodedImageCache,
    ) -> Result<(CpuPreparedPage, crate::profiling::ProfileReport), RenderError> {
        let DeviceSize { width, height } = request.output_size;
        if width == 0 || height == 0 {
            return Err(RenderError::LimitExceeded("zero output dimension"));
        }
        let surface_bytes = width as u64 * height as u64 * 4;
        if surface_bytes > request.limits.max_page_bytes {
            return Err(RenderError::LimitExceeded("max_page_bytes"));
        }
        let start = std::time::Instant::now();
        let decode_limits = image_decode_limits(&request.limits);
        let prepared = prepared::lower_with_decode_cache(
            &request.page,
            request.transform.matrix,
            request.output_size,
            &self.options.codecs,
            &decode_limits,
            self.options.hinting,
            cache,
        );
        if decode_limits.is_cancelled() {
            return Err(RenderError::Cancelled);
        }
        let mut profile = prepared.profile_report();
        profile.add_duration("render.prepare", start.elapsed());
        Ok((prepared, profile))
    }

    /// Decode the compiled page's unique embedded codec payloads without
    /// lowering geometry or rasterizing.
    #[cfg(feature = "profiling")]
    pub fn decode_page_profiled(
        &self,
        request: &RenderRequest,
    ) -> Result<crate::profiling::ProfileReport, RenderError> {
        let decode_limits = image_decode_limits(&request.limits);
        let profile = prepared::decode_page(
            &request.page,
            &self.options.codecs,
            &decode_limits,
            self.options.hinting,
        );
        if decode_limits.is_cancelled() {
            return Err(RenderError::Cancelled);
        }
        Ok(profile)
    }

    /// Execute a page previously returned by [`Self::prepare_profiled`].
    #[cfg(feature = "profiling")]
    pub fn execute_prepared_profiled(
        &self,
        request: &RenderRequest,
        prepared: &CpuPreparedPage,
        ctx: &mut CpuWorkerContext,
    ) -> Result<(HostPage, RenderStats, crate::profiling::ProfileReport), RenderError> {
        let DeviceSize { width, height } = request.output_size;
        if prepared.size != request.output_size || width == 0 || height == 0 {
            return Err(RenderError::Backend(
                "prepared page does not match request".into(),
            ));
        }
        let total_start = std::time::Instant::now();
        let surface_start = std::time::Instant::now();
        let mut surface = Surface::new_recycled(
            width as usize,
            height as usize,
            request.background,
            surface_reuse_enabled()
                .then(|| self.surfaces.take(width as usize, height as usize))
                .flatten(),
        );
        let mut stats = RenderStats {
            surface_bytes: surface.bytes(),
            ..RenderStats::default()
        };
        stats.prep = surface_start.elapsed();
        exec::execute(prepared, &mut surface, ctx, &mut stats);
        if stats.cancelled {
            return Err(RenderError::Cancelled);
        }
        stats.absorb_diagnostics(&prepared.diagnostics);
        let output_start = std::time::Instant::now();
        let mut parked = None;
        let (stride, pixels) = surface.into_output_recycling(request.output_format, &mut parked);
        if surface_reuse_enabled()
            && let Some(buffer) = parked
        {
            self.surfaces.park(buffer);
        }
        stats.output_bytes = pixels.len() as u64;
        stats.output = output_start.elapsed();
        let mut profile = stats.profile.clone();
        profile.add_duration("render.surface", stats.prep);
        profile.add_duration("render.execute", stats.raster);
        profile.add_duration("render.output", stats.output);
        profile.add_duration("render.prepared_total", total_start.elapsed());
        profile.increment("render.output_bytes", stats.output_bytes);
        let transient_render_bytes = match request.output_format {
            OutputFormat::Rgba8PremultipliedSrgb => stats.surface_bytes.max(stats.output_bytes),
            OutputFormat::Gray8 => stats.surface_bytes.saturating_add(stats.output_bytes),
        };
        profile.allocate_bytes(transient_render_bytes);
        profile.release_bytes(transient_render_bytes);
        Ok((
            HostPage {
                width,
                height,
                stride,
                format: request.output_format,
                pixels,
            },
            stats,
            profile,
        ))
    }
}

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

/// The default strip size: `PDF_RENDERER_STRIP_MB` in MiB when set (0 turns
/// automatic strips off), else [`STRIP_TARGET_BYTES`]. Read once.
pub(crate) fn default_strip_target_bytes() -> usize {
    use std::sync::OnceLock;
    static BYTES: OnceLock<usize> = OnceLock::new();
    *BYTES.get_or_init(|| {
        std::env::var("PDF_RENDERER_STRIP_MB")
            .ok()
            .and_then(|v| v.trim().parse::<usize>().ok())
            .map_or(STRIP_TARGET_BYTES, |mb| mb.saturating_mul(1024 * 1024))
    })
}

/// Rows per strip when `PDF_RENDERER_STRIP_ROWS` is set (and positive): every
/// page is then rendered strip by strip, whatever its size and format. It
/// exists so the page-hash gate can check that strips are byte-identical to
/// one pass on pages too small to be stripped otherwise, RGBA included (whose
/// strips are assembled into a full surface and save nothing). Read once.
fn strip_rows_override() -> Option<u32> {
    use std::sync::OnceLock;
    static ROWS: OnceLock<Option<u32>> = OnceLock::new();
    *ROWS.get_or_init(|| {
        std::env::var("PDF_RENDERER_STRIP_ROWS")
            .ok()
            .and_then(|v| v.trim().parse::<u32>().ok())
            .filter(|&rows| rows > 0)
    })
}

/// Whether finished page buffers are pooled and reused across renders. On by
/// default; `PDF_RENDERER_SURFACE_REUSE=off` (or `0`) disables it, for paired
/// A/B isolation on one binary. Read once.
fn surface_reuse_enabled() -> bool {
    use std::sync::OnceLock;
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| match std::env::var("PDF_RENDERER_SURFACE_REUSE") {
        Ok(v) => {
            let v = v.trim().to_ascii_lowercase();
            v != "off" && v != "0" && v != "false"
        }
        Err(_) => true,
    })
}

/// Whether the document-scoped shared font parse cache is active. On by default;
/// `PDF_RENDERER_FONTCACHE=off` (or `0`) disables it, for paired A/B isolation
/// of the cache on one binary. Read once.
fn shared_font_cache_enabled() -> bool {
    use std::sync::OnceLock;
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| match std::env::var("PDF_RENDERER_FONTCACHE") {
        Ok(v) => {
            let v = v.trim().to_ascii_lowercase();
            v != "off" && v != "0" && v != "false"
        }
        Err(_) => true,
    })
}

/// Whether the document-scoped rendered-glyph coverage cache is active. On by
/// default; `PDF_RENDERER_GLYPHCACHE=off` (or `0`) disables it, for paired A/B
/// isolation of the cache on one binary. Read once.
fn glyph_cache_enabled() -> bool {
    use std::sync::OnceLock;
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| match std::env::var("PDF_RENDERER_GLYPHCACHE") {
        Ok(v) => {
            let v = v.trim().to_ascii_lowercase();
            v != "off" && v != "0" && v != "false"
        }
        Err(_) => true,
    })
}

/// Whether the document-scoped decoded-image cache is active. On by default;
/// `PDF_RENDERER_IMAGECACHE=off` (or `0`) disables it, for paired A/B
/// isolation of the cache on one binary. Read once.
fn image_cache_enabled() -> bool {
    use std::sync::OnceLock;
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| match std::env::var("PDF_RENDERER_IMAGECACHE") {
        Ok(v) => {
            let v = v.trim().to_ascii_lowercase();
            v != "off" && v != "0" && v != "false"
        }
        Err(_) => true,
    })
}

impl Drop for CpuBackend {
    fn drop(&mut self) {
        // Optional observability for the parse-cache measurement: on backend
        // teardown (one document render session), report how often the shared
        // Type 1 / bare-CFF parse cache served a program without reparsing.
        if std::env::var_os("PDF_RENDERER_FONTCACHE_STATS").is_some() {
            let (hits, inserts) = self.shared_fonts.stats();
            eprintln!("shared-font-cache: hits={hits} inserts={inserts}");
        }
        if std::env::var_os("PDF_RENDERER_GLYPHCACHE_STATS").is_some() {
            let (hits, misses, inserts) = self.shared_glyphs.stats();
            let total = hits + misses;
            let rate = if total > 0 {
                hits as f64 / total as f64
            } else {
                0.0
            };
            eprintln!(
                "shared-glyph-cache: hits={hits} misses={misses} inserts={inserts} hit_rate={rate:.4}"
            );
        }
        if std::env::var_os("PDF_RENDERER_IMAGECACHE_STATS").is_some() {
            let (hits, misses, inserts) = self.shared_images.stats();
            let total = hits + misses;
            let rate = if total > 0 {
                hits as f64 / total as f64
            } else {
                0.0
            };
            eprintln!(
                "shared-image-cache: hits={hits} misses={misses} inserts={inserts} hit_rate={rate:.4}"
            );
        }
    }
}

impl RenderBackend for CpuBackend {
    fn id(&self) -> BackendId {
        BackendId::Cpu
    }

    fn capabilities(&self) -> BackendCapabilities {
        BackendCapabilities {
            formats: vec![OutputFormat::Rgba8PremultipliedSrgb, OutputFormat::Gray8],
            max_surface: DeviceSize {
                width: 1 << 16,
                height: 1 << 16,
            },
            features: self.features(),
            resident_surfaces: false,
            postprocess: PostprocessCapabilities::HOST_ALL,
        }
    }

    fn supports(&self, page: &CompiledPage, _request: &RenderRequest) -> SupportLevel {
        let missing = page.features.difference(self.features());
        if missing.is_empty() {
            SupportLevel::Native
        } else {
            SupportLevel::Unsupported(UnsupportedFeature {
                missing,
                detail: "feature not yet implemented in CPU rasterizer",
            })
        }
    }

    /// One strip for a page [`Self::render_to_host`] renders in strips, the
    /// whole surface otherwise: the same choice, from the same function, on
    /// the size and transform the render clamps the request to.
    fn working_surface_bytes(&self, request: &RenderRequest) -> u64 {
        let (size, matrix, _) = clamp_output_to_budget(
            request.output_size,
            request.transform.matrix,
            request.limits.max_page_bytes,
        );
        let rgba_out = request.output_format == OutputFormat::Rgba8PremultipliedSrgb;
        let rows = self
            .strip_rows_for(
                rgba_out,
                &request.page.complexity,
                &matrix,
                size.width,
                size.height,
            )
            .unwrap_or(size.height);
        u64::from(size.width)
            .saturating_mul(u64::from(rows))
            .saturating_mul(4)
    }

    fn submit(&self, request: RenderRequest) -> Result<RenderTicket, SubmitError> {
        let job_id = self.job_counter.fetch_add(1, Ordering::Relaxed);
        let (ticket, tx) = RenderTicket::new(job_id);
        // Synchronous fulfillment for now; the scheduler provides page-level
        // parallelism by calling submit from its own worker pool. Phase 4
        // may move fulfillment onto an internal rayon pool for tile
        // parallelism inside huge pages.
        let result = self
            .render_to_host(&request)
            .map(|(host, _stats)| RenderedPage::Host(host));
        let _ = tx.send(result);
        Ok(ticket)
    }
}

/// The stage report for one render: the `RenderStats` stage timers and counters
/// under their `render.*` names, plus everything the lowering and execution
/// hot paths recorded.
#[cfg(feature = "profiling")]
pub(crate) fn profile_from_stats(
    stats: &RenderStats,
    total: std::time::Duration,
) -> crate::profiling::ProfileReport {
    let mut profile = crate::profiling::ProfileReport::new();
    profile.add_duration("render.lower", stats.lower);
    profile.add_duration("render.surface", stats.prep);
    profile.add_duration("render.execute", stats.raster);
    profile.add_duration("render.output", stats.output);
    profile.add_duration("render.total", total);
    profile.increment("render.operations", stats.ops_total as u64);
    profile.increment("render.commands", stats.commands as u64);
    profile.increment("render.painted_ops", stats.ops_painted as u64);
    profile.increment("render.edges", stats.edges);
    profile.increment("render.covered_pixels", stats.covered_pixels);
    profile.increment(
        "render.transparency_groups",
        stats.transparency_groups as u64,
    );
    profile.increment("render.soft_masks", stats.soft_masks as u64);
    profile.increment("render.output_bytes", stats.output_bytes);
    profile.merge(&stats.profile);
    profile
}

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

    const JBIG2_L_12X5: &[u8] = &[
        0x00, 0x00, 0x00, 0x01, 0x30, 0x00, 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x0c,
        0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x00,
        0x00, 0x00, 0x00, 0x02, 0x26, 0x00, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x0c,
        0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
        0xff, 0xfd, 0xff, 0x02, 0xfe, 0xfe, 0xfe, 0xd2, 0x47, 0xc5, 0xc3, 0x1b, 0xff, 0xff, 0xac,
    ];

    fn jbig2_smask(decode: Option<[[f32; 2]; 1]>) -> crate::page_ir::ImageSMask {
        crate::page_ir::ImageSMask {
            width: 12,
            height: 5,
            bits_per_component: 1,
            decode: decode.map(|pairs| Arc::from(pairs.as_slice())),
            samples: Arc::from([]),
            codec: Some(crate::page_ir::ImageCodecKind::Jbig2),
            codec_data: Some(JBIG2_L_12X5.into()),
            codec_parms: None,
        }
    }

    #[test]
    fn standalone_jbig2_smask_decode_applies_pdf_opacity_polarity() {
        let backend = CpuBackend::default();
        let normal = backend
            .decode_bilevel_jbig2_smask(&jbig2_smask(None), &RenderLimits::default())
            .unwrap()
            .unwrap();
        let inverted = backend
            .decode_bilevel_jbig2_smask(&jbig2_smask(Some([[1.0, 0.0]])), &RenderLimits::default())
            .unwrap()
            .unwrap();
        assert_eq!((normal.width, normal.height, normal.stride), (12, 5, 12));
        assert_eq!(normal.opacity[0], 0, "black JBIG2 code becomes sample zero");
        assert_eq!(normal.opacity[1], 255);
        assert!(
            normal
                .opacity
                .iter()
                .zip(inverted.opacity.iter())
                .all(|(&a, &b)| a == 255 - b)
        );
    }

    #[test]
    fn standalone_jbig2_smask_decode_declines_malformed_data() {
        let mut smask = jbig2_smask(None);
        smask.codec_data = Some((&b"not jbig2"[..]).into());
        assert!(
            CpuBackend::default()
                .decode_bilevel_jbig2_smask(&smask, &RenderLimits::default())
                .unwrap()
                .is_none()
        );
    }

    #[test]
    fn image_limits_tighten_defaults_and_share_cancellation() {
        let token = crate::render_api::CancellationToken::new();
        let limits = RenderLimits {
            max_page_bytes: 4096,
            cancellation: Some(token.clone()),
            ..RenderLimits::default()
        };
        let codec = image_decode_limits(&limits);
        assert_eq!(codec.max_input_bytes, 4096);
        assert_eq!(codec.max_output_bytes, 4096);
        assert_eq!(codec.max_working_bytes, 4096);
        assert!(!codec.is_cancelled());
        token.cancel();
        assert!(codec.is_cancelled());

        let loose = image_decode_limits(&RenderLimits::default());
        let defaults = crate::image::DecodeLimits::default();
        assert_eq!(loose.max_input_bytes, defaults.max_input_bytes);
        assert_eq!(loose.max_working_bytes, defaults.max_working_bytes);
    }

    #[test]
    fn clamp_leaves_within_budget_pages_untouched() {
        let size = DeviceSize {
            width: 1000,
            height: 800,
        };
        let (out, m, clamped) = clamp_output_to_budget(size, Matrix::IDENTITY, 2 << 30);
        assert!(!clamped);
        assert_eq!(out, size);
        assert_eq!(m, Matrix::IDENTITY);
    }

    #[test]
    fn clamp_zero_budget_disables() {
        let size = DeviceSize {
            width: 100_000,
            height: 100_000,
        };
        let (out, _, clamped) = clamp_output_to_budget(size, Matrix::IDENTITY, 0);
        assert!(!clamped);
        assert_eq!(out, size);
    }

    #[test]
    fn capabilities_advertise_complete_host_postprocessing() {
        let postprocess = CpuBackend::default().capabilities().postprocess;
        assert_eq!(
            postprocess.operations,
            crate::render_api::PostprocessOperations::all()
        );
        assert!(!postprocess.resident_execution);
    }

    #[test]
    fn clamp_oversized_fits_budget_and_folds_scale_into_transform() {
        // A poster page whose RGBA8 surface far exceeds the budget.
        let size = DeviceSize {
            width: 20_000,
            height: 30_000,
        };
        let budget = 2u64 << 30; // 2 GiB
        let (out, m, clamped) = clamp_output_to_budget(size, Matrix::scale(2.0, 2.0), budget);
        assert!(clamped);
        // Clamped surface fits the budget by construction.
        let surface = out.width as u64 * out.height as u64 * 4;
        assert!(surface <= budget, "surface {surface} > budget {budget}");
        // Aspect ratio is preserved within a pixel of rounding.
        let want = size.width as f64 / size.height as f64;
        let got = out.width as f64 / out.height as f64;
        assert!((want - got).abs() < 1e-3);
        // The original scale-2 matrix mapped page (10000,15000) onto the old
        // device far corner (20000,30000); after the clamp the same page point
        // must land on the new box's far corner.
        let corner = m.apply(crate::page_ir::Point {
            x: 10_000.0,
            y: 15_000.0,
        });
        assert!((corner.x - out.width as f64).abs() < 2.0);
        assert!((corner.y - out.height as f64).abs() < 2.0);
    }

    use crate::page_ir::{PageBounds, Rect};
    use crate::render_api::{
        AnnotationMode, Background, OutputResidency, PageTransform, RenderLimits, RenderQuality,
        render_blocking,
    };

    fn basic_request(format: OutputFormat, background: Background) -> RenderRequest {
        let page = CompiledPage::empty(PageBounds {
            crop: Rect {
                x0: 0.0,
                y0: 0.0,
                x1: 612.0,
                y1: 792.0,
            },
            rotate: 0,
        });
        RenderRequest {
            page: Arc::new(page),
            transform: PageTransform {
                matrix: crate::page_ir::Matrix::IDENTITY,
            },
            crop: None,
            output_size: DeviceSize {
                width: 8,
                height: 4,
            },
            output_format: format,
            background,
            annotations: AnnotationMode::None,
            color_policy: crate::render_api::RenderColorPolicy::Original,
            quality: RenderQuality::Normal,
            limits: RenderLimits::default(),
            residency: OutputResidency::HostRequired,
        }
    }

    #[test]
    fn renders_white_background_end_to_end() {
        let backend = CpuBackend::default();
        let request = basic_request(OutputFormat::Rgba8PremultipliedSrgb, Background::White);
        assert!(matches!(
            backend.supports(&request.page, &request),
            SupportLevel::Native
        ));
        let page = render_blocking(&backend, request).unwrap();
        let host = page.as_host().unwrap();
        assert_eq!((host.width, host.height, host.stride), (8, 4, 32));
        assert!(host.pixels.iter().all(|&b| b == 0xFF));
    }

    #[test]
    fn respects_memory_limit() {
        // A budget too small for the full surface clamps the page down to fit
        // rather than rejecting it: the render succeeds and the RGBA8 surface
        // stays within budget (the OOM guard is preserved, just non-fatally).
        let backend = CpuBackend::default();
        let mut request = basic_request(OutputFormat::Gray8, Background::White);
        request.limits.max_page_bytes = 8;
        let page = render_blocking(&backend, request).unwrap();
        let host = page.as_host().unwrap();
        assert!(host.width >= 1 && host.height >= 1);
        assert!(
            host.width as u64 * host.height as u64 * 4 <= 8,
            "clamped surface {}x{} exceeds the 8-byte budget",
            host.width,
            host.height
        );
    }

    #[test]
    fn declines_pages_with_unimplemented_features() {
        let backend = CpuBackend::default();
        let request = basic_request(OutputFormat::Gray8, Background::White);
        let mut page = (*request.page).clone();
        // Soft masks are not implemented yet, so such a page is declined.
        page.features = PageFeatures::SOFT_MASKS;
        assert!(matches!(
            backend.supports(&page, &request),
            SupportLevel::Unsupported(_)
        ));
    }
}