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
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use crate::content::{PageCompiler, SemanticPage};
use crate::document::{DocumentLimits, DocumentSnapshot, PageIndex, ParseContext};
use crate::page_ir::{
    BlendMode, CompiledPage, DeviceRect, DeviceSize, DisplayOp, ImageCodecKind, ImageSMask, Matrix,
    PageFeatures, Point,
};
use crate::render_api::{
    AnnotationMode, Background, HostPage, OutputFormat, OutputResidency, PageTransform,
    RenderColorPolicy, RenderLimits, RenderQuality, RenderRequest,
};
use crate::render_cpu::{
    CpuBackend, CpuBackendOptions, CpuRenderOptions, CpuWorkerContext, DecodedBilevelSmask,
};

use crate::reader::intake::source;
use crate::reader::page_cache::PageCache;

/// The mutable state one page job works with: parser caches and raster
/// scratch, kept warm from one job to the next.
#[derive(Debug)]
struct WorkerContexts {
    parse: ParseContext,
    raster: CpuWorkerContext,
}

/// The idle [`WorkerContexts`] of one session.
///
/// A job checks one out, works without any lock held, and puts it back, so
/// there are as many as the session ever had jobs running at once. They used
/// to be thread-locals, reset only when the thread next served a different
/// session: closing a document freed nothing on the pool threads that had
/// worked on it, and each kept its parse cache (up to 256 MiB) and raster
/// scratch for as long as the thread lived. Owned here, they are dropped with
/// the session and can be released early ([`RenderSession::release_idle_memory`]).
#[derive(Debug, Default)]
struct WorkerPool {
    idle: std::sync::Mutex<Vec<WorkerContexts>>,
}

impl WorkerPool {
    fn lock(&self) -> std::sync::MutexGuard<'_, Vec<WorkerContexts>> {
        // Contexts are only ever pushed whole; a poisoned lock still guards a
        // valid list.
        self.idle
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    /// Run `job` with a warm context when one is idle, else a new one. A job
    /// that unwinds drops its context rather than returning it: scratch a
    /// panic interrupted is never reused.
    fn with<R>(&self, job: impl FnOnce(&mut WorkerContexts) -> R) -> R {
        // Most recently returned first: its caches are the likeliest warm.
        let recycled = self.lock().pop();
        let mut worker = recycled.unwrap_or_else(|| WorkerContexts {
            parse: ParseContext::new(),
            raster: CpuWorkerContext::new(),
        });
        let result = job(&mut worker);
        self.lock().push(worker);
        result
    }

    fn clear(&self) {
        self.lock().clear();
    }
}

static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1);

/// Cooperative cancellation token. The renderer token stays private
/// to this crate while page jobs can cheaply clone, cancel, and checkpoint it.
#[derive(Debug, Clone, Default)]
pub struct CancellationToken(crate::render_api::CancellationToken);

impl CancellationToken {
    /// A token that is not cancelled.
    pub fn new() -> Self {
        Self::default()
    }

    /// Request cancellation. Work holding this token or a clone of it stops at
    /// its next checkpoint and returns an error. Calling it again has no effect.
    pub fn cancel(&self) {
        self.0.cancel();
    }

    /// Whether [`cancel`](Self::cancel) has been called on this token or a clone.
    pub fn is_cancelled(&self) -> bool {
        self.0.is_cancelled()
    }
}

/// Errors at the document API. Renderer error types do not escape.
#[derive(Debug, thiserror::Error)]
pub enum ReadError {
    /// The bytes are not a PDF this crate can open: damaged beyond recovery,
    /// encrypted with a missing or wrong password, or over a document limit.
    /// The string describes the cause.
    #[error("failed to open PDF document: {0}")]
    Open(String),

    /// The page index is not below [`RenderSession::page_count`].
    #[error("page index {page} is out of range (document has {page_count} pages)")]
    PageOutOfRange {
        /// The zero-based index that was asked for.
        page: u32,
        /// Number of pages in the document.
        page_count: u32,
    },

    /// The page's content could not be interpreted, or the compilation was
    /// cancelled.
    #[error("failed to compile PDF page {page}: {message}")]
    Compile {
        /// Zero-based index of the page.
        page: u32,
        /// What went wrong.
        message: String,
    },
    /// A [`RasterProduct`] that cannot be rendered, such as one with a zero
    /// width or height.
    #[error("invalid raster product: {0}")]
    InvalidRasterProduct(&'static str),

    /// Rendering failed, was cancelled, or hit a render limit. A panic inside
    /// the renderer is caught and reported here.
    #[error("failed to render PDF page {page}: {message}")]
    Render {
        /// Zero-based index of the page.
        page: u32,
        /// What went wrong.
        message: String,
    },
    /// [`ExportOptions`](crate::ExportOptions) that cannot be used, such as a resolution that is zero,
    /// negative, not finite or above 10,000 DPI.
    #[error("invalid export options: {0}")]
    InvalidExportOptions(&'static str),
    /// The page at the requested resolution has more pixels than
    /// [`ExportOptions::max_pixels`](crate::ExportOptions::max_pixels) allows.
    #[error("exporting a {width}x{height} image exceeds the {max_pixels}-pixel budget")]
    ExportTooLarge {
        /// Width the export would have, in pixels.
        width: u32,
        /// Height the export would have, in pixels.
        height: u32,
        /// The budget that was exceeded.
        max_pixels: u64,
    },
    /// The PNG or JPEG encoder rejected the image, for example a JPEG wider or
    /// taller than 65,535 pixels.
    #[error("failed to encode image: {0}")]
    Encode(String),
}

/// Visible page geometry in PDF user space.
///
/// `crop_box` is the visible page and drives every method that does not name
/// a box explicitly — that is what a viewer shows and what this crate has
/// always meant by "the page". The other four boxes are carried for callers
/// that need a different extent (printing to the trim area, prepress); each
/// is clamped to the MediaBox and defaults to the CropBox when the document
/// omits it, so they are always populated and never degenerate on their own.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PageGeometry {
    /// The visible page as `[x0, y0, x1, y1]` in PDF points (1/72 inch), origin
    /// at the bottom left. The other boxes use the same layout.
    pub crop_box: [f64; 4],
    /// The physical sheet the page was authored for.
    pub media_box: [f64; 4],
    /// Trim plus bleed allowance; equals `crop_box` when absent.
    pub bleed_box: [f64; 4],
    /// The finished page after trimming; equals `crop_box` when absent.
    pub trim_box: [f64; 4],
    /// The author-declared meaningful content extent; equals `crop_box` when
    /// absent.
    pub art_box: [f64; 4],
    /// The page's `/Rotate` entry: clockwise degrees, a multiple of 90, applied
    /// when the page is displayed.
    pub rotate: u16,
}

impl PageGeometry {
    /// Width of the *crop* box, before `/Rotate`.
    pub fn width(self) -> f64 {
        (self.crop_box[2] - self.crop_box[0]).max(0.0)
    }

    /// Height of the *crop* box, before `/Rotate`.
    pub fn height(self) -> f64 {
        (self.crop_box[3] - self.crop_box[1]).max(0.0)
    }

    /// Width of the *crop* box as displayed, i.e. after `/Rotate`.
    pub fn display_width(self) -> f64 {
        display_extent(self.width(), self.height(), self.rotate).0
    }

    /// Height of the *crop* box as displayed, i.e. after `/Rotate`.
    pub fn display_height(self) -> f64 {
        display_extent(self.width(), self.height(), self.rotate).1
    }

    /// The displayed `(width, height)` of an arbitrary page box of this page,
    /// i.e. its extent with the page's `/Rotate` applied.
    ///
    /// Callers pick the box — pass one of the fields above — so this crate
    /// needs no opinion about which box a given consumer means.
    /// `display_width`/`display_height` are exactly this applied to
    /// `crop_box`.
    pub fn display_size_of_box(self, b: [f64; 4]) -> (f64, f64) {
        display_extent((b[2] - b[0]).max(0.0), (b[3] - b[1]).max(0.0), self.rotate)
    }
}

/// A page rotated by an odd multiple of 90 degrees is displayed with its axes
/// swapped. Every page-to-device mapping in this crate goes through here so
/// that rule is stated once.
pub(crate) fn display_extent(width: f64, height: f64, rotate: u16) -> (f64, f64) {
    if rotate % 180 == 0 {
        (width, height)
    } else {
        (height, width)
    }
}

/// An immutable compiled page whose renderer representation remains private.
#[derive(Debug, Clone)]
pub struct CompiledDocumentPage {
    page_index: u32,
    raster: Arc<CompiledPage>,
    pub(crate) semantic: Arc<SemanticPage>,
}

impl CompiledDocumentPage {
    /// Zero-based index of the page this was compiled from.
    pub fn page_index(&self) -> u32 {
        self.page_index
    }

