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
//! Lowering a [`SemanticPage`] to the backend-neutral
//! [`crate::page_ir::CompiledPage`] (roadmap §7 Phase 3).
//!
//! This is where PDF's *implicit* graphics state becomes *explicit* display
//! operations: the semantic layer's `SetFillColor`/`SetFillAlpha`/… state
//! mutations disappear, and their effect is baked directly onto each paint
//! operation (`FillPath { paint, alpha, blend, … }`). Resources are interned
//! into per-page tables and referenced by typed handle. The clip stack becomes
//! explicit `PushClip`/`PopClip` pairs bracketed to the `q`/`Q` scopes.
//!
//! Painter order is preserved exactly; nothing is reordered.

use std::collections::HashMap;
use std::sync::Arc;

use crate::page_ir::{
    BlendMode, Color, CompiledPage, DisplayOp, FontId, FontResource, GlyphRun, ImageId, ImageIr,
    InterpolationMode, LineCap, LineJoin, Matrix, PageComplexity, PageFeatures, Paint, PaintId,
    PathData, PathId, PlacedGlyph, Point, Rect, ResourceKey, ShadingId, ShadingKind,
    ShadingResource, StrokeStyle, StrokeStyleId, TilingId, TilingPattern, TransparencyGroup,
    TransparencyGroupId,
};

use crate::content::semantic::{
    SemColor, SemShading, SemShadingKind, SemTiling, SemanticOp, SemanticPage, TextElement, TextRun,
};

/// Lowering-time graphics state — the subset the IR bakes onto paint ops.
/// Cloned on `Save`, restored on `Restore`, exactly mirroring the semantic
/// `q`/`Q` scopes so state established inside a scope does not leak past it.
#[derive(Debug, Clone)]
struct LowerGs {
    ctm: Matrix,
    fill_color: SemColor,
    stroke_color: SemColor,
    fill_alpha: f32,
    stroke_alpha: f32,
    blend: BlendMode,
    line_width: f64,
    line_cap: LineCap,
    line_join: LineJoin,
    miter_limit: f64,
    dash_pattern: Vec<f64>,
    dash_phase: f64,
}

impl Default for LowerGs {
    fn default() -> Self {
        Self {
            ctm: Matrix::IDENTITY,
            fill_color: SemColor::DeviceGray(0.0),
            stroke_color: SemColor::DeviceGray(0.0),
            fill_alpha: 1.0,
            stroke_alpha: 1.0,
            blend: BlendMode::Normal,
            line_width: 1.0,
            line_cap: LineCap::Butt,
            line_join: LineJoin::Miter,
            miter_limit: 10.0,
            dash_pattern: Vec::new(),
            dash_phase: 0.0,
        }
    }
}

/// Dedup key for interning [`Paint`]s. Floats are keyed by bit pattern so the
/// map is exact and deterministic.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum PaintKey {
    Solid([u32; 4]),
    /// Tiling-pattern handle (the pattern `/Matrix` is fixed per handle).
    Pattern(u32),
    /// Shading-pattern handle.
    Shading(u32),
}

pub(crate) struct Lowerer<'a> {
    page: &'a SemanticPage,
    ops: Vec<DisplayOp>,

    paths: Vec<PathData>,
    path_map: HashMap<Vec<u8>, PathId>,
    paints: Vec<Paint>,
    paint_map: HashMap<PaintKey, PaintId>,
    stroke_styles: Vec<StrokeStyle>,
    stroke_map: HashMap<Vec<u8>, StrokeStyleId>,
    glyph_runs: Vec<GlyphRun>,
    fonts: Vec<FontResource>,
    /// Maps a semantic font handle to the compiled font table index.
    font_map: HashMap<u32, FontId>,
    images: Vec<ImageIr>,
    groups: Vec<TransparencyGroup>,

    gs: LowerGs,
    gs_stack: Vec<LowerGs>,
    /// Number of clips pushed and not yet popped.
    clip_count: u32,
    /// Clip count captured at each `Save`, to unwind on the matching `Restore`.
    clip_scope: Vec<u32>,
    /// Conservative page-space union of visible paint operations. Soft-mask
    /// construction is deliberately excluded: it modulates later paint but
    /// does not itself put marks on the page.
    content_bounds: Option<Rect>,
    soft_mask_depth: u32,
    /// Page-space bounds of the content of each soft mask being lowered,
    /// innermost last, with its index into `soft_mask_units`.
    mask_bounds: Vec<(usize, Option<Rect>)>,
    /// Square user units each soft mask's content covers, in the order of
    /// the `BeginSoftMask` ops.
    soft_mask_units: Vec<u64>,
    /// The most square user units one tiling-pattern fill covers.
    tiling_fill_units: u64,
}

impl<'a> Lowerer<'a> {
    pub(crate) fn new(page: &'a SemanticPage) -> Self {
        Self {
            page,
            ops: Vec::with_capacity(page.ops.len()),
            paths: Vec::new(),
            path_map: HashMap::new(),
            paints: Vec::new(),
            paint_map: HashMap::new(),
            stroke_styles: Vec::new(),
            stroke_map: HashMap::new(),
            glyph_runs: Vec::new(),
            fonts: Vec::new(),
            font_map: HashMap::new(),
            images: Vec::new(),
            groups: Vec::new(),
            gs: LowerGs::default(),
            gs_stack: Vec::new(),
            clip_count: 0,
            clip_scope: Vec::new(),
            content_bounds: None,
            soft_mask_depth: 0,
            mask_bounds: Vec::new(),
            soft_mask_units: Vec::new(),
            tiling_fill_units: 0,
        }
    }

    pub(crate) fn lower(mut self) -> CompiledPage {
        // Clone the op handle first so `self` is free to be mutated while we
        // walk it (the ops borrow the page's Arc, not `self`).
        let ops = self.page.ops.clone();
        for op in ops.iter() {
            self.lower_op(op);
        }

        // Shadings and tilings map 1:1 (index-preserving) from the semantic
        // tables, so the handles carried in resolved paints stay valid.
        let shadings: Vec<ShadingResource> =
            self.page.shadings.iter().map(convert_shading).collect();
        let tilings: Vec<TilingPattern> = self.page.tilings.iter().map(convert_tiling).collect();

        let features = self.compute_features(&shadings, &tilings);
        let complexity = self.compute_complexity();

        CompiledPage {
            schema_version: crate::page_ir::IR_SCHEMA_VERSION,
            bounds: self.page.bounds,
            content_bounds: self
                .content_bounds
                .and_then(|bounds| bounds.intersect(self.page.bounds.crop.normalized())),
            operations: self.ops.into(),
            paths: self.paths.into(),
            paints: self.paints.into(),
            stroke_styles: self.stroke_styles.into(),
            glyph_runs: self.glyph_runs.into(),
            fonts: self.fonts.into(),
            images: self.images.into(),
            // Soft masks are represented in the IR (DisplayOp::ApplySoftMask +
            // MaskResource) but populated in Phase 10.
            masks: Vec::new().into(),
            groups: self.groups.into(),
            shadings: shadings.into(),
            tilings: tilings.into(),
            features,
            complexity,
        }
    }