    /// Number of drawing operations in the compiled page. Zero means the page
    /// paints nothing.
    pub fn operation_count(&self) -> usize {
        self.raster.operations.len()
    }

    /// The render height at which this page's *bilevel* raster comes out
    /// pixel for pixel: the full-page-equivalent pixel height of the
    /// one-bit image covering the page. `None` for every other page — one
    /// with no image over it, or one whose image carries continuous tone.
    ///
    /// A page that is already black and white holds no more detail at any
    /// scale, and rendering it larger only invents edges: the interpolation
    /// lands differently on each impression of a letter, so shapes that
    /// should match no longer do. A greyscale or colour scan is the
    /// opposite — its soft edges resolve *better* the finer they are
    /// sampled — so it has no ceiling here.
    pub fn bilevel_raster_height(&self) -> Option<u32> {
        bilevel_raster_height(&self.raster)
    }

    /// How faithfully this page renders straight to grayscale, judged from the
    /// features it uses. See [`GraySuitability`].
    pub fn gray_suitability(&self) -> GraySuitability {
        let risky = PageFeatures::TRANSPARENCY
            | PageFeatures::SOFT_MASKS
            | PageFeatures::ICC_COLOR
            | PageFeatures::NONSEPARABLE_BLENDS
            | PageFeatures::OVERPRINT;
        if self.raster.features.intersects(risky) {
            GraySuitability::ColorFallback
        } else if self
            .raster
            .features
            .intersects(PageFeatures::IMAGES | PageFeatures::PATTERNS | PageFeatures::SHADINGS)
        {
            GraySuitability::AcceptableForBilevel
        } else {
            GraySuitability::Exact
        }
    }
}

/// Pixel format requested from a compiled document page.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RasterFormat {
    /// 8-bit RGB: three bytes per pixel, composited over white.
    Rgb8,
    /// 8-bit grayscale: one byte per pixel, composited over white.
    Gray8,
}

/// A rectangle cut out of a full-page raster, in that raster's pixels.
///
/// Pass it to [`RasterProduct::with_crop`] to render one region of a page (a
/// tile, or a zoomed detail) without rendering the rest. The product's `width`
/// and `height` are the output size of the region; when they differ from the
/// crop's own, the region is scaled to fit.
///
/// ```
/// use exprim::{DeviceCrop, RasterProduct};
///
/// // The top-left quarter of a page rendered at 1700 x 2200, at that scale.
/// let crop = DeviceCrop {
///     x: 0,
///     y: 0,
///     width: 850,
///     height: 1100,
///     page_width: 1700,
///     page_height: 2200,
/// };
/// let product = RasterProduct::rgb8(850, 1100).with_crop(crop);
/// assert_eq!(product.crop, Some(crop));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeviceCrop {
    /// Left edge of the region, in pixels from the left of the full-page raster.
    pub x: i32,
    /// Top edge of the region, in pixels from the top of the full-page raster.
    pub y: i32,
    /// Width of the region, in full-page pixels.
    pub width: u32,
    /// Height of the region, in full-page pixels.
    pub height: u32,
    /// Full-page raster size the crop coordinates are expressed in. The render
    /// matrix must scale the page to THIS size before translating by (x, y);
    /// it cannot be inferred from the crop rect (that only works for a crop
    /// anchored at the page's bottom-right corner).
    pub page_width: u32,
    /// Height of that full-page raster.
    pub page_height: u32,
}

/// One final-size raster requested by a document processing pipeline.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RasterProduct {
    /// Output width in pixels.
    pub width: u32,
    /// Output height in pixels.
    pub height: u32,
    /// Pixel format of the output.
    pub format: RasterFormat,
    /// Render only this region of the page. `None` renders the whole page,
    /// scaled to fill `width` x `height`.
    pub crop: Option<DeviceCrop>,
    /// Decode images at no less than the resolution this full-page raster
    /// needs; see [`DecodeReference`]. `None`: each image decodes for its own
    /// footprint on this product.
    pub decode_reference: Option<DecodeReference>,
}

/// A whole-page raster size whose image footprints set the lowest resolution
/// a product's images are decoded at.
///
/// JPEG and JPEG 2000 images decode a minified draw at a reduced resolution
/// chosen from its footprint, so products of one page rendered at different
/// sizes would each decode the page's scan at their own resolution. Products
/// that name the same reference decode each image once, at the reference's
/// resolution, and render from those same pixels; a product larger than the
/// reference still decodes at its own. Which resolution is decoded follows
/// from the product alone, never from what was rendered or cached before.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodeReference {
    /// Width of the full, uncropped page raster.
    pub width: u32,
    /// Height of the full, uncropped page raster.
    pub height: u32,
}

impl RasterProduct {
    /// A whole-page RGB raster of `width` x `height` pixels.
    ///
    /// The page is scaled to fill the raster exactly, so choose a size with the
    /// page's aspect ratio; [`RenderSession::page_pixel_size`] gives one for a
    /// resolution in DPI.
    pub fn rgb8(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            format: RasterFormat::Rgb8,
            crop: None,
            decode_reference: None,
        }
    }

    /// A whole-page grayscale raster of `width` x `height` pixels. Sizing works as
    /// for [`rgb8`](Self::rgb8).
    pub fn gray8(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            format: RasterFormat::Gray8,
            crop: None,
            decode_reference: None,
        }
    }

    /// Render only `crop` instead of the whole page. See [`DeviceCrop`].
    pub fn with_crop(mut self, crop: DeviceCrop) -> Self {
        self.crop = Some(crop);
        self
    }

    /// Decode this product's images at no less than a `width` x `height`
    /// rendering of the whole page needs (see [`DecodeReference`]).
    pub fn with_decode_reference(mut self, width: u32, height: u32) -> Self {
        self.decode_reference = Some(DecodeReference { width, height });
        self
    }
}

/// Whether rendering a page straight to grayscale matches rendering it in
/// colour and converting afterwards.
///
/// Reported by [`CompiledDocumentPage::gray_suitability`] from the features
/// the page uses, without rendering it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraySuitability {
    /// The page has only plain fills, strokes and text. A direct grayscale
    /// render is equivalent.
    Exact,
    /// The page has images, patterns or shadings. A direct grayscale render can
    /// differ slightly, which does not matter when the result is thresholded to
    /// black and white.
    AcceptableForBilevel,
    /// The page uses transparency, soft masks, ICC colour, non-separable blend
    /// modes or overprint. Render in colour and convert.
    ColorFallback,
}

/// The raster a pipeline inspects to decide how to process a page. Part of a
/// [`PageOutputPlan`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalysisTarget {
    /// The raster to render.
    pub product: RasterProduct,
}

/// The main raster of a page in a [`PageOutputPlan`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BaseTarget {
    /// The raster to render.
    pub product: RasterProduct,
    /// The page's grayscale suitability, recorded by the planner for later
    /// stages.
    pub gray_suitability: GraySuitability,
}

/// One extra region of a page in a [`PageOutputPlan`], usually a crop at its
/// own resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegionTarget {
    /// The raster to render.
    pub product: RasterProduct,
}

/// The raster of a page handed to text recognition. Part of a
/// [`PageOutputPlan`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OcrTarget {
    /// The raster to render.
    pub product: RasterProduct,
}

/// Every raster a processing pipeline wants from one page, rendered together
/// by [`RenderSession::render_output_plan`].
///
/// Most callers need only [`RenderSession::render`] or
/// [`RenderSession::export_page`]. A plan is for pipelines that take several
/// products from the same compiled page.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PageOutputPlan {
    /// Raster for analysis, if the pipeline wants one. It is carried for the
    /// caller: `render_output_plan` does not render it.
    pub analysis: Option<AnalysisTarget>,
    /// The main page raster.
    pub base: BaseTarget,
    /// Extra regions, rendered in this order.
    pub regions: Vec<RegionTarget>,
    /// Raster for text recognition, if wanted.
    pub ocr: Option<OcrTarget>,
}

/// An owned 8-bit RGB raster: three bytes per pixel, rows top to bottom, no
/// alpha. Cloning shares the pixel buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RgbSurface {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// Bytes from the start of one row to the start of the next: `width * 3`.
    pub stride: usize,
    /// Pixel bytes; row `y` starts at `y * stride`. From
    /// [`RenderSession::render`] this is exactly `stride * height` bytes;
    /// from [`RenderSession::render_in_place`] it is longer (see there), so
    /// read it through [`as_bytes`](Self::as_bytes) or row by row.
    pub pixels: Arc<[u8]>,
}