    fn lower_op(&mut self, op: &SemanticOp) {
        match op {
            SemanticOp::Save => {
                self.ops.push(DisplayOp::Save);
                self.gs_stack.push(self.gs.clone());
                self.clip_scope.push(self.clip_count);
            }
            SemanticOp::Restore => {
                let target = self.clip_scope.pop().unwrap_or(0);
                while self.clip_count > target {
                    self.ops.push(DisplayOp::PopClip);
                    self.clip_count -= 1;
                }
                self.ops.push(DisplayOp::Restore);
                self.gs = self.gs_stack.pop().unwrap_or_default();
            }
            SemanticOp::Concat(m) => {
                self.gs.ctm = m.then(self.gs.ctm);
                self.ops.push(DisplayOp::ConcatTransform(*m));
            }

            // State changes: absorbed into the paint ops that follow.
            SemanticOp::SetLineWidth(w) => self.gs.line_width = *w,
            SemanticOp::SetLineCap(c) => self.gs.line_cap = *c,
            SemanticOp::SetLineJoin(j) => self.gs.line_join = *j,
            SemanticOp::SetMiterLimit(m) => self.gs.miter_limit = *m,
            SemanticOp::SetDash { pattern, phase } => {
                self.gs.dash_pattern = pattern.clone();
                self.gs.dash_phase = *phase;
            }
            SemanticOp::SetFillColor(c) => self.gs.fill_color = c.clone(),
            SemanticOp::SetStrokeColor(c) => self.gs.stroke_color = c.clone(),
            SemanticOp::SetFillAlpha(a) => self.gs.fill_alpha = *a,
            SemanticOp::SetStrokeAlpha(a) => self.gs.stroke_alpha = *a,
            SemanticOp::SetBlendMode(m) => self.gs.blend = *m,

            SemanticOp::Fill { path, rule } => {
                self.note_tiling_path(path.index(), 0.0, true, false);
                self.include_path(path.index(), 0.0);
                let path = self.intern_path(path.index());
                let paint = self.intern_paint(&self.gs.fill_color.clone());
                self.ops.push(DisplayOp::FillPath {
                    path,
                    paint,
                    rule: *rule,
                    alpha: self.gs.fill_alpha,
                    blend: self.gs.blend,
                });
            }
            SemanticOp::Stroke { path } => {
                self.note_tiling_path(path.index(), self.gs.line_width * 0.5, false, true);
                self.include_path(path.index(), self.gs.line_width * 0.5);
                let path = self.intern_path(path.index());
                let paint = self.intern_paint(&self.gs.stroke_color.clone());
                let style = self.intern_stroke();
                self.ops.push(DisplayOp::StrokePath {
                    path,
                    paint,
                    style,
                    alpha: self.gs.stroke_alpha,
                    blend: self.gs.blend,
                });
            }
            SemanticOp::FillStroke { path, rule } => {
                self.note_tiling_path(path.index(), self.gs.line_width * 0.5, true, true);
                self.include_path(path.index(), self.gs.line_width * 0.5);
                let path = self.intern_path(path.index());
                let fill_paint = self.intern_paint(&self.gs.fill_color.clone());
                self.ops.push(DisplayOp::FillPath {
                    path,
                    paint: fill_paint,
                    rule: *rule,
                    alpha: self.gs.fill_alpha,
                    blend: self.gs.blend,
                });
                let stroke_paint = self.intern_paint(&self.gs.stroke_color.clone());
                let style = self.intern_stroke();
                self.ops.push(DisplayOp::StrokePath {
                    path,
                    paint: stroke_paint,
                    style,
                    alpha: self.gs.stroke_alpha,
                    blend: self.gs.blend,
                });
            }
            SemanticOp::Clip { path, rule } => {
                let path = self.intern_path(path.index());
                self.ops.push(DisplayOp::PushClip { path, rule: *rule });
                self.clip_count += 1;
            }
            SemanticOp::ClipText { runs } => {
                // Intern each clip-contributing run to a glyph run; the backend
                // unions their outlines into one text clip. Balanced by the
                // `PopClip` the enclosing `Restore` emits, like a path clip.
                let run_ids: Vec<crate::page_ir::GlyphRunId> = runs
                    .iter()
                    .map(|r| self.intern_glyph_run(r.index()))
                    .collect();
                self.ops.push(DisplayOp::PushClipText {
                    runs: run_ids.into(),
                });
                self.clip_count += 1;
            }

            SemanticOp::ShowText(run) => {
                let semantic_run = &self.page.text_runs[run.index()];
                if !semantic_run.visible
                    || self.page.fonts[semantic_run.font.index()].subtype == b"Type3"
                {
                    return;
                }
                let mode = semantic_run.render_mode;
                let run_id = self.intern_glyph_run(run.index());
                if matches!(self.gs.fill_color, SemColor::TilingPattern { .. })
                    || matches!(self.gs.stroke_color, SemColor::TilingPattern { .. })
                {
                    let rect = self.glyph_run_rect(run_id);
                    self.note_tiling_rect(rect);
                }
                self.include_glyph_run(run_id);
                let paint = self.intern_paint(&self.gs.fill_color.clone());
                // Stroking render modes (Tr 1/2/5/6) also stroke the glyph
                // outlines with the current stroke colour, alpha, and line
                // style (§9.3.1). The backend selects fill vs stroke from the
                // run's render_mode; the fill paint above is harmless when the
                // mode does not fill.
                let stroke = if matches!(mode, 1 | 2 | 5 | 6) {
                    Some(crate::page_ir::GlyphStroke {
                        paint: self.intern_paint(&self.gs.stroke_color.clone()),
                        style: self.intern_stroke(),
                        alpha: self.gs.stroke_alpha,
                    })
                } else {
                    None
                };
                self.ops.push(DisplayOp::DrawGlyphRun {
                    run: run_id,
                    paint,
                    alpha: self.gs.fill_alpha,
                    blend: self.gs.blend,
                    stroke,
                });
            }
            SemanticOp::DrawImage(image) => {
                self.include_unit_square();
                let image_id = self.intern_image(image.index());
                // The current fill paint colors an /ImageMask stencil.
                let paint = self.intern_paint(&self.gs.fill_color.clone());
                // The image occupies the unit square in current user space; the
                // CTM is carried by the surrounding ConcatTransform scope, so
                // the op's own transform is identity (consistent with paths).
                self.ops.push(DisplayOp::DrawImage {
                    image: image_id,
                    paint,
                    transform: Matrix::IDENTITY,
                    alpha: self.gs.fill_alpha,
                    blend: self.gs.blend,
                });
            }
            SemanticOp::BeginGroup {
                isolated,
                knockout,
                bounds,
                opacity,
                blend,
            } => {
                let id = TransparencyGroupId(self.groups.len() as u32);
                self.groups.push(TransparencyGroup {
                    isolated: *isolated,
                    knockout: *knockout,
                    bounds: *bounds,
                    opacity: *opacity,
                    blend: *blend,
                });
                self.ops
                    .push(DisplayOp::BeginTransparencyGroup { group: id });
                // ISO 32000-1 §11.6.6: inside a transparency group the
                // constant alpha and blend mode reset to their defaults — the
                // outer values become the GROUP's composite parameters
                // (carried on `TransparencyGroup` above), and must not also
                // apply to the ops inside, or a 0.5-alpha group draws its
                // content at 0.25. The interpreter resets its own state after
                // emitting BeginGroup but emits no op for it, so this replayed
                // state must reset here too. The group is always bracketed by
                // Save/Restore, which restores the outer values on exit.
                self.gs.fill_alpha = 1.0;
                self.gs.stroke_alpha = 1.0;
                self.gs.blend = BlendMode::Normal;
            }
            SemanticOp::EndGroup => self.ops.push(DisplayOp::EndTransparencyGroup),
            SemanticOp::BeginPaintOrigin(o) => self.ops.push(DisplayOp::BeginPaintOrigin(*o)),
            SemanticOp::EndPaintOrigin => self.ops.push(DisplayOp::EndPaintOrigin),
            SemanticOp::BeginSoftMask { kind, transfer } => {
                self.soft_mask_depth += 1;
                self.mask_bounds.push((self.soft_mask_units.len(), None));
                self.soft_mask_units.push(0);
                self.ops.push(DisplayOp::BeginSoftMask {
                    kind: *kind,
                    transfer: transfer.clone(),
                });
            }
            SemanticOp::EndSoftMask => {
                self.ops.push(DisplayOp::EndSoftMask);
                self.soft_mask_depth = self.soft_mask_depth.saturating_sub(1);
                if let Some((index, bounds)) = self.mask_bounds.pop() {
                    let units = self.page_units(bounds);
                    if let Some(slot) = self.soft_mask_units.get_mut(index) {
                        *slot = units;
                    }
                }
            }
            SemanticOp::ClearSoftMask => self.ops.push(DisplayOp::ClearSoftMask),
            SemanticOp::PaintShading(id) => {
                // A shading without a finite BBox is clipped by the page.
                // Using the page box remains conservative and avoids decoding
                // any image/font resource merely to determine an extent.
                self.include_rect(self.page.bounds.crop);
                // `sh` paints in the current user space; the CTM is carried by
                // the enclosing ConcatTransform scope, so the op transform is
                // identity (consistent with DrawImage).
                self.ops.push(DisplayOp::DrawShading {
                    shading: ShadingId(id.0),
                    transform: Matrix::IDENTITY,
                });
            }
        }
    }

    fn include_rect(&mut self, rect: Rect) {
        let rect = rect.normalized();
        if ![rect.x0, rect.y0, rect.x1, rect.y1]
            .iter()
            .all(|value| value.is_finite())
            || rect.width() <= 0.0
            || rect.height() <= 0.0
        {
            return;
        }
        // Soft-mask content marks the mask, not the page: its bounds size
        // the mask's planes for the memory estimate and stay out of the
        // page's content bounds.
        if let Some((_, bounds)) = self.mask_bounds.last_mut() {
            *bounds = Some(match *bounds {
                Some(seen) => seen.union(rect),
                None => rect,
            });
            return;
        }
        if self.soft_mask_depth != 0 {
            return;
        }
        self.content_bounds = Some(match self.content_bounds {
            Some(bounds) => bounds.union(rect),
            None => rect,
        });
    }

    fn include_transformed_rect(&mut self, rect: Rect, transform: Matrix) {
        self.include_rect(transform.transform_rect(rect));
    }

    fn include_path(&mut self, semantic_index: usize, stroke_half_width: f64) {
        if let Some(rect) = self.path_rect(semantic_index, stroke_half_width) {
            self.include_rect(rect);
        }
    }

    /// Page-space bounding box of a path's control points under the current
    /// transform, padded by `stroke_half_width` in user units.
    fn path_rect(&self, semantic_index: usize, stroke_half_width: f64) -> Option<Rect> {
        let path = &self.page.paths[semantic_index];
        if path.points.is_empty() {
            return None;
        }
        let points: Vec<Point> = path
            .points
            .iter()
            .map(|point| self.gs.ctm.apply(*point))
            .collect();
        let scale = self
            .gs
            .ctm
            .a
            .hypot(self.gs.ctm.b)
            .max(self.gs.ctm.c.hypot(self.gs.ctm.d));
        let pad = stroke_half_width.abs() * scale;
        Some(Rect {
            x0: points.iter().map(|p| p.x).fold(f64::INFINITY, f64::min) - pad,
            y0: points.iter().map(|p| p.y).fold(f64::INFINITY, f64::min) - pad,
            x1: points.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max) + pad,
            y1: points.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max) + pad,
        })
    }

    /// Square user units of `rect` that lie on the page; 0 for none.
    fn page_units(&self, rect: Option<Rect>) -> u64 {
        let Some(rect) = rect else { return 0 };
        let (rect, page) = (rect.normalized(), self.page.bounds.crop.normalized());
        let width = rect.x1.min(page.x1) - rect.x0.max(page.x0);
        let height = rect.y1.min(page.y1) - rect.y0.max(page.y0);
        if !(width.is_finite() && height.is_finite()) || width <= 0.0 || height <= 0.0 {
            return 0;
        }
        (width.ceil() as u64).saturating_mul(height.ceil() as u64)
    }

    /// A shape painted with a tiling pattern holds planes over its whole
    /// bounds while it is filled; remember the largest.
    fn note_tiling_rect(&mut self, rect: Option<Rect>) {
        self.tiling_fill_units = self.tiling_fill_units.max(self.page_units(rect));
    }

    fn note_tiling_path(&mut self, path: usize, stroke_half_width: f64, fill: bool, stroke: bool) {
        if (fill && matches!(self.gs.fill_color, SemColor::TilingPattern { .. }))
            || (stroke && matches!(self.gs.stroke_color, SemColor::TilingPattern { .. }))
        {
            let rect = self.path_rect(path, stroke_half_width);
            self.note_tiling_rect(rect);
        }
    }

    /// Page-space union of a glyph run's (generous) glyph boxes.
    fn glyph_run_rect(&self, run_id: crate::page_ir::GlyphRunId) -> Option<Rect> {
        let run = &self.glyph_runs[run_id.index()];
        let transform = run.transform.then(self.gs.ctm);
        let size = run.font_size.abs().max(0.01);
        run.glyphs
            .iter()
            .map(|glyph| {
                transform
                    .transform_rect(Rect {
                        x0: glyph.x,
                        y0: glyph.y - size * 0.25,
                        x1: glyph.x + size,
                        y1: glyph.y + size,
                    })
                    .normalized()
            })
            .reduce(|a, b| a.union(b))
    }

    fn include_unit_square(&mut self) {
        self.include_transformed_rect(
            Rect {
                x0: 0.0,
                y0: 0.0,
                x1: 1.0,
                y1: 1.0,
            },
            self.gs.ctm,
        );
    }

    fn include_glyph_run(&mut self, run_id: crate::page_ir::GlyphRunId) {
        let run = &self.glyph_runs[run_id.index()];
        let transform = run.transform.then(self.gs.ctm);
        let size = run.font_size.abs().max(0.01);
        let boxes: Vec<Rect> = run
            .glyphs
            .iter()
            .map(|glyph| Rect {
                x0: glyph.x,
                y0: glyph.y - size * 0.25,
                x1: glyph.x + size,
                y1: glyph.y + size,
            })
            .collect();
        for bounds in boxes {
            self.include_transformed_rect(bounds, transform);
        }
    }

    fn intern_path(&mut self, semantic_index: usize) -> PathId {
        let data = &self.page.paths[semantic_index];
        let key = path_key(data);
        if let Some(id) = self.path_map.get(&key) {
            return *id;
        }
        let id = PathId(self.paths.len() as u32);
        self.paths.push(data.clone());
        self.path_map.insert(key, id);
        id
    }

    fn intern_paint(&mut self, color: &SemColor) -> PaintId {
        let paint = resolve_paint(color);
        let key = paint_key(&paint);
        if let Some(id) = self.paint_map.get(&key) {
            return *id;
        }
        let id = PaintId(self.paints.len() as u32);
        self.paints.push(paint);
        self.paint_map.insert(key, id);
        id
    }

    fn intern_stroke(&mut self) -> StrokeStyleId {
        let style = StrokeStyle {
            width: self.gs.line_width,
            cap: self.gs.line_cap,
            join: self.gs.line_join,
            miter_limit: self.gs.miter_limit,
            dash_pattern: self.gs.dash_pattern.clone().into(),
            dash_phase: self.gs.dash_phase,
        };
        let key = stroke_key(&style);
        if let Some(id) = self.stroke_map.get(&key) {
            return *id;
        }
        let id = StrokeStyleId(self.stroke_styles.len() as u32);
        self.stroke_styles.push(style);
        self.stroke_map.insert(key, id);
        id
    }

    fn intern_font(&mut self, semantic_index: usize) -> FontId {
        if let Some(id) = self.font_map.get(&(semantic_index as u32)) {
            return *id;
        }
        let sem = &self.page.fonts[semantic_index];
        let key = match sem.object {
            Some(obj) => ResourceKey {
                object_number: obj.number,
                generation: obj.generation,
                variant: 0,
            },
            None => ResourceKey {
                object_number: 0,
                generation: 0,
                variant: semantic_index as u32,
            },
        };
        let id = FontId(self.fonts.len() as u32);
        // Carry the embedded outline program (empty → the backend falls back to
        // placement boxes).
        let program: Arc<[u8]> = match &sem.program {
            Some(bytes) => bytes.clone(),
            None => Vec::new().into(),
        };
        self.fonts.push(FontResource {
            key,
            program,
            face_index: sem.face_index,
            synthetic_shear: sem.synthesis.oblique_shear,
            // PDFium's weight-700 embolden level: kWeightPow[(700-400)/10]
            // = 70 font units per 1000 upem (cfx_face.cpp).
            synthetic_embolden_em: if sem.synthesis.embolden { 0.07 } else { 0.0 },
        });
        self.font_map.insert(semantic_index as u32, id);
        id
    }

    fn intern_glyph_run(&mut self, semantic_index: usize) -> crate::page_ir::GlyphRunId {
        let run = self.page.text_runs[semantic_index].clone();
        let sem = &self.page.fonts[run.font.index()];
        let metrics = sem.metrics.clone();
        let glyph_map = sem.glyph_map.clone();
        let font = self.intern_font(run.font.index());
        let glyphs = placed_glyphs(&run, &metrics, &glyph_map);
        let compiled = GlyphRun {
            font,
            font_size: run.font_size,
            transform: run_transform(&run),
            glyphs: glyphs.into(),
            render_mode: run.render_mode,
        };
        let id = crate::page_ir::GlyphRunId(self.glyph_runs.len() as u32);
        self.glyph_runs.push(compiled);
        id
    }

    fn intern_image(&mut self, semantic_index: usize) -> ImageId {
        let sem = &self.page.images[semantic_index];
        let key = match sem.object {
            Some(obj) => ResourceKey {
                object_number: obj.number,
                generation: obj.generation,
                variant: 0,
            },
            // Inline images have no object identity; key them by position so
            // two distinct inline images never collide in a cache.
            None => ResourceKey {
                object_number: 0,
                generation: 0,
                variant: semantic_index as u32,
            },
        };
        let ir = ImageIr {
            key,
            width: sem.width,
            height: sem.height,
            is_stencil: sem.is_mask,
            interpolation: if sem.interpolate {
                InterpolationMode::Bilinear
            } else {
                InterpolationMode::Nearest
            },
            soft_mask: None,
            bits_per_component: sem.bits_per_component,
            color_space: sem
                .color_space
                .clone()
                .unwrap_or(crate::page_ir::ImageColorSpace::Gray),
            decode: sem.decode.clone().map(Arc::from),
            samples: sem.samples.clone(),
            codec: sem.codec,
            codec_data: sem.codec_data.clone(),
            codec_parms: sem.codec_parms.clone(),
            smask: sem.smask.clone(),
            mask: sem.mask.clone(),
            smask_in_data: sem.smask_in_data,
            lowering_degraded: sem.lowering_degraded,
        };
        let id = ImageId(self.images.len() as u32);
        self.images.push(ir);
        id
    }

    fn compute_features(
        &self,
        shadings: &[ShadingResource],
        tilings: &[TilingPattern],
    ) -> PageFeatures {
        let mut f = PageFeatures::empty();
        for op in &self.ops {
            match op {
                DisplayOp::FillPath { alpha, blend, .. }
                | DisplayOp::StrokePath { alpha, blend, .. } => {
                    f |= PageFeatures::BASIC_PATHS;
                    apply_transparency(&mut f, *alpha, *blend);
                }
                DisplayOp::DrawGlyphRun { alpha, blend, .. } => {
                    f |= PageFeatures::TEXT;
                    apply_transparency(&mut f, *alpha, *blend);
                }
                DisplayOp::DrawImage { alpha, blend, .. } => {
                    f |= PageFeatures::IMAGES;
                    apply_transparency(&mut f, *alpha, *blend);
                }
                DisplayOp::PushClip { .. } => f |= PageFeatures::CLIPPING,
                DisplayOp::PushClipText { .. } => f |= PageFeatures::CLIPPING | PageFeatures::TEXT,
                DisplayOp::BeginTransparencyGroup { .. } => f |= PageFeatures::TRANSPARENCY,
                DisplayOp::DrawShading { .. } => f |= PageFeatures::SHADINGS,
                _ => {}
            }
        }
        if !shadings.is_empty()
            || self
                .paints
                .iter()
                .any(|p| matches!(p, Paint::Shading { .. }))
        {
            f |= PageFeatures::SHADINGS;
        }
        if !tilings.is_empty()
            || self
                .paints
                .iter()
                .any(|p| matches!(p, Paint::Pattern { .. }))
        {
            f |= PageFeatures::PATTERNS;
        }
        if self
            .stroke_styles
            .iter()
            .any(|s| !s.dash_pattern.is_empty())
        {
            f |= PageFeatures::DASHED_STROKES;
        }
        if self.images.iter().any(|i| i.is_stencil) {
            f |= PageFeatures::STENCIL_MASKS;
        }
        if self.page.fonts.iter().any(|font| font.subtype == b"Type3") {
            f |= PageFeatures::TYPE3_FONTS;
        }
        // Codec requirements from each image's filter chain, and from its
        // soft mask's (an MRC page's JPX foreground carries a JBIG2 /SMask —
        // both codecs must be advertised or preflight routes it wrong).
        for img in self.page.images.iter() {
            for filter in &img.filters {
                f |= codec_feature(filter);
            }
            if let Some(smask) = &img.smask {
                f |= codec_kind_feature(smask.codec);
            }
            // A stencil `/Mask` can itself be JBIG2/CCITT-encoded — advertise
            // its codec so preflight routes the page to a backend that has it.
            if let Some(crate::page_ir::ImageMask::Stencil(sm)) = &img.mask {
                f |= codec_kind_feature(sm.codec);
            }
        }
        // Color-management facts observed by the interpreter: flags only —
        // ICC rendering stays the arity approximation and overprint does not
        // change compositing; preflight/policy can now see them (§2.4).
        if self.page.uses_icc_color {
            f |= PageFeatures::ICC_COLOR;
        }
        if self.page.uses_overprint {
            f |= PageFeatures::OVERPRINT;
        }
        f
    }

    fn compute_complexity(&self) -> PageComplexity {
        let path_segment_count = self.paths.iter().map(|p| p.verbs.len() as u32).sum::<u32>();
        let glyph_count = self.glyph_runs.iter().map(|r| r.glyphs.len() as u32).sum();
        let image_pixels = self
            .images
            .iter()
            .map(|i| u64::from(i.width).saturating_mul(u64::from(i.height)))
            .fold(0u64, u64::saturating_add);
        // The CPU backend decodes every image of the page while it prepares
        // the page, and each prepared draw keeps its decoded samples until the
        // page finishes, so what an image *retains* adds up across the page.
        // Only a codec's working planes are freed when its decode returns,
        // and decodes run one at a time, so that part is the largest one.
        let (retained, working) = self
            .images
            .iter()
            .map(estimate_cold_image_bytes)
            .fold((0u64, 0u64), |(retained, working), image| {
                (retained.saturating_add(image.0), working.max(image.1))
            });
        let estimated_image_decode_peak_bytes = retained.saturating_add(working);
        // Transparency groups: each renders into its own offscreen surface,
        // live from its begin to its end op. Nested groups are live together
        // and sequential ones are not, so walk the op stream and keep the
        // peak of the live sum. User-space units at 1x (4 bytes per square
        // unit); the scheduler scales this by the request transform and caps
        // it by the device surface.
        let mut live: Vec<u64> = Vec::new();
        let mut live_bytes = 0u64;
        let mut estimated_peak_bytes = 0u64;
        // Soft masks, the same way. While a mask's content is rendered it
        // holds an RGBA plane over its bounds (four bytes per square unit);
        // afterwards its coverage plane (one byte per unit) stays on the mask
        // stack until the enclosing save scope or group ends. `masks` mirrors
        // that stack: a mask's coverage units, or 0 for the "no mask" entry a
        // group or a cleared mask pushes.
        let mut masks: Vec<u64> = Vec::new();
        let mut mask_marks: Vec<usize> = Vec::new();
        let mut group_marks: Vec<usize> = Vec::new();
        let mut rendering: Vec<u64> = Vec::new();
        let mut next_mask = 0usize;
        let mut mask_bytes = 0u64;
        let mut estimated_soft_mask_peak_bytes = 0u64;
        let unwind = |masks: &mut Vec<u64>, mask_bytes: &mut u64, to: usize| {
            while masks.len() > to {
                if let Some(units) = masks.pop() {
                    *mask_bytes = mask_bytes.saturating_sub(units);
                }
            }
        };
        for op in &self.ops {
            match op {
                DisplayOp::BeginTransparencyGroup { group } => {
                    // A wrapper group is painted straight onto its parent
                    // (`render_cpu::exec`), with no surface of its own.
                    let direct = self.groups.get(group.index()).is_some_and(|g| {
                        !g.isolated
                            && !g.knockout
                            && g.blend == BlendMode::Normal
                            && g.opacity >= 1.0
                            && masks.last().is_none_or(|&units| units == 0)
                    });
                    let bytes = if direct {
                        0
                    } else {
                        self.groups
                            .get(group.index())
                            .map_or(0, estimate_group_surface_bytes)
                    };
                    live.push(bytes);
                    live_bytes = live_bytes.saturating_add(bytes);
                    estimated_peak_bytes = estimated_peak_bytes.max(live_bytes);
                    group_marks.push(masks.len());
                    masks.push(0);
                }
                DisplayOp::EndTransparencyGroup => {
                    if let Some(bytes) = live.pop() {
                        live_bytes = live_bytes.saturating_sub(bytes);
                    }
                    if let Some(mark) = group_marks.pop() {
                        unwind(&mut masks, &mut mask_bytes, mark);
                    }
                }
                DisplayOp::Save => mask_marks.push(masks.len()),
                DisplayOp::Restore => {
                    if let Some(mark) = mask_marks.pop() {
                        unwind(&mut masks, &mut mask_bytes, mark);
                    }
                }
                DisplayOp::BeginSoftMask { .. } => {
                    let units = self.soft_mask_units.get(next_mask).copied().unwrap_or(0);
                    next_mask += 1;
                    rendering.push(units);
                    mask_bytes = mask_bytes.saturating_add(units.saturating_mul(4));
                    estimated_soft_mask_peak_bytes = estimated_soft_mask_peak_bytes.max(mask_bytes);
                }
                DisplayOp::EndSoftMask => {
                    if let Some(units) = rendering.pop() {
                        mask_bytes = mask_bytes
                            .saturating_sub(units.saturating_mul(4))
                            .saturating_add(units);
                        masks.push(units);
                        estimated_soft_mask_peak_bytes =
                            estimated_soft_mask_peak_bytes.max(mask_bytes);
                    }
                }
                DisplayOp::ClearSoftMask => masks.push(0),
                _ => {}
            }
        }
        PageComplexity {
            operation_count: self.ops.len() as u32,
            path_segment_count,
            glyph_count,
            image_pixels,
            transparency_group_count: self.groups.len() as u32,
            estimated_peak_bytes,
            soft_mask_count: self.soft_mask_units.len() as u32,
            estimated_soft_mask_peak_bytes,
            estimated_tiling_peak_bytes: self.tiling_fill_units.saturating_mul(5),
            estimated_image_decode_peak_bytes,
            path_clip_count: self
                .ops
                .iter()
                .filter(|op| match op {
                    DisplayOp::PushClip { path, .. } => self
                        .paths
                        .get(path.index())
                        .is_none_or(|path| !is_user_space_rect(path)),
                    DisplayOp::PushClipText { .. } => true,
                    _ => false,
                })
                .count()
                .min(u32::MAX as usize) as u32,
        }
    }
}