impl RgbSurface {
    /// The pixel bytes: exactly `stride * height` of them, whichever render
    /// call produced the surface.
    pub fn as_bytes(&self) -> &[u8] {
        let len = self.stride.saturating_mul(self.height as usize);
        self.pixels.get(..len).unwrap_or(&self.pixels)
    }
}

/// An owned 8-bit grayscale raster: one byte per pixel, rows top to bottom.
/// Cloning shares the pixel buffer.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraySurface {
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
    /// Bytes from the start of one row to the start of the next. At least
    /// `width`; a row may carry padding after its pixels.
    pub stride: usize,
    /// Pixel bytes; row `y` starts at `y * stride`.
    pub pixels: Arc<[u8]>,
}

/// Host raster owned by this API. Renderer surface types do not leave this crate.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RasterPlane {
    /// An RGB raster, from a product with [`RasterFormat::Rgb8`].
    Rgb8(RgbSurface),
    /// A grayscale raster, from a product with [`RasterFormat::Gray8`].
    Gray8(GraySurface),
}

/// One rendered region of a [`PageOutputPlan`], with the target it was
/// rendered for.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedRegion {
    /// The plan entry this raster answers.
    pub target: RegionTarget,
    /// The rendered pixels.
    pub plane: RasterPlane,
}

/// The rasters [`RenderSession::render_output_plan`] produced for one page.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PageRasterProducts {
    /// The main page raster.
    pub base: RasterPlane,
    /// The plan's regions, in plan order.
    pub regions: Vec<RenderedRegion>,
    /// The raster for text recognition, when the plan asked for one.
    pub ocr: Option<RasterPlane>,
}

/// Which decoded JBIG2 sample value the output stencil must paint. An image
/// `/SMask` uses 1 as opaque, while `/ImageMask` uses 0 as paint, so the usual
/// source `/Decode [0 1]` becomes an output stencil `/Decode [1 0]`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Jbig2StencilPolarity {
    /// Samples of 0 are painted.
    PaintZero,
    /// Samples of 1 are painted.
    PaintOne,
}

/// Source-preserving foreground text plane for a conservatively qualified MRC
/// page. Encoded bytes stay authoritative; `working_coverage` is a separate
/// area-averaged opacity plane on the target grid, used only by processing
/// and analysis.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreservedJbig2Smask {
    /// The mask's embedded JBIG2 stream, as stored in the PDF.
    pub page_data: Arc<[u8]>,
    /// The stream's `/JBIG2Globals` data. Empty when it has none.
    pub global_data: Arc<[u8]>,
    /// Width of the mask in its own pixels.
    pub native_width: u32,
    /// Height of the mask in its own pixels.
    pub native_height: u32,
    /// Which sample value paints when the stream is written back as a stencil.
    pub stencil_polarity: Jbig2StencilPolarity,
    /// The mask's opacity resampled to the requested target size.
    pub working_coverage: GraySurface,
}

/// Memory bounds of one [`RenderSession`]. Every open document has its own
/// caches, so a host that keeps many documents open divides its allowance
/// among them here; the defaults suit one document at a time. A smaller bound
/// costs recompiling, decoding or rasterizing again, never different output.
///
/// ```
/// let mut options = exprim::SessionOptions::default();
/// options.image_cache_bytes = 16 << 20;
/// options.cached_pages = 2;
/// ```
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SessionOptions {
    /// Compiled pages retained (8). Zero disables retention.
    pub cached_pages: usize,
    /// Bytes the retained compiled pages may hold together (256 MiB): mostly
    /// their image samples and encoded image payloads. The most recent page
    /// is kept whatever its size.
    pub cached_page_bytes: usize,
    /// Decoded-image cache (96 MiB).
    pub image_cache_bytes: usize,
    /// Parsed-font cache (48 MiB).
    pub font_cache_bytes: usize,
    /// Rendered-glyph cache (32 MiB).
    pub glyph_cache_bytes: usize,
    /// Finished page buffers kept for reuse (256 MiB).
    pub surface_pool_bytes: usize,
    /// Size of the strips a large page is rendered in (32 MiB of working
    /// surface; 0 renders every page in one pass). A page whose working
    /// surface would be more than twice this is rendered strip by strip into
    /// its output buffer, so the render holds the output plus one strip
    /// instead of the output plus the whole surface. Smaller strips hold
    /// less and take longer.
    pub strip_bytes: usize,
}

impl Default for SessionOptions {
    fn default() -> Self {
        Self {
            cached_pages: 8,
            cached_page_bytes: 256 << 20,
            image_cache_bytes: 96 << 20,
            font_cache_bytes: 48 << 20,
            glyph_cache_bytes: 32 << 20,
            surface_pool_bytes: 256 << 20,
            strip_bytes: crate::render_cpu::default_strip_target_bytes(),
        }
    }
}

/// What a retained compiled page weighs against
/// [`SessionOptions::cached_page_bytes`]: the raster IR (image samples and
/// payloads above all) plus the semantic page's own op and text tables. The
/// two share paths, image data and font programs, which are counted once.
fn retained_page_bytes(page: &CompiledDocumentPage) -> usize {
    let semantic = &page.semantic;
    page.raster
        .approx_retained_bytes()
        .saturating_add(semantic.ops.len() * std::mem::size_of::<crate::content::SemanticOp>())
        .saturating_add(semantic.text_runs.len() * std::mem::size_of::<crate::content::TextRun>())
}

/// Per-document immutable renderer state.
#[derive(Debug)]
pub struct RenderSession {
    id: u64,
    pub(crate) snapshot: Arc<DocumentSnapshot>,
    pub(crate) compiler: Arc<PageCompiler>,
    // Constructed once per document now so Phase 3 does not accidentally
    // create page-local font, glyph, and decoded-image caches.
    backend: Arc<CpuBackend>,
    pages: PageCache<CompiledDocumentPage>,
    workers: WorkerPool,
    /// Timing detail applied to every worker a profiled render checks out.
    #[cfg(feature = "profiling")]
    profile_detail: std::sync::Mutex<crate::profiling::ProfileDetail>,
}