/// Offscreen bytes of one transparency group at 1x: four bytes per square
/// unit of its user-space bounds, twice for a knockout group, which keeps a
/// same-sized scratch copy for the whole group.
/// Whether `path` is one closed axis-aligned rectangle in user space: the
/// clips that need no coverage mask (at any page rotation that is a multiple
/// of a quarter turn). Anything else is counted as a path clip, which is the
/// safe direction for a memory estimate.
fn is_user_space_rect(path: &crate::page_ir::PathData) -> bool {
    use crate::page_ir::PathVerb::{Close, LineTo, MoveTo};
    let points = &path.points[..];
    let corners = match &*path.verbs {
        [MoveTo, LineTo, LineTo, LineTo] | [MoveTo, LineTo, LineTo, LineTo, Close] => points,
        [MoveTo, LineTo, LineTo, LineTo, LineTo]
        | [MoveTo, LineTo, LineTo, LineTo, LineTo, Close]
            if points.len() == 5 && points[0] == points[4] =>
        {
            &points[..4]
        }
        _ => return false,
    };
    let [a, b, c, d] = corners else {
        return false;
    };
    (a.x == b.x && b.y == c.y && c.x == d.x && d.y == a.y)
        || (a.y == b.y && b.x == c.x && c.y == d.y && d.x == a.x)
}