impl RenderSession {
    /// Open a PDF held in memory.
    ///
    /// `password` is the user or owner password of an encrypted document; pass
    /// `None` otherwise. Opening parses the document structure only. Pages are
    /// interpreted when first compiled, and up to eight compiled pages are kept
    /// (see [`open_with_cache_capacity`](Self::open_with_cache_capacity)).
    ///
    /// A session is `Send` and `Sync`: share it by reference or in an `Arc` and
    /// render different pages from different threads.
    ///
    /// # Errors
    ///
    /// [`ReadError::Open`] when the bytes cannot be opened as a PDF, including a
    /// missing or wrong password. [`examine_document`](crate::examine_document) tells those cases apart
    /// without failing.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use std::sync::Arc;
    ///
    /// let bytes: Arc<[u8]> = std::fs::read("document.pdf")?.into();
    /// let session = exprim::RenderSession::open(bytes, None)?;
    /// println!("{} pages", session.page_count());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open(bytes: Arc<[u8]>, password: Option<&str>) -> Result<Self, ReadError> {
        Self::open_with_cache_capacity(bytes, password, 8)
    }

    /// Open with a bound on retained page compilations (eight by default).
    /// Each entry owns semantic and raster IR together. Zero disables retention;
    /// caller-held page handles remain valid after eviction. The retained
    /// pages are also bounded in bytes (see [`SessionOptions`]).
    pub fn open_with_cache_capacity(
        bytes: Arc<[u8]>,
        password: Option<&str>,
        cached_pages: usize,
    ) -> Result<Self, ReadError> {
        Self::open_source_with_cache_capacity(source(bytes), password, cached_pages)
    }

    /// Open a PDF file by memory-mapping it, so the document's bytes are paged
    /// in on demand and can be dropped by the operating system under pressure
    /// instead of sitting on the heap for the life of the session
    /// ([`open`](Self::open) keeps the whole file in memory, and reading it
    /// into an `Arc<[u8]>` first copies it once more).
    ///
    /// The file must not be truncated or rewritten in place while the session
    /// is open. Replace it by renaming a new file over it instead.
    ///
    /// # Errors
    ///
    /// [`ReadError::Open`] when the file cannot be mapped or is not a PDF this
    /// crate can open.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// let session = exprim::RenderSession::open_path("document.pdf", None)?;
    /// println!("{} pages", session.page_count());
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn open_path(
        path: impl AsRef<std::path::Path>,
        password: Option<&str>,
    ) -> Result<Self, ReadError> {
        let mapped = crate::source::MmapSource::open(path)
            .map_err(|error| ReadError::Open(error.to_string()))?;
        Self::open_source(Arc::new(mapped), password)
    }

    /// Open a PDF from any byte source: a memory map, positional file reads,
    /// or bytes the caller already holds.
    ///
    /// # Errors
    ///
    /// [`ReadError::Open`] as for [`open`](Self::open).
    pub fn open_source(
        source: Arc<dyn crate::source::PdfSource>,
        password: Option<&str>,
    ) -> Result<Self, ReadError> {
        Self::open_source_with_options(source, password, &SessionOptions::default())
    }

    /// [`open_source`](Self::open_source) with explicit memory bounds.
    pub fn open_source_with_options(
        source: Arc<dyn crate::source::PdfSource>,
        password: Option<&str>,
        options: &SessionOptions,
    ) -> Result<Self, ReadError> {
        let snapshot =
            DocumentSnapshot::open_with_password(source, DocumentLimits::default(), password)
                .map_err(|error| ReadError::Open(error.to_string()))?;
        let backend = CpuBackend::new(CpuBackendOptions::default())
            .with_cache_bytes(
                options.image_cache_bytes,
                options.font_cache_bytes,
                options.glyph_cache_bytes,
            )
            .with_surface_pool_bytes(options.surface_pool_bytes)
            .with_strip_target_bytes(options.strip_bytes);

        Ok(Self {
            id: NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed),
            snapshot: Arc::new(snapshot),
            compiler: Arc::new(PageCompiler::new().with_annotations(true)),
            backend: Arc::new(backend),
            pages: PageCache::with_byte_budget(
                options.cached_pages,
                options.cached_page_bytes,
                retained_page_bytes,
            ),
            workers: WorkerPool::default(),
            #[cfg(feature = "profiling")]
            profile_detail: std::sync::Mutex::new(crate::profiling::ProfileDetail::default()),
        })
    }

    /// [`open_source`](Self::open_source) with a bound on retained page
    /// compilations (see [`open_with_cache_capacity`](Self::open_with_cache_capacity)).
    pub fn open_source_with_cache_capacity(
        source: Arc<dyn crate::source::PdfSource>,
        password: Option<&str>,
        cached_pages: usize,
    ) -> Result<Self, ReadError> {
        let options = SessionOptions {
            cached_pages,
            ..SessionOptions::default()
        };
        Self::open_source_with_options(source, password, &options)
    }

    /// Drop everything the decoded-image, parsed-font and glyph caches hold.
    /// With [`clear_page_cache`](Self::clear_page_cache) and
    /// [`release_idle_memory`](Self::release_idle_memory) this returns an
    /// open but idle document to little more than its parsed structure.
    /// Later renders decode, parse and rasterize again, to the same bytes.
    pub fn clear_resource_caches(&self) {
        self.backend.clear_resource_caches();
    }

    /// Bytes the retained compiled pages weigh against
    /// [`SessionOptions::cached_page_bytes`].
    pub fn cached_page_bytes(&self) -> usize {
        self.pages.retained_bytes()
    }

    /// Give back memory the session keeps only to make the next job faster:
    /// the parser caches and raster scratch of idle workers, and page buffers
    /// held for reuse. Compiled pages and the font, glyph and image caches
    /// stay (see [`clear_page_cache`](Self::clear_page_cache) for the former);
    /// work in flight is unaffected. Output never depends on this.
    pub fn release_idle_memory(&self) {
        self.workers.clear();
        self.backend.release_idle_memory();
    }

    /// Bytes of finished page buffers the session currently keeps for reuse
    /// (at most 256 MiB; [`release_idle_memory`](Self::release_idle_memory)
    /// drops them).
    pub fn idle_surface_bytes(&self) -> usize {
        self.backend.idle_surface_bytes()
    }

    /// Distinguishes this session from every other one in the process.
    pub(crate) fn id(&self) -> u64 {
        self.id
    }

    /// Number of pages in the document.
    pub fn page_count(&self) -> u32 {
        self.snapshot.page_count()
    }

    /// The page boxes and rotation of `page` (zero-based), read from the page
    /// dictionary without interpreting its content.
    ///
    /// # Errors
    ///
    /// [`ReadError::PageOutOfRange`] when `page` is not below
    /// [`page_count`](Self::page_count).
    pub fn page_geometry(&self, page: u32) -> Result<PageGeometry, ReadError> {
        let page_ref = self
            .snapshot
            .page(PageIndex(page))
            .map_err(|_| self.page_out_of_range(page))?;
        Ok(PageGeometry {
            crop_box: page_ref.crop_box,
            media_box: page_ref.media_box,
            bleed_box: page_ref.bleed_box,
            trim_box: page_ref.trim_box,
            art_box: page_ref.art_box,
            rotate: page_ref.rotate,
        })
    }

    /// Interpret `page` (zero-based) and return a handle that can be rendered at
    /// any size, any number of times.
    ///
    /// The result is cached in the session, so compiling the same page again is
    /// cheap, and the text functions ([`page_text`](crate::page_text) and the
    /// rest) reuse the same compilation. This is
    /// [`compile_cancellable`](Self::compile_cancellable) without a token.
    ///
    /// # Errors
    ///
    /// [`ReadError::PageOutOfRange`] for a bad index and [`ReadError::Compile`]
    /// when the page cannot be interpreted. A failure affects that page only.
    pub fn compile(&self, page: u32) -> Result<Arc<CompiledDocumentPage>, ReadError> {
        self.compile_cancellable(page, None)
    }

    /// Compile semantic and raster artifacts in one interpretation, or reuse a
    /// retained result. Concurrent requests for the same page share the work;
    /// different pages compile independently. Cancelled work is not retained.
    pub fn compile_cancellable(
        &self,
        page: u32,
        cancellation: Option<&CancellationToken>,
    ) -> Result<Arc<CompiledDocumentPage>, ReadError> {
        if page >= self.page_count() {
            return Err(self.page_out_of_range(page));
        }
        self.pages.get_or_compile(page, cancellation, || {
            let artifacts = self
                .workers
                .with(|worker| {
                    worker.parse.begin_job();
                    worker
                        .parse
                        .set_cancellation_flag(cancellation.map(|token| token.0.shared_flag()));
                    let result = self.compiler.compile_artifacts(
                        &self.snapshot,
                        PageIndex(page),
                        &mut worker.parse,
                    );
                    worker.parse.set_cancellation_flag(None);
                    result
                })
                .map_err(|error| ReadError::Compile {
                    page,
                    message: error.to_string(),
                })?;
            Ok(Arc::new(CompiledDocumentPage {
                page_index: page,
                raster: artifacts.compiled,
                semantic: artifacts.semantic,
            }))
        })
    }

    /// Evict retained semantic and raster artifacts together. Work already in
    /// flight can finish for its caller but will not repopulate this cache.
    /// Renderer resource caches and caller-held handles are unaffected.
    pub fn clear_page_cache(&self) {
        self.pages.clear();
    }

    /// Rasterize a compiled page into `product`.
    ///
    /// The output is composited over white with the page's annotations drawn.
    /// Call it from any thread; each thread keeps its own scratch memory.
    ///
    /// # Errors
    ///
    /// [`ReadError::InvalidRasterProduct`] for a zero-sized product and
    /// [`ReadError::Render`] when rendering fails.
    ///
    /// # Examples
    ///
    /// Render the first page at 150 DPI and read its pixels:
    ///
    /// ```no_run
    /// use exprim::{RasterPlane, RasterProduct, RenderSession};
    /// # let bytes: std::sync::Arc<[u8]> = std::fs::read("document.pdf")?.into();
    ///
    /// let session = RenderSession::open(bytes, None)?;
    /// let page = session.compile(0)?;
    /// let (width, height) = session.page_pixel_size(0, 150.0)?;
    /// let plane = session.render(&page, &RasterProduct::rgb8(width, height))?;
    /// if let RasterPlane::Rgb8(surface) = plane {
    ///     let first_row = &surface.pixels[..surface.width as usize * 3];
    ///     assert_eq!(first_row.len(), width as usize * 3);
    /// }
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn render(
        &self,
        page: &Arc<CompiledDocumentPage>,
        product: &RasterProduct,
    ) -> Result<RasterPlane, ReadError> {
        self.render_cancellable(page, product, None)
    }

    /// [`render`](Self::render) with cooperative cancellation: when the token is
    /// cancelled the render stops at its next checkpoint and returns an error.
    pub fn render_cancellable(
        &self,
        page: &Arc<CompiledDocumentPage>,
        product: &RasterProduct,
        cancellation: Option<&CancellationToken>,
    ) -> Result<RasterPlane, ReadError> {
        self.render_inner(page, product, cancellation, false)
            .map(|(plane, _stats)| plane)
    }

    /// [`render`](Self::render) for a raster that is consumed and dropped
    /// (encoded, printed, analysed), not kept.
    ///
    /// An RGB product is packed inside the surface it was rendered on instead
    /// of into a second buffer, so the render never holds more than four
    /// bytes per pixel, where [`render`](Self::render) holds seven at the
    /// instant it packs (the RGBA surface and the RGB copy) and then keeps the
    /// RGBA surface for reuse. In exchange the returned
    /// [`RgbSurface::pixels`] keeps the surface's length, a third more than
    /// `stride * height`: read it through [`RgbSurface::as_bytes`], and
    /// prefer [`render`](Self::render) for rasters that are retained in
    /// number. The pixels themselves are identical. Gray products are
    /// rendered exactly as by [`render`](Self::render).
    ///
    /// # Errors
    ///
    /// As [`render`](Self::render).
    pub fn render_in_place(
        &self,
        page: &Arc<CompiledDocumentPage>,
        product: &RasterProduct,
    ) -> Result<RasterPlane, ReadError> {
        self.render_in_place_cancellable(page, product, None)
    }

    /// [`render_in_place`](Self::render_in_place) with cooperative
    /// cancellation.
    pub fn render_in_place_cancellable(
        &self,
        page: &Arc<CompiledDocumentPage>,
        product: &RasterProduct,
        cancellation: Option<&CancellationToken>,
    ) -> Result<RasterPlane, ReadError> {
        self.render_inner(page, product, cancellation, true)
            .map(|(plane, _stats)| plane)
    }

    /// [`Self::render`] plus the feature-gated stage report, so benchmark
    /// tooling can attribute the public session path (worker reuse, the
    /// shared caches, and the RGB packing pass) the same way as the low-level
    /// backend path.
    #[cfg(feature = "profiling")]
    pub fn render_profiled(
        &self,
        page: &Arc<CompiledDocumentPage>,
        product: &RasterProduct,
    ) -> Result<(RasterPlane, crate::profiling::ProfileReport), ReadError> {
        let start = std::time::Instant::now();
        let (plane, stats) = self.render_inner(page, product, None, false)?;
        let profile = crate::render_cpu::profile_from_stats(&stats, start.elapsed());
        Ok((plane, profile))
    }

    /// Choose the timing detail of this session's profiled renders (see
    /// `CpuWorkerContext::set_profile_detail`).
    #[cfg(feature = "profiling")]
    pub fn set_profile_detail(&self, detail: crate::profiling::ProfileDetail) {
        *self
            .profile_detail
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner()) = detail;
    }

    fn render_inner(
        &self,
        page: &Arc<CompiledDocumentPage>,
        product: &RasterProduct,
        cancellation: Option<&CancellationToken>,
        in_place: bool,
    ) -> Result<(RasterPlane, crate::render_cpu::RenderStats), ReadError> {
        if product.width == 0 || product.height == 0 {
            return Err(ReadError::InvalidRasterProduct(
                "width and height must both be non-zero",
            ));
        }

        let output_format = match product.format {
            RasterFormat::Rgb8 => OutputFormat::Rgba8PremultipliedSrgb,
            RasterFormat::Gray8 => OutputFormat::Gray8,
        };
        let request = RenderRequest {
            page: Arc::clone(&page.raster),
            transform: PageTransform {
                matrix: product_matrix(&page.raster, product),
            },
            crop: product.crop.map(|crop| DeviceRect {
                x: crop.x,
                y: crop.y,
                width: crop.width,
                height: crop.height,
            }),
            output_size: DeviceSize {
                width: product.width,
                height: product.height,
            },
            output_format,
            background: Background::White,
            color_policy: RenderColorPolicy::Original,
            annotations: AnnotationMode::StaticAppearances,
            quality: RenderQuality::Normal,
            limits: render_limits(cancellation),
            residency: OutputResidency::HostRequired,
        };
        let options = render_options(&page.raster, product);
        let rgb = product.format == RasterFormat::Rgb8;

        let rendered = catch_unwind(AssertUnwindSafe(|| {
            self.workers.with(|worker| {
                #[cfg(feature = "profiling")]
                worker.raster.set_profile_detail(
                    *self
                        .profile_detail
                        .lock()
                        .unwrap_or_else(|poisoned| poisoned.into_inner()),
                );
                if rgb {
                    // The backend drops the alpha byte itself: inside the
                    // surface for an in-place render, into a buffer of the
                    // exact length otherwise, and strip by strip for a large
                    // page either way. Rewrapped as a host page for the
                    // shared checks below; its stride says three bytes per
                    // pixel.
                    let rendered = if in_place {
                        self.backend.render_packed_rgb_with_options(
                            &request,
                            &options,
                            &mut worker.raster,
                        )
                    } else {
                        self.backend
                            .render_rgb_with_options(&request, &options, &mut worker.raster)
                    };
                    rendered.map(|(packed, stats)| {
                        (
                            HostPage {
                                width: packed.width,
                                height: packed.height,
                                stride: packed.stride,
                                format: output_format,
                                pixels: packed.pixels,
                            },
                            stats,
                        )
                    })
                } else {
                    self.backend
                        .render_with_options(&request, &options, &mut worker.raster)
                }
            })
        }))
        .map_err(|payload| ReadError::Render {
            page: page.page_index,
            message: format!(
                "renderer panicked: {}",
                crate::render_api::panic_message(payload)
            ),
        })?
        .map_err(|error| ReadError::Render {
            page: page.page_index,
            message: error.to_string(),
        })?;
        let (rendered, stats) = rendered;
        if rendered.format != output_format {
            return Err(ReadError::Render {
                page: page.page_index,
                message: format!(
                    "renderer returned {:?} for a {:?} request",
                    rendered.format, output_format
                ),
            });
        }

        match product.format {
            RasterFormat::Gray8 => Ok((
                RasterPlane::Gray8(GraySurface {
                    width: rendered.width,
                    height: rendered.height,
                    stride: rendered.stride,
                    pixels: rendered.pixels,
                }),
                stats,
            )),
            RasterFormat::Rgb8 => Ok((
                RasterPlane::Rgb8(RgbSurface {
                    width: rendered.width,
                    height: rendered.height,
                    stride: rendered.stride,
                    pixels: rendered.pixels,
                }),
                stats,
            )),
        }
    }

    /// Render the base raster, every region and the text-recognition raster of
    /// `plan` from one compiled page, in that order. The first error ends the
    /// call.
    pub fn render_output_plan(
        &self,
        page: &Arc<CompiledDocumentPage>,
        plan: &PageOutputPlan,
        cancellation: Option<&CancellationToken>,
    ) -> Result<PageRasterProducts, ReadError> {
        let base = self.render_cancellable(page, &plan.base.product, cancellation)?;
        let regions = plan
            .regions
            .iter()
            .map(|target| {
                Ok(RenderedRegion {
                    target: target.clone(),
                    plane: self.render_cancellable(page, &target.product, cancellation)?,
                })
            })
            .collect::<Result<Vec<_>, ReadError>>()?;
        let ocr = plan
            .ocr
            .as_ref()
            .map(|target| self.render_cancellable(page, &target.product, cancellation))
            .transpose()?;
        Ok(PageRasterProducts { base, regions, ocr })
    }

    /// Return the native JBIG2 `/SMask` payload plus a target-grid working
    /// opacity plane when this compiled page matches the strict MRC shape (a JBIG2 mask over a picture layer).
    /// Any structural or decode mismatch is a normal `None` and leaves the
    /// caller free to run the existing raster/binarization path for that page.
    pub fn preserved_jbig2_smask(
        &self,
        page: &Arc<CompiledDocumentPage>,
        target_width: u32,
        target_height: u32,
        cancellation: Option<&CancellationToken>,
    ) -> Result<Option<PreservedJbig2Smask>, ReadError> {
        if target_width == 0 || target_height == 0 {
            return Err(ReadError::InvalidRasterProduct(
                "preserved mask target dimensions must be non-zero",
            ));
        }
        let Some(candidate) = qualifying_jbig2_smask(&page.raster) else {
            return Ok(None);
        };
        let decoded = self
            .backend
            .decode_bilevel_jbig2_smask(&candidate.smask, &render_limits(cancellation))
            .map_err(|error| ReadError::Render {
                page: page.page_index,
                message: format!("JBIG2 SMask decode failed: {error}"),
            })?;
        let Some(decoded) = decoded else {
            return Ok(None);
        };
        let working_coverage = resize_smask_coverage(decoded, target_width, target_height)
            .ok_or_else(|| ReadError::Render {
                page: page.page_index,
                message: "JBIG2 SMask decoder returned a truncated opacity plane".to_string(),
            })?;
        Ok(Some(PreservedJbig2Smask {
            page_data: candidate.page_data,
            global_data: candidate
                .smask
                .codec_parms
                .as_ref()
                .and_then(|parms| parms.jbig2_globals.clone())
                .unwrap_or_else(|| Arc::from([])),
            native_width: candidate.smask.width,
            native_height: candidate.smask.height,
            stencil_polarity: candidate.stencil_polarity,
            working_coverage,
        }))
    }

    fn page_out_of_range(&self, page: u32) -> ReadError {
        ReadError::PageOutOfRange {
            page,
            page_count: self.page_count(),
        }
    }
}

fn render_limits(cancellation: Option<&CancellationToken>) -> RenderLimits {
    RenderLimits {
        cancellation: cancellation.map(|token| token.0.clone()),
        ..RenderLimits::default()
    }
}

/// Resample a 0/255 opacity plane onto the target grid by exact area
/// averaging: each target pixel is the coverage of the source region it
/// spans, with the fractional edge rows and columns weighted by their
/// overlap. That is what a coverage plane means, so there is no ringing and
/// no overshoot, and the separable integer passes cost about a tenth of the
/// Lanczos3 resize this replaced (which was the whole preserved-mask probe
/// on a 6 Mpx page).
fn resize_smask_coverage(
    decoded: DecodedBilevelSmask,
    target_width: u32,
    target_height: u32,
) -> Option<GraySurface> {
    let (source_width, source_height) = (decoded.width as usize, decoded.height as usize);
    if decoded.stride != source_width
        || source_width == 0
        || source_height == 0
        || target_width == 0
        || target_height == 0
    {
        return None;
    }
    let source = decoded.opacity.get(..source_width * source_height)?;
    if (target_width as usize, target_height as usize) == (source_width, source_height) {
        return Some(GraySurface {
            width: target_width,
            height: target_height,
            stride: source_width,
            pixels: Arc::clone(&decoded.opacity),
        });
    }
    let (tw, th) = (target_width as usize, target_height as usize);
    let columns = coverage_spans(source_width, tw);
    let rows = coverage_spans(source_height, th);

    // Horizontal pass: per source row, the weighted column sums. Weights are
    // in units of 1/tw source pixel and add up to `source_width` per target
    // column, so the sum stays below 255 * source_width.
    let mut horizontal = vec![0u32; source_height * tw];
    for (source_row, sums) in source
        .chunks_exact(source_width)
        .zip(horizontal.chunks_exact_mut(tw))
    {
        for (sum, span) in sums.iter_mut().zip(&columns) {
            *sum = span
                .taps()
                .map(|(i, weight)| weight * u32::from(source_row[i]))
                .sum();
        }
    }
    // Vertical pass: the same over the row sums, then one exact rounded
    // divide by the pixel's full source area.
    let denominator = (source_width * source_height) as u64;
    let mut pixels = vec![0u8; tw * th];
    for (out_row, span) in pixels.chunks_exact_mut(tw).zip(&rows) {
        for (x, out) in out_row.iter_mut().enumerate() {
            let sum: u64 = span
                .taps()
                .map(|(i, weight)| u64::from(weight) * u64::from(horizontal[i * tw + x]))
                .sum();
            *out = ((sum + denominator / 2) / denominator).min(255) as u8;
        }
    }
    Some(GraySurface {
        width: target_width,
        height: target_height,
        stride: tw,
        pixels: Arc::from(pixels),
    })
}