fn estimate_group_surface_bytes(group: &crate::page_ir::TransparencyGroup) -> u64 {
    let w = (group.bounds.x1 - group.bounds.x0).abs().ceil().max(0.0) as u64;
    let h = (group.bounds.y1 - group.bounds.y0).abs().ceil().max(0.0) as u64;
    let surfaces = if group.knockout { 2 } else { 1 };
    w.saturating_mul(h)
        .saturating_mul(4)
        .saturating_mul(surfaces)
}

/// `(retained, working)` bytes of one image at source resolution, the most
/// a render can allocate for it.
///
/// *Retained*, kept until the page finishes: the codec's decoded raster
/// (filter-decoded samples are already owned by the IR and are shared, not
/// copied), any decoded codec mask, and the RGB8 copy the backend resolves
/// palette, ICC, Lab, tint, CMYK, gray and 16-bit images to (charged to every
/// image that is not a stencil, one-bit, bilevel-codec or DeviceRGB of at
/// most eight bits, which the backend samples in place).
///
/// *Working*, freed when the decode returns: four bytes per source component
/// per pixel for DCT and JPX (coefficient and sample planes), and two packed
/// one-bit planes for JBIG2 and CCITT.
///
/// Decode-time reduction (DCT and JPX decode a minified draw at a fraction of
/// full size) is not modelled: the placement is not known here, so this stays
/// the full-resolution upper bound.
fn estimate_cold_image_bytes(image: &ImageIr) -> (u64, u64) {
    let pixels = u64::from(image.width).saturating_mul(u64::from(image.height));
    let bpc = image.bits_per_component;
    let (decoded, working) = match image.codec {
        None => (0, 0),
        Some(codec) => {
            // A JPX `/SMaskInData` opacity channel is one more component than
            // the declared colour space has.
            let components = (image.color_space.components() as u64)
                .saturating_add(u64::from(image.smask_in_data != 0));
            estimate_codec_bytes(codec, image.width, image.height, components, bpc)
        }
    };
    let bilevel_codec = matches!(
        image.codec,
        Some(crate::page_ir::ImageCodecKind::Jbig2 | crate::page_ir::ImageCodecKind::CcittFax)
    );
    let sampled_in_place = image.is_stencil
        || bpc <= 1
        || bilevel_codec
        || (bpc <= 8 && image.color_space == crate::page_ir::ImageColorSpace::Rgb);
    let promoted = if sampled_in_place {
        0
    } else {
        pixels.saturating_mul(3)
    };
    let mut retained = decoded.saturating_add(promoted);
    let mut working = working;
    let masks = [
        image.smask.as_deref(),
        match image.mask.as_ref() {
            Some(crate::page_ir::ImageMask::Stencil(mask)) => Some(mask.as_ref()),
            _ => None,
        },
    ];
    for mask in masks.into_iter().flatten() {
        if let Some(codec) = mask.codec {
            let (decoded, mask_working) =
                estimate_codec_bytes(codec, mask.width, mask.height, 1, mask.bits_per_component);
            retained = retained.saturating_add(decoded);
            working = working.max(mask_working);
        }
    }
    (retained, working)
}

/// `(decoded, working)` bytes of one codec decode of a `width` x `height`
/// raster with `components` components.
fn estimate_codec_bytes(
    codec: crate::page_ir::ImageCodecKind,
    width: u32,
    height: u32,
    components: u64,
    bits_per_component: u8,
) -> (u64, u64) {
    use crate::page_ir::ImageCodecKind;
    let pixels = u64::from(width).saturating_mul(u64::from(height));
    match codec {
        // Packed one-bit rows out; the decoder's own bitmap is one bit per
        // pixel as well (in 32-bit words), plus margin for a region bitmap.
        ImageCodecKind::Jbig2 | ImageCodecKind::CcittFax => {
            let packed = u64::from(width)
                .div_ceil(8)
                .saturating_mul(u64::from(height));
            (packed, packed.saturating_mul(2))
        }
        ImageCodecKind::Dct | ImageCodecKind::Jpx => {
            let bytes_per_sample = if bits_per_component > 8 { 2 } else { 1 };
            let samples = pixels.saturating_mul(components);
            (
                samples.saturating_mul(bytes_per_sample),
                samples.saturating_mul(4),
            )
        }
    }
}

/// Set the transparency and non-separable-blend flags from one op's alpha and
/// blend mode.
fn apply_transparency(f: &mut PageFeatures, alpha: f32, blend: BlendMode) {
    if alpha < 1.0 || blend != BlendMode::Normal {
        f.insert(PageFeatures::TRANSPARENCY);
    }
    if !blend.is_separable() {
        f.insert(PageFeatures::NONSEPARABLE_BLENDS);
    }
}