/// The source pixels one target pixel spans along an axis, with each tap's
/// overlap in units of 1/`target` source pixel. Target pixel `j` covers the
/// source interval `[j*source/target, (j+1)*source/target)`; measured in
/// those units it is `[j*source, (j+1)*source)` and source pixel `i` is
/// `[i*target, (i+1)*target)`, so every overlap is an exact integer and the
/// weights of one span add up to `source`.
#[derive(Clone, Copy)]
struct CoverageSpan {
    first: usize,
    last: usize,
    first_weight: u32,
    last_weight: u32,
    interior_weight: u32,
}

impl CoverageSpan {
    fn taps(&self) -> impl Iterator<Item = (usize, u32)> + '_ {
        (self.first..=self.last).map(move |i| {
            let weight = if self.first == self.last {
                self.first_weight
            } else if i == self.first {
                self.first_weight
            } else if i == self.last {
                self.last_weight
            } else {
                self.interior_weight
            };
            (i, weight)
        })
    }
}

fn coverage_spans(source: usize, target: usize) -> Vec<CoverageSpan> {
    (0..target)
        .map(|j| {
            let start = j * source;
            let end = (j + 1) * source;
            let first = start / target;
            let last = ((end - 1) / target).min(source - 1);
            let overlap = |i: usize| -> u32 {
                let lo = start.max(i * target);
                let hi = end.min((i + 1) * target);
                hi.saturating_sub(lo) as u32
            };
            CoverageSpan {
                first,
                last,
                first_weight: overlap(first),
                last_weight: overlap(last),
                interior_weight: target as u32,
            }
        })
        .collect()
}

#[derive(Clone)]
struct Jbig2SmaskCandidate {
    smask: Arc<ImageSMask>,
    /// The non-empty JBIG2 page stream taken from `smask`. Carrying it here
    /// makes "qualified" and "has a usable payload" one fact instead of two.
    page_data: Arc<[u8]>,
    stencil_polarity: Jbig2StencilPolarity,
}

fn qualifying_jbig2_smask(page: &CompiledPage) -> Option<Jbig2SmaskCandidate> {
    if page.bounds.rotate != 0 {
        return None;
    }
    let mut ctm = Matrix::IDENTITY;
    let mut stack = Vec::new();
    let mut candidate = None;
    let mut image_draws = 0usize;

    for op in page.operations.iter() {
        match op {
            DisplayOp::Save => stack.push(ctm),
            DisplayOp::Restore => ctm = stack.pop()?,
            DisplayOp::ConcatTransform(matrix) => ctm = matrix.then(ctm),
            DisplayOp::BeginPaintOrigin(_) | DisplayOp::EndPaintOrigin => {}
            // Render mode 3 is invisible text, the searchable layer a scanner
            // lays over the page image. It leaves no ink, so it cannot disturb
            // the preserved mask; every other glyph run hits the reject arm.
            DisplayOp::DrawGlyphRun { run, .. }
                if page.glyph_runs.get(run.index())?.render_mode == 3 => {}
            DisplayOp::DrawImage {
                image,
                transform,
                alpha,
                blend,
                ..
            } => {
                image_draws += 1;
                let image = page.images.get(image.index())?;
                let placement = transform.then(ctm);
                if *blend != BlendMode::Normal
                    || (*alpha - 1.0).abs() > f32::EPSILON
                    || !is_unflipped_full_page(placement, page, image.width, image.height)
                    || image.is_stencil
                    || image.lowering_degraded
                    || image.mask.is_some()
                    || image.smask_in_data != 0
                {
                    return None;
                }
                if let Some(smask) = image.smask.as_ref() {
                    if candidate.is_some()
                        || smask.width != image.width
                        || smask.height != image.height
                        || smask.bits_per_component != 1
                        || smask.codec != Some(ImageCodecKind::Jbig2)
                        || !smask.samples.is_empty()
                    {
                        return None;
                    }
                    let page_data = smask.codec_data.clone().filter(|data| !data.is_empty())?;
                    let stencil_polarity = match smask.decode.as_deref() {
                        None => Jbig2StencilPolarity::PaintOne,
                        Some([[lo, hi]]) if *lo == 0.0 && *hi == 1.0 => {
                            Jbig2StencilPolarity::PaintOne
                        }
                        Some([[lo, hi]]) if *lo == 1.0 && *hi == 0.0 => {
                            Jbig2StencilPolarity::PaintZero
                        }
                        _ => return None,
                    };
                    candidate = Some(Jbig2SmaskCandidate {
                        smask: Arc::clone(smask),
                        page_data: Arc::from(page_data.as_slice()),
                        stencil_polarity,
                    });
                }
            }
            _ => return None,
        }
    }
    if !stack.is_empty() || image_draws == 0 {
        return None;
    }
    candidate
}