/// Map a canonical filter name to its codec requirement flag.
fn codec_feature(filter: &[u8]) -> PageFeatures {
    match filter {
        b"DCTDecode" => PageFeatures::NEEDS_DCT,
        b"JPXDecode" => PageFeatures::NEEDS_JPX,
        b"JBIG2Decode" => PageFeatures::NEEDS_JBIG2,
        b"CCITTFaxDecode" => PageFeatures::NEEDS_CCITT,
        _ => PageFeatures::empty(),
    }
}

/// The `NEEDS_*` feature for a decoded [`ImageCodecKind`] (soft/hard masks
/// carry a codec enum rather than a filter name).
fn codec_kind_feature(codec: Option<crate::page_ir::ImageCodecKind>) -> PageFeatures {
    match codec {
        Some(crate::page_ir::ImageCodecKind::Dct) => PageFeatures::NEEDS_DCT,
        Some(crate::page_ir::ImageCodecKind::Jpx) => PageFeatures::NEEDS_JPX,
        Some(crate::page_ir::ImageCodecKind::Jbig2) => PageFeatures::NEEDS_JBIG2,
        Some(crate::page_ir::ImageCodecKind::CcittFax) => PageFeatures::NEEDS_CCITT,
        None => PageFeatures::empty(),
    }
}

/// The horizontal scaling `Th` (`Tz` / 100) that [`run_transform`] folds into
/// the run's matrix: `Th` itself, or 1 when it is 0 or otherwise not a normal
/// number (a singular or non-finite glyph matrix is never built; such runs
/// keep the placement-only scaling they always had).
fn folded_horizontal_scale(run: &TextRun) -> f64 {
    let th = run.horizontal_scale / 100.0;
    if th.is_normal() { th } else { 1.0 }
}

/// The run's glyph-space-to-user-space matrix: `Tm` with the horizontal
/// scaling folded in, `scale(Th, 1) × Tm`, so `Tz` reaches the glyph *shapes*
/// (the text rendering matrix of §9.4.4 is `[Tfs·Th 0 0 Tfs 0 Ts] × Tm`), not
/// only their positions. `Th = 1` keeps `Tm` bit for bit.
fn run_transform(run: &TextRun) -> Matrix {
    let th = folded_horizontal_scale(run);
    if th == 1.0 {
        run.text_matrix
    } else {
        Matrix::scale(th, 1.0).then(run.text_matrix)
    }
}

/// Place a run's character codes using the PDF advance widths (fonts.md §3).
/// **The `glyph` field still carries the raw character code, not a font glyph
/// index** — encoding→glyph-id resolution and outlines are later font phases —
/// but horizontal placement is now metric-correct: advance = width·Tfs/1000 +
/// Tc (+ Tw for code 32), with `TJ` adjustments applied.
///
/// Placements are in the frame *before* the horizontal scaling, which
/// [`run_transform`] applies to positions and shapes alike; only an unfolded
/// (zero or non-normal) `Th` is still applied here.
fn placed_glyphs(
    run: &TextRun,
    metrics: &crate::font::FontMetrics,
    glyph_map: &crate::font::GlyphMap,
) -> Vec<PlacedGlyph> {
    let th = run.horizontal_scale / 100.0 / folded_horizontal_scale(run);
    let fs = run.font_size;
    // Vertical writing (wmode 1, §9.7.4.3): the pen runs down the y axis by
    // the `/W2` vertical displacement (`w1y`, typically negative), and each
    // glyph is drawn displaced by −v — the vector from its horizontal origin
    // to its vertical origin (default `vx = w0/2`, `vy = /DW2[0]`), so the
    // glyph hangs centered below the pen point. Neither the advance nor `TJ`
    // adjustments are scaled by Th, which is horizontal-only; the `v` x
    // displacement is horizontal, so it is.
    let vertical = metrics.is_vertical();
    let mut cursor = 0.0;
    let mut out = Vec::new();
    for el in run.elements.iter() {
        match el {
            TextElement::Show(bytes) => {
                // The font decodes the byte string into codes/CIDs with PDF
                // advances (1 byte for simple fonts, 2 for Identity CID); the
                // CID→GID map turns a composite CID into its glyph id.
                for dc in metrics.decode(bytes) {
                    let word = if dc.word_space { run.word_spacing } else { 0.0 };
                    if let Some(vp) = vertical.then(|| metrics.vertical(dc.cid)).flatten() {
                        let (vx, vy) = vp.origin;
                        out.push(PlacedGlyph {
                            glyph: glyph_map.gid(dc.cid),
                            x: -(vx as f64) / 1000.0 * fs * th,
                            y: cursor + run.rise - (vy as f64) / 1000.0 * fs,
                        });
                        cursor += vp.advance as f64 / 1000.0 * fs + run.char_spacing + word;
                    } else {
                        out.push(PlacedGlyph {
                            glyph: glyph_map.gid(dc.cid),
                            x: cursor,
                            y: run.rise,
                        });
                        let w = dc.advance as f64 / 1000.0 * fs;
                        cursor += (w + run.char_spacing + word) * th;
                    }
                }
            }
            TextElement::Adjust(n) => {
                cursor += if vertical {
                    -n / 1000.0 * fs
                } else {
                    -n / 1000.0 * fs * th
                };
            }
        }
    }
    out
}

// Resolve a semantic color to a device-space IR paint. Device families convert
// exactly; parameterized spaces are approximated by component arity until the
// color phase resolves their tint transforms (documented deferral).
fn resolve_paint(color: &SemColor) -> Paint {
    let clamp = |v: f64| v.clamp(0.0, 1.0) as f32;
    match color {
        SemColor::DeviceGray(g) => {
            let [r, gg, b] = crate::color::gray_to_rgb(clamp(*g));
            Paint::Solid(rgba(r, gg, b))
        }
        SemColor::DeviceRgb(r, g, b) => Paint::Solid(rgba(clamp(*r), clamp(*g), clamp(*b))),
        SemColor::DeviceCmyk(c, m, y, k) => {
            let [r, g, b] = crate::color::cmyk_to_rgb(clamp(*c), clamp(*m), clamp(*y), clamp(*k));
            Paint::Solid(rgba(r, g, b))
        }
        SemColor::Components { values, .. } => {
            let v: Vec<f32> = values.iter().map(|x| clamp(*x)).collect();
            let [r, g, b] = match v.len() {
                1 => crate::color::gray_to_rgb(v[0]),
                3 => [v[0], v[1], v[2]],
                4 => crate::color::cmyk_to_rgb(v[0], v[1], v[2], v[3]),
                _ => [0.0, 0.0, 0.0],
            };
            Paint::Solid(rgba(r, g, b))
        }
        // An unresolved pattern paints nothing (transparent) rather than a
        // spurious solid — the resolved forms below carry the real paint.
        SemColor::Pattern { .. } => Paint::Solid(Color {
            r: 0.0,
            g: 0.0,
            b: 0.0,
            a: 0.0,
        }),
        SemColor::ShadingPattern { shading, matrix } => Paint::Shading {
            shading: ShadingId(shading.0),
            matrix: *matrix,
        },
        SemColor::TilingPattern { tiling, matrix } => Paint::Pattern {
            tiling: TilingId(tiling.0),
            matrix: *matrix,
        },
    }
}