/// See [`CompiledDocumentPage::bilevel_raster_height`]. An image counts when
/// it covers at least this share of the page's shorter side in both axes: a
/// scan covers the page, a logo or a figure does not.
const PAGE_IMAGE_COVERAGE: f64 = 0.6;

fn bilevel_raster_height(page: &CompiledPage) -> Option<u32> {
    let crop = page.bounds.crop;
    let (page_w, page_h) = (crop.width().abs(), crop.height().abs());
    if !(page_w > 0.0 && page_h > 0.0) {
        return None;
    }
    let mut ctm = Matrix::IDENTITY;
    let mut stack = Vec::new();
    let mut ink: Option<u32> = None;
    for op in page.operations.iter() {
        match op {
            DisplayOp::Save => stack.push(ctm),
            DisplayOp::Restore => ctm = stack.pop().unwrap_or(Matrix::IDENTITY),
            DisplayOp::ConcatTransform(matrix) => ctm = matrix.then(ctm),
            DisplayOp::DrawImage {
                image, transform, ..
            } => {
                let Some(image) = page.images.get(image.index()) else {
                    continue;
                };
                let placement = transform.then(ctm);
                if !placement.is_finite() {
                    continue;
                }
                // The unit image square's extent on the page.
                let drawn_w = placement.a.abs() + placement.c.abs();
                let drawn_h = placement.b.abs() + placement.d.abs();
                if drawn_h <= 0.0
                    || drawn_w < page_w * PAGE_IMAGE_COVERAGE
                    || drawn_h < page_h * PAGE_IMAGE_COVERAGE
                {
                    continue;
                }
                // The ink layer: the image itself when it is one bit, else
                // the one-bit mask painted through it. A continuous-tone
                // image with no such mask is not a ceiling — it is a scan,
                // and it resolves better the finer it is sampled.
                let bilevel = if image.is_stencil || image.bits_per_component == 1 {
                    Some((image.width, image.height))
                } else {
                    image
                        .smask
                        .as_ref()
                        .filter(|smask| smask.bits_per_component == 1)
                        .map(|smask| (smask.width, smask.height))
                };
                let Some((width, height)) = bilevel.filter(|(_, height)| *height > 0) else {
                    continue;
                };
                // A quarter-turned placement puts the image's width along the
                // page's height.
                let along_page_height = if placement.b.abs() > placement.d.abs() {
                    width
                } else {
                    height
                };
                let implied = (f64::from(along_page_height) * page_h / drawn_h).round();
                if implied.is_finite() && implied >= 1.0 {
                    let implied = implied as u32;
                    ink = Some(ink.map_or(implied, |n: u32| n.max(implied)));
                }
            }
            _ => {}
        }
    }
    ink
}

fn is_unflipped_full_page(
    matrix: Matrix,
    page: &CompiledPage,
    image_width: u32,
    image_height: u32,
) -> bool {
    if !matrix.is_finite()
        || matrix.a <= 0.0
        || matrix.d <= 0.0
        || matrix.b.abs() > 1e-7
        || matrix.c.abs() > 1e-7
    {
        return false;
    }
    let p0 = matrix.apply(Point { x: 0.0, y: 0.0 });
    let p1 = matrix.apply(Point { x: 1.0, y: 1.0 });
    let crop = page.bounds.crop;
    let numeric_tolerance = (crop.width().abs().max(crop.height().abs()) * 1e-5).max(1e-4);
    // PDF producers commonly place a full-page raster on half-pixel boundaries.
    // That is still the same full-page image, and rejecting it prevents lossless
    // preservation of an otherwise qualifying native JBIG2 soft mask.
    let tolerance_x = numeric_tolerance.max(matrix.a.abs() / f64::from(image_width.max(1)) * 0.5);
    let tolerance_y = numeric_tolerance.max(matrix.d.abs() / f64::from(image_height.max(1)) * 0.5);
    (p0.x - crop.x0).abs() <= tolerance_x
        && (p0.y - crop.y0).abs() <= tolerance_y
        && (p1.x - crop.x1).abs() <= tolerance_x
        && (p1.y - crop.y1).abs() <= tolerance_y
}

fn page_to_device_matrix(page: &CompiledPage, output_width: u32, output_height: u32) -> Matrix {
    let crop = page.bounds.crop;
    let rotation = page.bounds.rotate % 360;
    let (display_width, display_height) = display_extent(crop.width(), crop.height(), rotation);
    let scale_x = output_width as f64 / display_width.max(f64::EPSILON);
    let scale_y = output_height as f64 / display_height.max(f64::EPSILON);

    match rotation {
        90 => Matrix {
            a: 0.0,
            b: scale_y,
            c: scale_x,
            d: 0.0,
            e: -crop.y0 * scale_x,
            f: -crop.x0 * scale_y,
        },
        180 => Matrix {
            a: -scale_x,
            b: 0.0,
            c: 0.0,
            d: scale_y,
            e: crop.x1 * scale_x,
            f: -crop.y0 * scale_y,
        },
        270 => Matrix {
            a: 0.0,
            b: -scale_y,
            c: -scale_x,
            d: 0.0,
            e: crop.y1 * scale_x,
            f: crop.x1 * scale_y,
        },
        _ => Matrix {
            a: scale_x,
            b: 0.0,
            c: 0.0,
            d: -scale_y,
            e: -crop.x0 * scale_x,
            f: crop.y1 * scale_y,
        },
    }
}

/// The renderer policy for one product: its decode reference, as the
/// transform of the whole page onto the reference raster. A zero-sized
/// reference names no raster and is ignored.
fn render_options(page: &CompiledPage, product: &RasterProduct) -> CpuRenderOptions {
    CpuRenderOptions {
        image_decode_reference: product
            .decode_reference
            .filter(|reference| reference.width > 0 && reference.height > 0)
            .map(|reference| PageTransform {
                matrix: page_to_device_matrix(page, reference.width, reference.height),
            }),
    }
}