fn rgba(r: f32, g: f32, b: f32) -> Color {
    Color { r, g, b, a: 1.0 }
}

fn color4(c: [f32; 4]) -> Color {
    Color {
        r: c[0],
        g: c[1],
        b: c[2],
        a: c[3],
    }
}

fn resource_key(object: Option<crate::object::ObjectId>, fallback: u32) -> ResourceKey {
    match object {
        Some(o) => ResourceKey {
            object_number: o.number,
            generation: o.generation,
            variant: 0,
        },
        None => ResourceKey {
            object_number: 0,
            generation: 0,
            variant: fallback,
        },
    }
}

/// Convert a semantic shading (already ramp-sampled) into the IR resource.
fn convert_shading(s: &SemShading) -> ShadingResource {
    let key = resource_key(s.object, 0);
    let ramp =
        |r: &[[f32; 4]]| -> std::sync::Arc<[Color]> { r.iter().map(|c| color4(*c)).collect() };
    let (shading_type, kind) = match &s.kind {
        SemShadingKind::Axial {
            coords,
            domain,
            extend,
            ramp: r,
            background,
        } => (
            2u8,
            ShadingKind::Axial {
                coords: [
                    coords[0] as f32,
                    coords[1] as f32,
                    coords[2] as f32,
                    coords[3] as f32,
                ],
                domain: [domain[0] as f32, domain[1] as f32],
                extend: *extend,
                ramp: ramp(r),
                background: background.map(color4),
            },
        ),
        SemShadingKind::Radial {
            coords,
            domain,
            extend,
            ramp: r,
            background,
        } => (
            3u8,
            ShadingKind::Radial {
                coords: [
                    coords[0] as f32,
                    coords[1] as f32,
                    coords[2] as f32,
                    coords[3] as f32,
                    coords[4] as f32,
                    coords[5] as f32,
                ],
                domain: [domain[0] as f32, domain[1] as f32],
                extend: *extend,
                ramp: ramp(r),
                background: background.map(color4),
            },
        ),
        SemShadingKind::MeshTriangles {
            shading_type,
            triangles,
            background,
        } => (
            *shading_type,
            ShadingKind::MeshTriangles {
                triangles: triangles
                    .iter()
                    .map(|t| {
                        [
                            mesh_vertex_ir(&t[0]),
                            mesh_vertex_ir(&t[1]),
                            mesh_vertex_ir(&t[2]),
                        ]
                    })
                    .collect(),
                background: background.map(color4),
            },
        ),
        SemShadingKind::MeshPatches {
            shading_type,
            patches,
            background,
        } => (
            *shading_type,
            ShadingKind::MeshPatches {
                patches: patches
                    .iter()
                    .map(|p| crate::page_ir::MeshPatch {
                        points: p.points.map(|q| [q[0] as f32, q[1] as f32]),
                        colors: p.colors.map(color4),
                    })
                    .collect(),
                background: background.map(color4),
            },
        ),
        SemShadingKind::FunctionGrid {
            domain,
            matrix,
            grid_w,
            grid_h,
            colors,
            background,
        } => (
            1u8,
            ShadingKind::FunctionGrid {
                domain: [
                    domain[0] as f32,
                    domain[1] as f32,
                    domain[2] as f32,
                    domain[3] as f32,
                ],
                matrix: *matrix,
                grid_w: *grid_w,
                grid_h: *grid_h,
                colors: colors.iter().map(|c| color4(*c)).collect(),
                background: background.map(color4),
            },
        ),
        SemShadingKind::Unsupported { background } => (
            0u8,
            ShadingKind::Unsupported {
                background: background.map(color4),
            },
        ),
    };
    ShadingResource {
        key,
        shading_type,
        kind,
        bbox: s.bbox,
    }
}

fn mesh_vertex_ir(v: &crate::content::semantic::SemMeshVertex) -> crate::page_ir::MeshVertex {
    crate::page_ir::MeshVertex {
        x: v.x as f32,
        y: v.y as f32,
        color: color4(v.color),
    }
}

/// Convert a semantic tiling pattern into the IR resource, lowering its cell
/// content into a nested [`CompiledPage`].
fn convert_tiling(t: &SemTiling) -> TilingPattern {
    let key = resource_key(t.object, 0);
    let cell = lower(&t.cell);
    TilingPattern {
        key,
        uncolored: t.uncolored,
        under_color: color4(t.under_color),
        bbox: [
            t.bbox[0] as f32,
            t.bbox[1] as f32,
            t.bbox[2] as f32,
            t.bbox[3] as f32,
        ],
        x_step: t.x_step as f32,
        y_step: t.y_step as f32,
        cell: std::sync::Arc::new(cell),
    }
}

fn paint_key(paint: &Paint) -> PaintKey {
    match paint {
        Paint::Solid(c) => {
            PaintKey::Solid([c.r.to_bits(), c.g.to_bits(), c.b.to_bits(), c.a.to_bits()])
        }
        Paint::Pattern { tiling, .. } => PaintKey::Pattern(tiling.0),
        Paint::Shading { shading, .. } => PaintKey::Shading(shading.0),
    }
}

fn path_key(data: &PathData) -> Vec<u8> {
    let mut key = Vec::with_capacity(data.verbs.len() + data.points.len() * 16 + 4);
    key.extend_from_slice(&(data.verbs.len() as u32).to_le_bytes());
    for v in data.verbs.iter() {
        key.push(*v as u8);
    }
    for p in data.points.iter() {
        key.extend_from_slice(&p.x.to_bits().to_le_bytes());
        key.extend_from_slice(&p.y.to_bits().to_le_bytes());
    }
    key
}

fn stroke_key(s: &StrokeStyle) -> Vec<u8> {
    let mut key = Vec::new();
    key.extend_from_slice(&s.width.to_bits().to_le_bytes());
    key.push(s.cap as u8);
    key.push(s.join as u8);
    key.extend_from_slice(&s.miter_limit.to_bits().to_le_bytes());
    key.extend_from_slice(&s.dash_phase.to_bits().to_le_bytes());
    for d in s.dash_pattern.iter() {
        key.extend_from_slice(&d.to_bits().to_le_bytes());
    }
    key
}

/// The public entry point.
pub(crate) fn lower(page: &SemanticPage) -> CompiledPage {
    Lowerer::new(page).lower()
}