fn product_matrix(page: &CompiledPage, product: &RasterProduct) -> Matrix {
    let Some(crop) = product.crop else {
        return page_to_device_matrix(page, product.width, product.height);
    };
    let mut matrix = page_to_device_matrix(page, crop.page_width.max(1), crop.page_height.max(1));
    let sx = product.width as f64 / crop.width.max(1) as f64;
    let sy = product.height as f64 / crop.height.max(1) as f64;
    matrix.a *= sx;
    matrix.c *= sx;
    matrix.e = (matrix.e - crop.x as f64) * sx;
    matrix.b *= sy;
    matrix.d *= sy;
    matrix.f = (matrix.f - crop.y as f64) * sy;
    matrix
}

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

    use super::*;
    use crate::page_ir::{
        CodecParms, ImageColorSpace, ImageId, ImageIr, InterpolationMode, PageBounds, PaintId,
        Rect, ResourceKey,
    };

    fn eligible_page() -> CompiledPage {
        let smask = Arc::new(ImageSMask {
            width: 12,
            height: 5,
            bits_per_component: 1,
            decode: None,
            samples: Arc::from([]),
            codec: Some(ImageCodecKind::Jbig2),
            codec_data: Some((&b"encoded mask"[..]).into()),
            codec_parms: Some(CodecParms {
                jbig2_globals: Some(Arc::from(&b"encoded globals"[..])),
                ..CodecParms::default()
            }),
        });
        let image = ImageIr {
            key: ResourceKey {
                object_number: 1,
                generation: 0,
                variant: 0,
            },
            width: 12,
            height: 5,
            is_stencil: false,
            interpolation: InterpolationMode::Nearest,
            soft_mask: None,
            bits_per_component: 8,
            color_space: ImageColorSpace::Gray,
            decode: None,
            samples: Some(Arc::from(&b"base"[..])),
            codec: None,
            codec_data: None,
            codec_parms: None,
            smask: Some(smask),
            mask: None,
            smask_in_data: 0,
            lowering_degraded: false,
        };
        let mut page = CompiledPage::empty(PageBounds {
            crop: Rect {
                x0: 0.0,
                y0: 0.0,
                x1: 120.0,
                y1: 50.0,
            },
            rotate: 0,
        });
        page.images = Arc::from([image]);
        page.operations = Arc::from([
            DisplayOp::Save,
            DisplayOp::ConcatTransform(Matrix::scale(120.0, 50.0)),
            DisplayOp::DrawImage {
                image: ImageId(0),
                paint: PaintId(0),
                transform: Matrix::IDENTITY,
                alpha: 1.0,
                blend: BlendMode::Normal,
            },
            DisplayOp::Restore,
        ]);
        page
    }

    #[test]
    fn qualifies_only_native_full_page_jbig2_smask() {
        let page = eligible_page();
        let candidate = qualifying_jbig2_smask(&page).expect("eligible mask");
        assert_eq!(candidate.page_data.as_ref(), &b"encoded mask"[..]);
        assert_eq!(
            candidate
                .smask
                .codec_parms
                .as_ref()
                .and_then(|parms| parms.jbig2_globals.as_deref()),
            Some(&b"encoded globals"[..])
        );
        assert_eq!(candidate.stencil_polarity, Jbig2StencilPolarity::PaintOne);

        let mut maskless = page.clone();
        let maskless_image = &mut Arc::make_mut(&mut maskless.images)[0];
        maskless_image.smask = None;
        maskless_image.codec = Some(ImageCodecKind::Dct);
        maskless_image.codec_data = Some((&b"jpeg"[..]).into());
        assert!(qualifying_jbig2_smask(&maskless).is_none());

        let mut non_jbig2 = page.clone();
        let smask = Arc::make_mut(&mut non_jbig2.images)[0]
            .smask
            .as_mut()
            .unwrap();
        Arc::make_mut(smask).codec = Some(ImageCodecKind::CcittFax);
        assert!(qualifying_jbig2_smask(&non_jbig2).is_none());

        let mut grayscale = page.clone();
        let smask = Arc::make_mut(&mut grayscale.images)[0]
            .smask
            .as_mut()
            .unwrap();
        let smask = Arc::make_mut(smask);
        smask.bits_per_component = 8;
        smask.codec = None;
        smask.codec_data = None;
        smask.samples = Arc::from(&b"gray"[..]);
        assert!(qualifying_jbig2_smask(&grayscale).is_none());

        let mut image_mask = page.clone();
        Arc::make_mut(&mut image_mask.images)[0].is_stencil = true;
        assert!(qualifying_jbig2_smask(&image_mask).is_none());

        let mut in_data = page.clone();
        Arc::make_mut(&mut in_data.images)[0].smask_in_data = 1;
        assert!(qualifying_jbig2_smask(&in_data).is_none());

        let mut explicit_mask = page;
        Arc::make_mut(&mut explicit_mask.images)[0].mask =
            Some(crate::page_ir::ImageMask::ColorKey(Arc::from([[0, 0]])));
        assert!(qualifying_jbig2_smask(&explicit_mask).is_none());
    }

    #[test]
    fn source_decode_maps_to_opposite_stencil_polarity() {
        let mut page = eligible_page();
        {
            let smask = Arc::make_mut(&mut page.images)[0].smask.as_mut().unwrap();
            Arc::make_mut(smask).decode = Some(Arc::from([[1.0, 0.0]]));
        }
        assert_eq!(
            qualifying_jbig2_smask(&page)
                .expect("inverted source decode remains representable")
                .stencil_polarity,
            Jbig2StencilPolarity::PaintZero
        );

        let smask = Arc::make_mut(&mut page.images)[0].smask.as_mut().unwrap();
        Arc::make_mut(smask).decode = Some(Arc::from([[0.2, 0.8]]));
        assert!(qualifying_jbig2_smask(&page).is_none());
    }

    #[test]
    fn rejects_ambiguous_or_unsupported_placement() {
        let page = eligible_page();
        let mut duplicate = page.clone();
        let mut operations = duplicate.operations.to_vec();
        operations.splice(3..3, duplicate.operations[0..3].iter().cloned());
        duplicate.operations = Arc::from(operations);
        assert!(qualifying_jbig2_smask(&duplicate).is_none());

        let mut rotated = page.clone();
        rotated.bounds.rotate = 90;
        assert!(qualifying_jbig2_smask(&rotated).is_none());

        let mut offset = page;
        Arc::make_mut(&mut offset.operations)[1] =
            DisplayOp::ConcatTransform(Matrix::scale(109.0, 50.0));
        assert!(qualifying_jbig2_smask(&offset).is_none());
    }

    #[test]
    fn accepts_full_page_placement_within_half_a_source_pixel() {
        let mut page = eligible_page();
        // The 12x5 base raster spans 120x50 points, so half a source pixel is
        // 5 points on either axis. Keep both edges just inside that allowance.
        Arc::make_mut(&mut page.operations)[1] = DisplayOp::ConcatTransform(Matrix {
            a: 112.0,
            b: 0.0,
            c: 0.0,
            d: 42.0,
            e: 4.0,
            f: 4.0,
        });
        assert!(qualifying_jbig2_smask(&page).is_some());

        Arc::make_mut(&mut page.operations)[1] = DisplayOp::ConcatTransform(Matrix {
            a: 108.0,
            b: 0.0,
            c: 0.0,
            d: 38.0,
            e: 6.0,
            f: 6.0,
        });
        assert!(qualifying_jbig2_smask(&page).is_none());
    }

    #[test]
    fn working_plane_preserves_fractional_edge_coverage() {
        let decoded = DecodedBilevelSmask {
            width: 2,
            height: 2,
            stride: 2,
            opacity: Arc::from([0, 255, 255, 0]),
        };
        let working = resize_smask_coverage(decoded, 7, 7).expect("valid coverage");
        assert_eq!((working.width, working.height, working.stride), (7, 7, 7));
        assert!(
            working
                .pixels
                .iter()
                .any(|&sample| sample > 0 && sample < 255),
            "resized analysis mask must retain antialiased edge coverage"
        );
        // Target pixel 3 spans source [6/7, 8/7): 1/7 of the first source
        // pixel and 1/7 of the second, so its coverage is their mean.
        assert_eq!(working.pixels[3], 128);
        assert_eq!(working.pixels[0], 0);
        assert_eq!(working.pixels[6], 255);
    }

    #[test]
    fn working_plane_is_the_exact_area_average() {
        // A 4x4 checkerboard halved: every 2x2 block is half ink.
        let mut checker = [0u8; 16];
        for (i, v) in checker.iter_mut().enumerate() {
            if (i % 4 + i / 4) % 2 == 0 {
                *v = 255;
            }
        }
        let decoded = DecodedBilevelSmask {
            width: 4,
            height: 4,
            stride: 4,
            opacity: Arc::from(checker),
        };
        let working = resize_smask_coverage(decoded, 2, 2).expect("valid coverage");
        assert_eq!(&working.pixels[..], &[128, 128, 128, 128]);

        // 3 -> 2 along one axis: the first target pixel takes one source
        // pixel and half of the next (255/2 over a span of 1.5 = 85), the
        // second the remaining half and one.
        let decoded = DecodedBilevelSmask {
            width: 3,
            height: 1,
            stride: 3,
            opacity: Arc::from([0, 255, 255]),
        };
        let working = resize_smask_coverage(decoded, 2, 1).expect("valid coverage");
        assert_eq!(&working.pixels[..], &[85, 255]);

        // Same size: the plane is passed through untouched.
        let decoded = DecodedBilevelSmask {
            width: 3,
            height: 1,
            stride: 3,
            opacity: Arc::from([0, 255, 7]),
        };
        let working = resize_smask_coverage(decoded, 3, 1).expect("valid coverage");
        assert_eq!(&working.pixels[..], &[0, 255, 7]);
    }

    /// A product's decode reference becomes the whole-page transform onto the
    /// reference raster, whatever the product's own size and crop; without a
    /// reference, or with a zero-sized one, the renderer gets no policy.
    #[test]
    fn decode_reference_maps_to_the_whole_page_transform() {
        let page = eligible_page();
        let crop = DeviceCrop {
            x: 3,
            y: 4,
            width: 5,
            height: 6,
            page_width: 40,
            page_height: 60,
        };
        let region = RasterProduct::rgb8(10, 12)
            .with_crop(crop)
            .with_decode_reference(40, 60);
        assert_eq!(
            render_options(&page, &region)
                .image_decode_reference
                .map(|reference| reference.matrix),
            Some(page_to_device_matrix(&page, 40, 60))
        );
        for product in [
            RasterProduct::gray8(8, 8),
            RasterProduct::gray8(8, 8).with_decode_reference(0, 60),
        ] {
            assert!(
                render_options(&page, &product)
                    .image_decode_reference
                    .is_none()
            );
        }
    }
}