franken_ocr 0.9.0

Pure-Rust, CPU-hyper-optimized runner for the Baidu Unlimited-OCR model (single-binary CLI: focr)
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
//! Native PDF page rasterization in pure, memory-safe Rust (no FFI).
//!
//! `focr ocr file.pdf` renders each PDF page to an [`image::DynamicImage`] and
//! feeds it through the same preprocess + OCR pipeline a PNG/JPG would take, so
//! a PDF no longer has to be rasterized out of band (poppler / `pdftoppm`).
//!
//! ## Scope: the scanned-image fast path
//!
//! The overwhelming majority of OCR-input PDFs are *scans* — one full-page image
//! XObject per page. This module extracts that image and decodes it to RGB/gray
//! with the codecs the project already trusts ([`image`]'s JPEG via `zune-jpeg`,
//! `flate2`/`miniz_oxide` for `FlateDecode`, the pure-Rust [`fax`] crate for
//! CCITT Group 4). Everything here is pure Rust with no C/C++ FFI, matching the
//! project's no-FFI doctrine. `lopdf` (with `default-features` off) is the new
//! container parser; `fax` is already in the lock graph. We own the image-codec
//! decode dispatch below, so the parser is the only borrowed piece.
//!
//! ## Honest limits
//!
//! Two image codecs have **no** production-quality pure-Rust decoder and are
//! reported as a clear error rather than guessed at:
//! * `JPXDecode` (JPEG 2000) — every working decoder wraps OpenJPEG (C / FFI).
//! * `JBIG2Decode` — only C (`jbig2dec`) bindings exist.
//!
//! Born-digital PDFs whose pages are *vector / text* content (no full-page image
//! XObject) also fall outside this fast path: rasterizing arbitrary PDF vector
//! graphics needs a full content-stream interpreter + glyph rasterizer, tracked
//! separately. Such pages, and the two unsupported codecs, surface as
//! [`FocrError::InputDecode`] naming exactly what was unsupported, so the caller
//! can rasterize that PDF out of band and retry.

use std::path::Path;

use image::{DynamicImage, GrayImage, ImageBuffer, RgbImage};
use lopdf::xobject::PdfImage;
use lopdf::{Document, Object, ObjectId};

use crate::error::{FocrError, FocrResult};

/// The 5-byte header every PDF begins with (`%PDF-`).
const PDF_MAGIC: &[u8] = b"%PDF-";

/// Whether `path` names a PDF: a `.pdf` extension, or a `%PDF-` magic prefix.
///
/// The magic check makes the routing robust to extension-less inputs; it reads
/// only the first few bytes and never fails the caller (an unreadable file just
/// returns `false` and is handled as a normal image path downstream).
#[must_use]
pub fn looks_like_pdf(path: &Path) -> bool {
    if path
        .extension()
        .and_then(|e| e.to_str())
        .is_some_and(|e| e.eq_ignore_ascii_case("pdf"))
    {
        return true;
    }
    let Ok(mut file) = std::fs::File::open(path) else {
        return false;
    };
    let mut head = [0u8; 5];
    use std::io::Read;
    matches!(file.read_exact(&mut head), Ok(())) && head == PDF_MAGIC
}

/// Whether `bytes` look like a PDF: the `%PDF-` magic prefix. The in-memory
/// twin of [`looks_like_pdf`] for callers (the browser/wasm boundary) that
/// hold the document as bytes and have no filesystem path to sniff.
#[must_use]
pub fn looks_like_pdf_bytes(bytes: &[u8]) -> bool {
    bytes.starts_with(PDF_MAGIC)
}

/// A lazily-rendered PDF: the parsed document plus its page object ids in order.
///
/// Pages are rendered one at a time via [`PdfPages::render`] so a 600-page book
/// never materializes 600 rasters at once — the OCR driver pulls one page,
/// recognizes it, and drops it before the next.
pub struct PdfPages {
    doc: Document,
    /// Page object ids in 1-based page order (the value of `get_pages`).
    pages: Vec<ObjectId>,
}

impl PdfPages {
    /// Parse the PDF at `path`. Does not render any page yet.
    ///
    /// # Errors
    /// [`FocrError::InputDecode`] if the file cannot be parsed as a PDF.
    pub fn open(path: &Path) -> FocrResult<Self> {
        let doc = Document::load(path)
            .map_err(|e| FocrError::InputDecode(format!("parse PDF {}: {e}", path.display())))?;
        Self::from_document(doc, &path.display().to_string())
    }

    /// Parse a PDF already held in memory (the browser/wasm path, where the
    /// document arrives as bytes and there is no filesystem). Does not render
    /// any page yet. Everything downstream — page iteration, rasterization,
    /// rotation normalization — is the exact same code [`Self::open`] uses, so
    /// the two constructors render byte-identical pages for the same input.
    ///
    /// # Errors
    /// [`FocrError::InputDecode`] if the bytes cannot be parsed as a PDF.
    pub fn from_bytes(bytes: &[u8]) -> FocrResult<Self> {
        let doc = Document::load_mem(bytes)
            .map_err(|e| FocrError::InputDecode(format!("parse PDF bytes: {e}")))?;
        Self::from_document(doc, "bytes")
    }

    /// Shared tail of both constructors: collect the page ids in order and
    /// reject empty documents. `what` names the input in the error message
    /// (a path for [`Self::open`], `"bytes"` for [`Self::from_bytes`]).
    fn from_document(doc: Document, what: &str) -> FocrResult<Self> {
        let pages: Vec<ObjectId> = doc.get_pages().into_values().collect();
        if pages.is_empty() {
            return Err(FocrError::InputDecode(format!("PDF {what} has no pages")));
        }
        Ok(Self { doc, pages })
    }

    /// Number of pages.
    #[must_use]
    pub fn len(&self) -> usize {
        self.pages.len()
    }

    /// Whether the document has no pages (never true after [`Self::open`], which
    /// rejects empty documents — present for lint-clean `len()` ergonomics).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.pages.is_empty()
    }

    /// Render page `idx` (0-based) to a [`DynamicImage`], applying the page's
    /// `/Rotate`.
    ///
    /// Picks the largest image XObject on the page (the main scan, ignoring small
    /// preview/thumbnail images) and decodes it. See the module docs for the
    /// supported codecs.
    ///
    /// # Errors
    /// [`FocrError::InputDecode`] if the page has no decodable full-page image
    /// (vector/text page), or its image uses an unsupported codec
    /// (`JPXDecode` / `JBIG2Decode`) or color space.
    pub fn render(&self, idx: usize) -> FocrResult<DynamicImage> {
        let page_id = *self.pages.get(idx).ok_or_else(|| {
            FocrError::InputDecode(format!(
                "PDF page index {idx} out of range ({})",
                self.len()
            ))
        })?;

        let images = self.doc.get_page_images(page_id).map_err(|e| {
            FocrError::InputDecode(format!("read images on PDF page {}: {e}", idx + 1))
        })?;

        // Fast path: the page's scan is the largest image XObject. Skip the
        // small preview thumbnails some producers embed alongside the main scan.
        let main = images
            .iter()
            .max_by_key(|im| (im.width as i128) * (im.height as i128))
            .ok_or_else(|| {
                FocrError::InputDecode(format!(
                    "PDF page {} has no image XObject (vector/text PDFs are not supported by the \
                     native fast path; rasterize the PDF out of band, e.g. with pdftoppm, and pass \
                     the page images)",
                    idx + 1
                ))
            })?;

        let decoded = decode_image_xobject(&self.doc, main)
            .map_err(|e| FocrError::InputDecode(format!("PDF page {}: {e}", idx + 1)))?;

        let total_rotation = (page_rotation(&self.doc, page_id)
            + content_rotation(&self.doc, page_id))
        .rem_euclid(360);
        Ok(apply_rotation(decoded, total_rotation))
    }
}

/// Rotation (0/90/180/270 degrees, clockwise-positive like `/Rotate`) the
/// page CONTENT STREAM applies to its main image through the current
/// transformation matrix. Scanned-book PDFs often store the scan portrait
/// and place it with a rotated `cm` instead of a `/Rotate` entry — the
/// Cadwallader class: `/Rotate 0`, image 2480x3504, displayed landscape.
/// Ignoring the CTM fed the OCR model SIDEWAYS pages (bd-av64.11,
/// 2026-07-06: a spread decoded garbage until the 600s forward budget).
///
/// Only the matrix in effect at the FIRST `Do` is classified, and only
/// axis-aligned rotations are recognized (a skewed/general matrix returns
/// 0 — leave the raster as stored rather than guess).
fn content_rotation(doc: &Document, page_id: ObjectId) -> i64 {
    let Ok(content) = doc.get_and_decode_page_content(page_id) else {
        return 0;
    };
    let mut cm: Option<[f64; 4]> = None;
    for op in &content.operations {
        match op.operator.as_ref() {
            "cm" => {
                let v: Vec<f64> = op
                    .operands
                    .iter()
                    .filter_map(|o| o.as_float().ok().map(f64::from))
                    .collect();
                if v.len() >= 4 {
                    cm = Some([v[0], v[1], v[2], v[3]]);
                }
            }
            "Do" => break,
            _ => {}
        }
    }
    let Some([a, b, c, d]) = cm else { return 0 };
    if b.abs() > a.abs() && c.abs() > d.abs() {
        // Rotated placement: the image x-axis maps to the page y-axis. For
        // b > 0 (the Cadwallader matrix [0 595 -841 0]) the stored raster
        // reads upright after a 90-degree COUNTER-clockwise turn — verified
        // empirically against a reference render (mean-abs-diff 3.6 CCW vs
        // 19.6 CW on the title page), because raster row 0 sits at page
        // LEFT under this matrix. 270 here is the image crate's CCW.
        if b > 0.0 { 270 } else { 90 }
    } else if a < 0.0 && d < 0.0 {
        180
    } else {
        0
    }
}

/// Decode one image XObject to RGB/gray, dispatching on its terminal `/Filter`.
/// Detect and split a two-page book spread into (left, right) halves
/// (bd-av64.11). A spread is a rasterized page that is (a) noticeably wider
/// than tall (w/h >= 1.25 — portrait book pages side by side) AND (b) has a
/// low-ink vertical gutter near the horizontal center. Returns `None` when
/// either condition fails — a false split is worse than none (full-bleed
/// landscape photos, single-column landscape pages, spreads with a plate
/// crossing the gutter all pass through unsplit).
///
/// The gutter search: over the middle 20% of columns, a column qualifies
/// as gutter when its dark fraction is EITHER <= 0.5% (a blank inter-page
/// gap — flat-scanned loose pages) OR >= 60% (the dark binding shadow of a
/// bound book pressed into the scanner — the Cadwallader case). Text
/// columns are mixed black-on-white and match neither. Among qualifying
/// columns the one closest to the exact center wins. Decision + geometry
/// are logged by the caller under FOCR_TIMING.
#[must_use]
pub fn split_spread(img: &DynamicImage) -> Option<(DynamicImage, DynamicImage, u32)> {
    let (w, h) = (img.width(), img.height());
    if h == 0 || (f64::from(w) / f64::from(h)) < 1.25 {
        return None;
    }
    let gray = img.to_luma8();
    let ink_threshold = 160u8; // scanned text is near-black; paper near-white
    let (lo, hi) = (w * 2 / 5, w * 3 / 5); // middle 20% of columns
    let center = i64::from(w / 2);
    let mut best: Option<(i64, u32)> = None; // (distance to center, column)
    for x in lo..hi {
        let mut dark = 0u32;
        for y in 0..h {
            if gray.get_pixel(x, y).0[0] < ink_threshold {
                dark += 1;
            }
        }
        let dark_frac_pct_x10 = u64::from(dark) * 1000 / u64::from(h);
        let is_gutter = dark_frac_pct_x10 <= 5 || dark_frac_pct_x10 >= 600;
        if is_gutter {
            let dist = (i64::from(x) - center).abs();
            if best.is_none_or(|(d, _)| dist < d) {
                best = Some((dist, x));
            }
        }
    }
    let (_, gutter_x) = best?;
    let left = img.crop_imm(0, 0, gutter_x, h);
    let right = img.crop_imm(gutter_x, 0, w - gutter_x, h);
    Some((left, right, gutter_x))
}

fn decode_image_xobject(doc: &Document, img: &PdfImage) -> Result<DynamicImage, String> {
    let width = u32::try_from(img.width).map_err(|_| "negative image width".to_string())?;
    let height = u32::try_from(img.height).map_err(|_| "negative image height".to_string())?;
    if width == 0 || height == 0 {
        return Err("zero image dimension".to_string());
    }
    // Bound the DECLARED dimensions before any per-pixel allocation. A crafted PDF
    // can claim a gigapixel image and make a downstream `width*height` product
    // overflow `usize` (the CMYK guard) or reserve hundreds of TB (a raster
    // `Vec`). Real document scans are far below this (a 600-DPI A0 page is ~0.5
    // Gpx). `u32 * u32` is computed in `u64` so the check itself cannot overflow.
    const MAX_PIXELS: u64 = 1 << 30; // 1 Gpx
    if u64::from(width) * u64::from(height) > MAX_PIXELS {
        return Err(format!(
            "image dimensions {width}x{height} exceed the {MAX_PIXELS}-pixel maximum"
        ));
    }
    let bpc = img.bits_per_component.unwrap_or(8);
    let color_space = img.color_space.as_deref().unwrap_or("DeviceRGB");
    let filters = img.filters.clone().unwrap_or_default();
    let terminal = filters.last().map(String::as_str).unwrap_or("");

    // The image codecs (DCT/CCITT) consume `img.content` verbatim — the RAW stream,
    // with NO filters applied (lopdf's `get_page_images` does not decode). So a
    // multi-filter chain whose codec is preceded by an ASCII/Flate filter would
    // feed still-encoded bytes to the codec. Reject such chains with an accurate
    // message rather than a misleading "decode failed". (The raw-sample branch is
    // chain-safe: `decompressed_content` walks the whole filter chain.)
    let chained = filters.len() > 1;

    match terminal {
        "DCTDecode" if chained => Err(format!(
            "image filter chain {filters:?} ending in DCTDecode is unsupported (only a \
             sole DCTDecode filter); rasterize this PDF out of band and retry"
        )),
        // `content` is already the raw JPEG byte stream.
        "DCTDecode" => image::load_from_memory_with_format(img.content, image::ImageFormat::Jpeg)
            .map_err(|e| format!("JPEG (DCTDecode) decode failed: {e}")),

        // No pure-Rust decoder exists for either; be honest rather than wrong.
        "JPXDecode" => Err(
            "image uses JPXDecode (JPEG 2000), which has no pure-Rust decoder; \
                            rasterize this PDF out of band and retry"
                .to_string(),
        ),
        "JBIG2Decode" => Err("image uses JBIG2Decode, which has no pure-Rust decoder; \
                              rasterize this PDF out of band and retry"
            .to_string()),

        "CCITTFaxDecode" if chained => Err(format!(
            "image filter chain {filters:?} ending in CCITTFaxDecode is unsupported (only a \
             sole CCITTFaxDecode filter); rasterize this PDF out of band and retry"
        )),
        "CCITTFaxDecode" => decode_ccitt_g4(doc, img, width, height),

        // Raw samples behind a stream-compression filter (or none): inflate and
        // pack into an image buffer per the color space / bit depth.
        // `decompressed_content` handles Flate/LZW/ASCII85; ASCIIHexDecode is NOT
        // among them, so it falls through to the honest "unsupported" arm.
        "FlateDecode" | "LZWDecode" | "ASCII85Decode" | "" => {
            // Bound the inflate at 4x the samples the (already MAX_PIXELS-bounded)
            // declared dimensions could legitimately decode to, so a highly
            // compressed "zip bomb" stream cannot inflate to GBs before any length
            // check. Only a sole FlateDecode is inflated under this cap directly
            // (see `decompressed_stream`); LZW/ASCII85/chains keep lopdf's decoder.
            let cap = expected_sample_cap(width, height, bpc, color_space);
            let sole_flate = !chained && terminal == "FlateDecode";
            let samples = decompressed_stream(doc, img.id, img.content, sole_flate, cap)?;
            // /Indexed samples are palette indices, not color components: expand
            // them through the palette in the color-space array (GH#4 — lopdf's
            // `color_space` keeps only the array's first name, so the base +
            // lookup table must be re-read from the stream dict).
            if color_space == "Indexed" || color_space == "I" {
                return indexed_to_image(doc, img.id, &samples, width, height, bpc);
            }
            raw_samples_to_image(samples, width, height, bpc, color_space)
        }
        other => Err(format!("unsupported image filter {other}")),
    }
}

/// Re-fetch the image XObject as a stream and return its decompressed bytes,
/// bounding the inflate so a decompression bomb cannot OOM the process.
///
/// `raw` is `PdfImage::content`, the *raw* stream slice (still deflate/LZW/ASCII
/// encoded for those filters). lopdf's `Stream::decompressed_content` un-applies
/// the whole filter chain (including PNG/TIFF predictors) but materializes the
/// FULL inflated output before any length check — so a tiny, highly-compressed
/// FlateDecode stream (a "zip bomb", ~1000:1) inflates to GBs regardless of the
/// declared dimensions. For the common case — a SOLE FlateDecode with no predictor
/// — we inflate `raw` ourselves under `cap` and reject an overrun, allocating at
/// most `cap + 1` bytes. Everything else (LZW, ASCII85, filter chains, or a
/// `/Predictor > 1` that needs un-applying) falls back to `decompressed_content`;
/// those paths keep lopdf's residual unbounded-inflate risk.
fn decompressed_stream(
    doc: &Document,
    id: ObjectId,
    raw: &[u8],
    sole_flate: bool,
    cap: u64,
) -> Result<Vec<u8>, String> {
    let stream = doc
        .get_object(id)
        .and_then(Object::as_stream)
        .map_err(|e| format!("read image stream: {e}"))?;
    // Bounded fast path only when nothing downstream of the inflate is needed: a
    // single FlateDecode with no PNG/TIFF predictor. A predictor (>1) or any chain
    // would need lopdf's post-processing, so those keep the unbounded decoder. The
    // `?` still propagates a cap overrun (the bomb signal) before the `let Some`.
    if sole_flate
        && stream_predictor(stream) <= 1
        && let Some(out) = bounded_inflate(raw, cap)?
    {
        return Ok(out);
    }
    // The bounded path did not apply, or `raw` was not decodable as standalone zlib
    // (e.g. a headerless raw-deflate stream some producers emit); fall back to
    // lopdf's framing-tolerant decoder.
    stream
        .decompressed_content()
        .map_err(|e| format!("inflate image stream: {e}"))
}

/// The `/Predictor` in a stream's `/DecodeParms` (or its `/DP` abbreviation), or
/// `1` (no predictor) when absent. A sole-filter stream carries `DecodeParms` as a
/// single dict; the array form (filter chains) is never routed to the bounded path.
fn stream_predictor(stream: &lopdf::Stream) -> i64 {
    stream
        .dict
        .get(b"DecodeParms")
        .or_else(|_| stream.dict.get(b"DP"))
        .and_then(Object::as_dict)
        .ok()
        .and_then(|p| p.get(b"Predictor").ok())
        .and_then(|o| o.as_i64().ok())
        .unwrap_or(1)
}

/// Inflate a sole-FlateDecode (zlib) stream, refusing to allocate past `cap`.
///
/// PDF `/FlateDecode` is the zlib data format (RFC 1950), so `ZlibDecoder` is the
/// right reader. Reading just one byte past `cap` distinguishes "fits" from
/// "overruns" without buffering the whole bomb. Returns `Ok(None)` — *not* an error
/// — when `raw` is not valid standalone zlib, so the caller can fall back to lopdf's
/// framing-tolerant decoder; a clean inflate that overruns `cap` is the bomb signal
/// and is the only `Err`.
fn bounded_inflate(raw: &[u8], cap: u64) -> Result<Option<Vec<u8>>, String> {
    use std::io::Read;
    let mut out = Vec::new();
    if flate2::read::ZlibDecoder::new(raw)
        .take(cap.saturating_add(1))
        .read_to_end(&mut out)
        .is_err()
    {
        return Ok(None);
    }
    if out.len() as u64 > cap {
        return Err(format!(
            "decompressed image stream exceeds the {cap}-byte cap \
             (4x the expected sample size; possible decompression bomb)"
        ));
    }
    Ok(Some(out))
}

/// A generous cap on the inflated sample buffer: `4 × width × height × components ×
/// ceil(bpc/8)`.
///
/// The declared dimensions are already `MAX_PIXELS`-bounded, so this bounds a
/// decompression bomb to a small multiple of the bytes those dimensions could
/// legitimately decode to, instead of the GBs an adversarial stream would inflate
/// to. Unknown color spaces get the 4-component (CMYK) upper bound;
/// `raw_samples_to_image` rejects them afterward. `saturating_mul` keeps the
/// arithmetic from overflowing on hostile inputs.
///
/// `bpc` is clamped to the PDF-legal image range `1..=16` BEFORE it scales the cap:
/// a crafted `/BitsPerComponent` (e.g. `i64::MAX`) would otherwise blow the cap up
/// to `u64::MAX`, and a `cap` of `u64::MAX` makes the `take(cap + 1)` bound in
/// [`bounded_inflate`] effectively unbounded — re-opening the very bomb hole this
/// guards. The real bit-depth is validated separately in `raw_samples_to_image`.
fn expected_sample_cap(width: u32, height: u32, bpc: i64, color_space: &str) -> u64 {
    let comps: u64 = match color_space {
        "DeviceGray" | "CalGray" => 1,
        "DeviceRGB" | "CalRGB" => 3,
        _ => 4, // DeviceCMYK and any unknown: the largest plausible component count
    };
    // PDF images are 1/2/4/8/16 bpc; clamp so a hostile bit-depth cannot inflate
    // the cap past the bytes a real 16-bit image of these dimensions would need.
    let bytes_per_comp = (bpc.clamp(1, 16) as u64).div_ceil(8);
    u64::from(width)
        .saturating_mul(u64::from(height))
        .saturating_mul(comps)
        .saturating_mul(bytes_per_comp)
        .saturating_mul(4)
}

/// Build a [`DynamicImage`] from raw component samples.
fn raw_samples_to_image(
    samples: Vec<u8>,
    width: u32,
    height: u32,
    bpc: i64,
    color_space: &str,
) -> Result<DynamicImage, String> {
    let comps = match color_space {
        "DeviceRGB" | "CalRGB" => 3usize,
        "DeviceGray" | "CalGray" => 1,
        "DeviceCMYK" => 4,
        // ICCBased streams carry an /N component count; without resolving the
        // profile we cannot know it here, and Separation needs a tint transform.
        // (/Indexed is expanded earlier, in `indexed_to_image`.) Punt with a
        // clear message rather than render garbage.
        other => return Err(format!("unsupported color space {other}")),
    };

    match bpc {
        8 => match comps {
            3 => from_raw_rgb(width, height, samples),
            1 => from_raw_gray(width, height, samples),
            4 => Ok(DynamicImage::ImageRgb8(cmyk8_to_rgb(
                &samples, width, height,
            )?)),
            _ => Err(format!("unsupported component count {comps}")),
        },
        1 => bilevel_to_gray(&samples, width, height),
        16 => {
            // Samples are big-endian; downscale to 8-bpc by keeping the high byte.
            let high: Vec<u8> = samples.as_chunks::<2>().0.iter().map(|c| c[0]).collect();
            raw_samples_to_image(high, width, height, 8, color_space)
        }
        other => Err(format!("unsupported bits-per-component {other}")),
    }
}

fn from_raw_rgb(width: u32, height: u32, samples: Vec<u8>) -> Result<DynamicImage, String> {
    let buf: RgbImage = ImageBuffer::from_raw(width, height, samples)
        .ok_or_else(|| "RGB sample count does not match image dimensions".to_string())?;
    Ok(DynamicImage::ImageRgb8(buf))
}

fn from_raw_gray(width: u32, height: u32, samples: Vec<u8>) -> Result<DynamicImage, String> {
    let buf: GrayImage = ImageBuffer::from_raw(width, height, samples)
        .ok_or_else(|| "gray sample count does not match image dimensions".to_string())?;
    Ok(DynamicImage::ImageLuma8(buf))
}

/// Expand 8-bpc CMYK to RGB (the naive `r = 255 - min(255, c + k)` conversion;
/// adequate for OCR, which only needs legible contrast, not color fidelity).
fn cmyk8_to_rgb(samples: &[u8], width: u32, height: u32) -> Result<RgbImage, String> {
    let pixels = (width as usize) * (height as usize);
    if samples.len() < pixels * 4 {
        return Err("CMYK sample count does not match image dimensions".to_string());
    }
    let mut out = Vec::with_capacity(pixels * 3);
    for px in samples.as_chunks::<4>().0.iter().take(pixels) {
        let (c, m, y, k) = (
            u16::from(px[0]),
            u16::from(px[1]),
            u16::from(px[2]),
            u16::from(px[3]),
        );
        out.push((255 - (c + k).min(255)) as u8);
        out.push((255 - (m + k).min(255)) as u8);
        out.push((255 - (y + k).min(255)) as u8);
    }
    ImageBuffer::from_raw(width, height, out).ok_or_else(|| "CMYK->RGB pack failed".to_string())
}

/// Unpack MSB-first, byte-padded 1-bpc bilevel samples to an 8-bpc gray image.
fn bilevel_to_gray(samples: &[u8], width: u32, height: u32) -> Result<DynamicImage, String> {
    let row_bytes = (width as usize).div_ceil(8);
    if samples.len() < row_bytes * height as usize {
        return Err("bilevel sample count does not match image dimensions".to_string());
    }
    let mut out = Vec::with_capacity((width as usize) * (height as usize));
    for y in 0..height as usize {
        let row = &samples[y * row_bytes..];
        for x in 0..width as usize {
            let bit = (row[x / 8] >> (7 - (x % 8))) & 1;
            out.push(if bit == 1 { 255 } else { 0 });
        }
    }
    from_raw_gray(width, height, out)
}

/// Expand an `/Indexed` image XObject's palette indices to a direct-color image
/// (GH#4: `[/Indexed /DeviceRGB 1 <000000FFFFFF>]` at 1 bpc and kin).
///
/// The samples are `bpc`-wide palette indices (1/2/4/8 bits, MSB-first,
/// byte-padded rows — the same packing as bilevel). Each index selects one
/// entry of the lookup table declared in the color-space array; the entry's
/// component values are in the BASE color space. Bases resolved here:
/// `DeviceGray`/`CalGray` (1 component, renders gray), `DeviceRGB`/`CalRGB`
/// (3, renders RGB), `DeviceCMYK` (4, palette converted to RGB up front), and
/// `ICCBased` via its `/N` component count (treated as the matching device
/// space — adequate for OCR, which needs contrast, not colorimetry).
fn indexed_to_image(
    doc: &Document,
    id: ObjectId,
    samples: &[u8],
    width: u32,
    height: u32,
    bpc: i64,
) -> Result<DynamicImage, String> {
    let (comps, palette) = indexed_palette(doc, id)?;
    let indices = unpack_indices(samples, width, height, bpc)?;
    let last = (palette.len() / comps).saturating_sub(1);
    match comps {
        1 => {
            let out: Vec<u8> = indices
                .iter()
                .map(|&i| palette[(usize::from(i)).min(last)])
                .collect();
            from_raw_gray(width, height, out)
        }
        3 => {
            let mut out = Vec::with_capacity(indices.len() * 3);
            for &i in &indices {
                let at = (usize::from(i)).min(last) * 3;
                out.extend_from_slice(&palette[at..at + 3]);
            }
            from_raw_rgb(width, height, out)
        }
        other => Err(format!("unsupported Indexed component count {other}")),
    }
}

/// Resolve the `[/Indexed base hival lookup]` color-space array of an image
/// XObject: returns `(base component count, palette bytes)`, with the palette
/// zero-padded to exactly `(hival + 1) * comps` bytes (some producers truncate
/// the table; Acrobat treats missing entries as 0) and a `DeviceCMYK` base
/// already converted to RGB so the caller only sees 1- or 3-component entries.
fn indexed_palette(doc: &Document, id: ObjectId) -> Result<(usize, Vec<u8>), String> {
    let deref = |obj: &'_ Object| -> Result<Object, String> {
        doc.dereference(obj)
            .map(|(_, o)| o.clone())
            .map_err(|e| format!("resolve Indexed color space: {e}"))
    };
    let stream = doc
        .get_object(id)
        .and_then(Object::as_stream)
        .map_err(|e| format!("read image stream: {e}"))?;
    let cs = stream
        .dict
        .get(b"ColorSpace")
        .map_err(|e| format!("Indexed image without /ColorSpace: {e}"))?;
    let cs = deref(cs)?;
    let arr = cs
        .as_array()
        .map_err(|_| "Indexed /ColorSpace is not an array".to_string())?;
    if arr.len() < 4 {
        return Err(format!(
            "Indexed color space array has {} elements, expected 4",
            arr.len()
        ));
    }

    // Base color space: a name, or an array whose head names the family
    // ([/ICCBased <stream>], [/CalRGB <dict>], ...).
    let base = deref(&arr[1])?;
    let (base_name, base_arr): (Vec<u8>, Option<&[Object]>) = match &base {
        Object::Name(n) => (n.clone(), None),
        Object::Array(a) => {
            let head = a
                .first()
                .and_then(|o| o.as_name().ok())
                .ok_or_else(|| "Indexed base color-space array has no name".to_string())?;
            (head.to_vec(), Some(a.as_slice()))
        }
        _ => return Err("unsupported Indexed base color space object".to_string()),
    };
    let comps: usize = match base_name.as_slice() {
        b"DeviceGray" | b"CalGray" | b"G" => 1,
        b"DeviceRGB" | b"CalRGB" | b"RGB" => 3,
        b"DeviceCMYK" | b"CMYK" => 4,
        b"ICCBased" => {
            // /N of the ICC profile stream: 1, 3, or 4 components.
            let profile = base_arr
                .and_then(|a| a.get(1))
                .ok_or_else(|| "ICCBased Indexed base without a profile stream".to_string())?;
            let profile = deref(profile)?;
            let n = profile
                .as_stream()
                .ok()
                .and_then(|s| s.dict.get(b"N").ok())
                .and_then(|o| o.as_i64().ok())
                .ok_or_else(|| "ICCBased Indexed base without /N".to_string())?;
            usize::try_from(n)
                .ok()
                .filter(|n| [1, 3, 4].contains(n))
                .ok_or_else(|| {
                    format!("ICCBased Indexed base with unsupported component count {n}")
                })?
        }
        other => {
            return Err(format!(
                "unsupported Indexed base color space {}",
                String::from_utf8_lossy(other)
            ));
        }
    };

    // hival: the maximum valid index. Indexed images are at most 8 bpc, so a
    // conforming hival fits in a byte; clamp a hostile value rather than let it
    // size the padded palette allocation below.
    let hival = deref(&arr[2])?
        .as_i64()
        .map_err(|_| "Indexed hival is not an integer".to_string())?;
    if !(0..=255).contains(&hival) {
        return Err(format!("Indexed hival {hival} outside 0..=255"));
    }
    #[allow(clippy::cast_sign_loss)] // 0..=255 checked above
    let entries = hival as usize + 1;

    // Lookup table: a (possibly hex) string, or a stream of the packed bytes.
    let lookup = deref(&arr[3])?;
    let mut palette: Vec<u8> = match &lookup {
        Object::String(bytes, _) => bytes.clone(),
        Object::Stream(s) => s
            .decompressed_content()
            .map_err(|e| format!("inflate Indexed palette stream: {e}"))?,
        _ => return Err("Indexed palette is neither a string nor a stream".to_string()),
    };
    palette.resize(entries * comps, 0);

    // A CMYK palette is converted once, per entry, so the pixel loop only ever
    // sees gray or RGB (adequate-for-OCR conversion, same as `cmyk8_to_rgb`).
    if comps == 4 {
        let rgb = cmyk8_to_rgb(&palette, u32::try_from(entries).unwrap_or(1), 1)?;
        return Ok((3, rgb.into_raw()));
    }
    Ok((comps, palette))
}

/// Unpack MSB-first, byte-padded-row index samples (1/2/4/8 bpc — the only
/// legal depths for `/Indexed` images) to one `u8` index per pixel.
fn unpack_indices(samples: &[u8], width: u32, height: u32, bpc: i64) -> Result<Vec<u8>, String> {
    let bits: usize = match bpc {
        1 | 2 | 4 | 8 => usize::try_from(bpc).expect("bpc in 1..=8"),
        other => {
            return Err(format!(
                "unsupported bits-per-component {other} for Indexed"
            ));
        }
    };
    let (w, h) = (width as usize, height as usize);
    let row_bytes = (w * bits).div_ceil(8);
    if samples.len() < row_bytes * h {
        return Err("indexed sample count does not match image dimensions".to_string());
    }
    let mask = if bits == 8 { 0xFF } else { (1u8 << bits) - 1 };
    let mut out = Vec::with_capacity(w * h);
    for y in 0..h {
        let row = &samples[y * row_bytes..];
        for x in 0..w {
            let bit = x * bits;
            out.push((row[bit / 8] >> (8 - bits - bit % 8)) & mask);
        }
    }
    Ok(out)
}

/// Decode a CCITT Group 4 (T.6) fax image XObject to an 8-bpc gray image.
///
/// Group 4 is `/K < 0`; G3 (`/K >= 0`) is reported unsupported. `/BlackIs1`
/// flips the 0=black / 255=white convention.
fn decode_ccitt_g4(
    doc: &Document,
    img: &PdfImage,
    width: u32,
    height: u32,
) -> Result<DynamicImage, String> {
    use fax::Color;
    use fax::decoder::{decode_g4, pels};

    let stream = doc
        .get_object(img.id)
        .and_then(Object::as_stream)
        .map_err(|e| format!("read CCITT stream: {e}"))?;

    // /DecodeParms (or the /DP abbreviation) may be a dict or an array of dicts;
    // the single-dict form is what scanners emit for a lone CCITT filter.
    let parms = stream
        .dict
        .get(b"DecodeParms")
        .or_else(|_| stream.dict.get(b"DP"))
        .and_then(Object::as_dict)
        .ok();
    let param_i64 = |key: &[u8], default: i64| -> i64 {
        parms
            .and_then(|p| p.get(key).ok())
            .and_then(|o| o.as_i64().ok())
            .unwrap_or(default)
    };
    let k = param_i64(b"K", 0);
    let columns = u16::try_from(param_i64(b"Columns", 1728)).unwrap_or(1728);
    let black_is_1 = parms
        .and_then(|p| p.get(b"BlackIs1").ok())
        .and_then(|o| o.as_bool().ok())
        .unwrap_or(false);

    if k >= 0 {
        return Err(
            "CCITTFaxDecode K>=0 (Group 3) is not supported; only Group 4 (K<0)".to_string(),
        );
    }
    let cols = if columns == 0 {
        u16::try_from(width).unwrap_or(1728)
    } else {
        columns
    };
    let (black, white) = if black_is_1 {
        (255u8, 0u8)
    } else {
        (0u8, 255u8)
    };
    let rows_hint = u16::try_from(height).ok().filter(|&h| h != 0);

    // Grow as the decode emits lines; do NOT pre-reserve from the declared
    // `/Height`, which is an attacker-controlled `u32` (`cols * height` could
    // reserve hundreds of TB and abort). The real output is bounded by the actual
    // G4 stream — `decode_g4` stops at end-of-data or `rows_hint` rows.
    let mut out: Vec<u8> = Vec::new();
    decode_g4(img.content.iter().copied(), cols, rows_hint, |line| {
        out.extend(pels(line, cols).map(|c| match c {
            Color::Black => black,
            Color::White => white,
        }));
    })
    .ok_or_else(|| "CCITT Group 4 decode failed".to_string())?;

    let decoded_rows = u32::try_from(out.len() / usize::from(cols).max(1)).unwrap_or(0);
    from_raw_gray(u32::from(cols), decoded_rows, out)
}

/// The page's `/Rotate` (an inheritable multiple of 90, clockwise), normalized
/// to `0 | 90 | 180 | 270`.
fn page_rotation(doc: &Document, page_id: ObjectId) -> i64 {
    inherited(doc, page_id, b"Rotate")
        .and_then(|o| o.as_i64().ok())
        .unwrap_or(0)
        .rem_euclid(360)
}

/// Apply a clockwise rotation (0/90/180/270) to the rendered page.
fn apply_rotation(img: DynamicImage, degrees: i64) -> DynamicImage {
    match degrees {
        90 => DynamicImage::ImageRgba8(image::imageops::rotate90(&img)),
        180 => DynamicImage::ImageRgba8(image::imageops::rotate180(&img)),
        270 => DynamicImage::ImageRgba8(image::imageops::rotate270(&img)),
        _ => img,
    }
}

/// Resolve an inheritable page attribute, walking `/Parent` (bounded against a
/// cyclic page tree).
fn inherited<'a>(doc: &'a Document, mut id: ObjectId, key: &[u8]) -> Option<&'a Object> {
    for _ in 0..64 {
        let dict = doc.get_dictionary(id).ok()?;
        if let Ok(value) = dict.get(key) {
            return Some(value);
        }
        id = dict.get(b"Parent").and_then(Object::as_reference).ok()?;
    }
    None
}

// ── The document walk ──────────────────────────────────────────────────────
//
// ONE implementation of "OCR every selected page of this document", shared by
// every front end. It lived in `cli.rs` first, which meant the CLI was the only
// caller that got it right: the iOS app and the browser playground each grew
// their own page loop, and each got the error classification and the page-spec
// grammar subtly wrong. Anything that walks a PDF goes through here.
//
// The walk is parameterized by the recognizer rather than by an engine type, so
// the same code serves the CLI (`OcrEngine`), the `focr-ios` boundary
// (`OcrModel`), and any embedder — none of which share a type.

/// Resolve a `--pages` spec into 0-based page indices, in source order with
/// duplicates removed. `None` selects the whole document.
///
/// Out-of-range and malformed pages are **usage errors naming the real page
/// count**, not silently dropped: asking for page 400 of a 200-page book is a
/// mistake worth reporting, and a frontend that quietly ignores it leaves the
/// user believing pages were read that never were.
///
/// # Errors
/// [`FocrError::Usage`] for an unparseable element, page 0 (pages are 1-based),
/// a page past the end, a reversed range, or an empty element.
pub fn select_pages(spec: Option<&str>, page_count: usize) -> FocrResult<Vec<usize>> {
    let Some(spec) = spec else {
        return Ok((0..page_count).collect());
    };
    let usage = |what: &str| {
        FocrError::Usage(format!(
            "--pages {spec:?}: {what} (expected 1-based pages/ranges like \"1,5-9\"; \
             this document has {page_count} page(s))"
        ))
    };
    let parse_one = |tok: &str| -> FocrResult<usize> {
        let n: usize = tok
            .trim()
            .parse()
            .map_err(|_| usage(&format!("unparseable page {tok:?}")))?;
        if n == 0 {
            return Err(usage("page 0 (pages are 1-based)"));
        }
        if n > page_count {
            return Err(usage(&format!("page {n} is out of range")));
        }
        Ok(n - 1)
    };
    let mut selected = Vec::new();
    let mut seen = vec![false; page_count];
    for part in spec.split(',') {
        let part = part.trim();
        if part.is_empty() {
            return Err(usage("empty element"));
        }
        let range = match part.split_once('-') {
            Some((a, b)) => {
                let (a, b) = (parse_one(a)?, parse_one(b)?);
                if a > b {
                    return Err(usage(&format!("reversed range {part:?}")));
                }
                a..=b
            }
            None => {
                let n = parse_one(part)?;
                n..=n
            }
        };
        for idx in range {
            if !seen[idx] {
                seen[idx] = true;
                selected.push(idx);
            }
        }
    }
    selected.sort_unstable();
    Ok(selected)
}

/// Whether an error ends the whole document walk or just this page.
///
/// The distinction is the load-bearing part of a document run, and it is easy to
/// get wrong in the permissive direction. A page whose codec has no pure-Rust
/// decoder is *this page's* problem — one JPEG-2000 page in a 300-page scan must
/// not throw away the other 299. But a missing model, a cancelled run, or a
/// format mismatch is the *document's* problem: skipping 300 pages one at a time
/// and reporting "300 skipped" would be a slow, confusing way to say "you never
/// had a model loaded".
///
/// This set is exactly the one `cli.rs` has used for its own page loops since
/// before this function existed, and it must stay that way: the CLI's behavior
/// is the documented one, and a divergence here would silently change what
/// `focr ocr book.pdf` does. In particular `Timeout` is deliberately NOT fatal —
/// the stage budget is per-forward, so one slow page is a skip, not a verdict on
/// the rest of the book.
#[must_use]
pub fn is_fatal_to_document(err: &FocrError) -> bool {
    matches!(
        err,
        FocrError::ModelNotFound(_) | FocrError::Cancelled | FocrError::FormatMismatch(_)
    )
}

/// One page that was read.
#[derive(Debug, Clone)]
pub struct DocumentPage {
    /// 1-based source page number.
    pub page: usize,
    /// The page's recognized text.
    pub markdown: String,
    /// Grounded spans, when the recognizer produced them.
    pub layout: Vec<crate::native_engine::LayoutSpan>,
    /// Wall time for this page alone.
    pub duration: std::time::Duration,
}

/// One page that was refused, and why.
#[derive(Debug, Clone)]
pub struct SkippedPage {
    /// 1-based source page number.
    pub page: usize,
    /// The engine's own message — "JPXDecode: no pure-Rust decoder", not a
    /// paraphrase.
    pub reason: String,
}

/// The result of walking a document.
#[derive(Debug, Clone, Default)]
pub struct DocumentOutcome {
    /// Pages that read, in source order.
    pub pages: Vec<DocumentPage>,
    /// Pages that were skipped, in source order.
    pub skipped: Vec<SkippedPage>,
    /// Pages in the source document.
    pub total_pages: usize,
}

impl DocumentOutcome {
    /// The whole document as one markdown string, pages joined by a blank line
    /// — the same shape `focr ocr book.pdf` writes.
    #[must_use]
    pub fn markdown(&self) -> String {
        self.pages
            .iter()
            .map(|p| p.markdown.trim_end())
            .collect::<Vec<_>>()
            .join("\n\n")
    }

    /// Total wall time across the pages that read.
    #[must_use]
    pub fn duration(&self) -> std::time::Duration {
        self.pages.iter().map(|p| p.duration).sum()
    }
}

/// Progress across a document walk, reported before and after each page so a
/// caller can drive a ledger and a total-progress bar without tracking state.
#[derive(Debug, Clone, Copy)]
pub enum DocumentEvent<'a> {
    /// About to render and read this page. `index` is 0-based within the
    /// selection; `selected` is how many pages the walk will attempt.
    PageStarted {
        page: usize,
        index: usize,
        selected: usize,
    },
    /// This page read.
    PageDone(&'a DocumentPage),
    /// This page was refused; the walk continues.
    PageSkipped(&'a SkippedPage),
}

/// Walk `selected` pages of `pages`, rendering each and handing it to
/// `recognize`.
///
/// `recognize` receives the 1-based page number and the rasterized image, and
/// returns that page's text plus layout. Errors are classified by
/// [`is_fatal_to_document`]: a fatal one aborts and propagates; anything else is
/// recorded as a skip and the walk continues.
///
/// The walk is **sequential by construction**, and that is a correctness
/// property, not a simplification: the engine admits one forward at a time (each
/// page already fans out across every core internally), so concurrent pages
/// would not be faster and would multiply peak memory by the number in flight.
///
/// # Errors
/// A fatal per-page error, or [`FocrError::InputDecode`] when the selection
/// produced no readable page at all — carrying the first page's reason, so
/// "nothing worked" still says why.
pub fn walk_document<R>(
    pages: &PdfPages,
    selected: &[usize],
    mut recognize: R,
    observer: &mut dyn FnMut(DocumentEvent<'_>),
) -> FocrResult<DocumentOutcome>
where
    R: FnMut(usize, DynamicImage) -> FocrResult<(String, Vec<crate::native_engine::LayoutSpan>)>,
{
    let mut outcome = DocumentOutcome {
        total_pages: pages.len(),
        ..Default::default()
    };
    // Kept as text, not as the error: the reason a page was refused is what a
    // caller needs, and the first one is the most useful when nothing worked.
    let mut first_reason: Option<String> = None;

    for (index, &idx) in selected.iter().enumerate() {
        let page = idx + 1;
        observer(DocumentEvent::PageStarted {
            page,
            index,
            selected: selected.len(),
        });

        let started = std::time::Instant::now();
        let attempt = pages
            .render(idx)
            .and_then(|image| recognize(page, image))
            .map(|(markdown, layout)| DocumentPage {
                page,
                markdown,
                layout,
                duration: started.elapsed(),
            });

        match attempt {
            Ok(done) => {
                outcome.pages.push(done);
                observer(DocumentEvent::PageDone(
                    outcome.pages.last().expect("just pushed"),
                ));
            }
            Err(err) if is_fatal_to_document(&err) => return Err(err),
            Err(err) => {
                let reason = err.to_string();
                if first_reason.is_none() {
                    first_reason = Some(reason.clone());
                }
                outcome.skipped.push(SkippedPage { page, reason });
                observer(DocumentEvent::PageSkipped(
                    outcome.skipped.last().expect("just pushed"),
                ));
            }
        }
    }

    if outcome.pages.is_empty() {
        return Err(FocrError::InputDecode(first_reason.unwrap_or_else(|| {
            "the page selection produced no decodable pages".to_string()
        })));
    }
    Ok(outcome)
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── page selection ─────────────────────────────────────────────────────

    #[test]
    fn no_spec_selects_every_page() {
        assert_eq!(select_pages(None, 4).expect("ok"), vec![0, 1, 2, 3]);
    }

    #[test]
    fn spec_is_1_based_sorted_and_deduped() {
        assert_eq!(select_pages(Some("3,1"), 5).expect("ok"), vec![0, 2]);
        assert_eq!(select_pages(Some("2-4"), 5).expect("ok"), vec![1, 2, 3]);
        // Overlapping ranges collapse rather than repeating a page.
        assert_eq!(
            select_pages(Some("1-3,2-4"), 5).expect("ok"),
            vec![0, 1, 2, 3]
        );
    }

    #[test]
    fn out_of_range_is_a_usage_error_naming_the_page_count() {
        // Silently dropping this is the bug: the user would believe page 9 was
        // read. The message has to name the real count.
        let err = select_pages(Some("9"), 3).expect_err("must reject");
        assert!(matches!(err, FocrError::Usage(_)), "got {err:?}");
        let text = err.to_string();
        assert!(text.contains("out of range"), "{text}");
        assert!(text.contains("3 page(s)"), "{text}");
    }

    #[test]
    fn zero_reversed_and_empty_elements_are_rejected() {
        for bad in ["0", "3-1", "1,,2", "x"] {
            let err = select_pages(Some(bad), 5).expect_err(bad);
            assert!(matches!(err, FocrError::Usage(_)), "{bad}: {err:?}");
        }
    }

    // ── fatal vs skippable ─────────────────────────────────────────────────

    #[test]
    fn only_document_level_failures_are_fatal() {
        // A page the renderer cannot decode is this page's problem.
        assert!(!is_fatal_to_document(&FocrError::InputDecode(
            "JPXDecode: no pure-Rust decoder".into()
        )));
        assert!(!is_fatal_to_document(&FocrError::NotImplemented(
            "x".into()
        )));
        // The stage budget is PER FORWARD, so one slow page is a skip, not a
        // verdict on the rest of the book. This matches what cli.rs has always
        // done; changing it would silently change `focr ocr book.pdf`.
        assert!(!is_fatal_to_document(&FocrError::Timeout("x".into())));
        // These say the run itself is over; skipping 300 pages one at a time
        // would be a slow way to report "you never had a model".
        assert!(is_fatal_to_document(&FocrError::ModelNotFound("x".into())));
        assert!(is_fatal_to_document(&FocrError::Cancelled));
        assert!(is_fatal_to_document(&FocrError::FormatMismatch("x".into())));
    }

    // ── outcome assembly ───────────────────────────────────────────────────

    #[test]
    fn markdown_joins_pages_with_a_blank_line_and_trims() {
        let outcome = DocumentOutcome {
            pages: vec![
                DocumentPage {
                    page: 1,
                    markdown: "one\n\n".into(),
                    layout: Vec::new(),
                    duration: std::time::Duration::from_millis(10),
                },
                DocumentPage {
                    page: 2,
                    markdown: "two".into(),
                    layout: Vec::new(),
                    duration: std::time::Duration::from_millis(20),
                },
            ],
            skipped: vec![SkippedPage {
                page: 3,
                reason: "JBIG2Decode".into(),
            }],
            total_pages: 3,
        };
        assert_eq!(outcome.markdown(), "one\n\ntwo");
        assert_eq!(outcome.duration(), std::time::Duration::from_millis(30));
    }

    fn synth_page(w: u32, h: u32, text_cols: &[(u32, u32)]) -> DynamicImage {
        // White canvas with black "text block" columns [x0, x1).
        let mut img = image::GrayImage::from_pixel(w, h, image::Luma([255u8]));
        for &(x0, x1) in text_cols {
            for x in x0..x1 {
                for y in (10..h.saturating_sub(10)).step_by(3) {
                    img.put_pixel(x, y, image::Luma([20u8]));
                }
            }
        }
        DynamicImage::ImageLuma8(img)
    }

    /// bd-av64.11: a synthetic spread (text left + right, blank center
    /// gutter) splits at the gutter; the negatives pass through unsplit.
    #[test]
    fn split_spread_positive_and_negatives() {
        // POSITIVE: 1600x1000 spread, text at [100,700) and [900,1500).
        let spread = synth_page(1600, 1000, &[(100, 700), (900, 1500)]);
        let (left, right, gx) = split_spread(&spread).expect("spread splits");
        assert!((700..=900).contains(&gx), "gutter near center: {gx}");
        assert_eq!(left.width() + right.width(), 1600);
        assert_eq!(left.height(), 1000);
        // NEGATIVE 1: portrait page (aspect below the spread threshold).
        assert!(split_spread(&synth_page(1000, 1600, &[(100, 900)])).is_none());
        // NEGATIVE 2: landscape but ink crosses the center (a full-width
        // plate/table) — no blank gutter, no split.
        assert!(split_spread(&synth_page(1600, 1000, &[(100, 1500)])).is_none());
        // NEGATIVE 3: landscape blank page — a gutter exists but splitting a
        // blank is harmless; the heuristic DOES split it (blank center
        // qualifies). Accepting this is deliberate: both halves are blank,
        // and OCR of blank halves is cheap + correct.
        // NEGATIVE 4: single centered column (text crosses the middle).
        assert!(split_spread(&synth_page(1600, 1000, &[(600, 1000)])).is_none());
        // POSITIVE 2: a bound book's DARK binding shadow as the gutter (the
        // Cadwallader case) — a solid dark band at the center qualifies.
        let mut bound = synth_page(1600, 1000, &[(100, 700), (900, 1500)]).to_luma8();
        for x in 780..820 {
            for y in 0..1000 {
                bound.put_pixel(x, y, image::Luma([30u8]));
            }
        }
        let bound = DynamicImage::ImageLuma8(bound);
        let (_, _, gx) = split_spread(&bound).expect("binding shadow splits");
        assert!((780..=820).contains(&gx), "split inside the shadow: {gx}");
    }

    #[test]
    fn looks_like_pdf_by_extension() {
        assert!(looks_like_pdf(Path::new("/x/y/scan.pdf")));
        assert!(looks_like_pdf(Path::new("/x/y/scan.PDF")));
        assert!(!looks_like_pdf(Path::new("/x/y/page.png")));
        // Missing file, no .pdf extension -> not a PDF (no panic).
        assert!(!looks_like_pdf(Path::new("/no/such/file.bin")));
    }

    #[test]
    fn looks_like_pdf_bytes_by_magic() {
        assert!(looks_like_pdf_bytes(b"%PDF-1.5\n..."));
        assert!(!looks_like_pdf_bytes(b"\x89PNG\r\n\x1a\n"));
        assert!(!looks_like_pdf_bytes(b"%PDF")); // truncated magic
        assert!(!looks_like_pdf_bytes(b""));
    }

    /// `from_bytes(read(file))` must produce byte-identical page rasters to
    /// `open(file)` — the two constructors share every line after the parser
    /// entry, and this pins that contract for the wasm boundary that rides
    /// `from_bytes`.
    #[test]
    fn from_bytes_renders_identically_to_open() {
        use image::{ImageBuffer, Rgb};
        use lopdf::{Stream, dictionary};
        use std::io::Cursor;

        let (w, h) = (24u32, 18u32);
        let src = DynamicImage::ImageRgb8(ImageBuffer::from_fn(w, h, |x, y| {
            Rgb([(x * 10) as u8, (y * 13) as u8, 200])
        }));
        let mut jpeg = Vec::new();
        src.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
            .expect("encode jpeg");
        let image = Stream::new(
            dictionary! {
                "Type" => "XObject",
                "Subtype" => "Image",
                "Width" => i64::from(w),
                "Height" => i64::from(h),
                "ColorSpace" => "DeviceRGB",
                "BitsPerComponent" => 8,
                "Filter" => "DCTDecode",
            },
            jpeg,
        )
        .with_compression(false);
        let path = build_single_page_pdf(Some(image));

        let by_path = PdfPages::open(&path).expect("open by path");
        let bytes = std::fs::read(&path).expect("read pdf bytes");
        assert!(looks_like_pdf_bytes(&bytes));
        let by_bytes = PdfPages::from_bytes(&bytes).expect("open from bytes");

        assert_eq!(by_path.len(), by_bytes.len());
        let a = by_path.render(0).expect("render by path");
        let b = by_bytes.render(0).expect("render from bytes");
        assert_eq!((a.width(), a.height()), (b.width(), b.height()));
        assert_eq!(
            a.to_rgb8().into_raw(),
            b.to_rgb8().into_raw(),
            "open() and from_bytes() rasters must be byte-identical"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// Junk bytes must surface the precise parse error, not a panic; an empty
    /// but well-formed document must report "has no pages".
    #[test]
    fn from_bytes_rejects_junk_with_named_error() {
        let Err(err) = PdfPages::from_bytes(b"not a pdf at all") else {
            panic!("junk must error");
        };
        assert!(err.to_string().contains("parse PDF bytes"), "got: {err}");
    }

    #[test]
    fn bilevel_unpacks_msb_first() {
        // 8x1: 0b1010_0000 -> px0=255, px1=0, px2=255, rest 0.
        let img = bilevel_to_gray(&[0b1010_0000], 8, 1).expect("bilevel");
        let gray = img.to_luma8();
        assert_eq!(gray.get_pixel(0, 0).0[0], 255);
        assert_eq!(gray.get_pixel(1, 0).0[0], 0);
        assert_eq!(gray.get_pixel(2, 0).0[0], 255);
        assert_eq!(gray.get_pixel(3, 0).0[0], 0);
    }

    #[test]
    fn cmyk_pure_black_and_white() {
        // pixel0 = pure K (black), pixel1 = all-zero (white).
        let rgb = cmyk8_to_rgb(&[0, 0, 0, 255, 0, 0, 0, 0], 2, 1).expect("cmyk");
        assert_eq!(rgb.get_pixel(0, 0).0, [0, 0, 0]);
        assert_eq!(rgb.get_pixel(1, 0).0, [255, 255, 255]);
    }

    #[test]
    fn rgb_dimension_mismatch_errors() {
        // 3 bytes is not enough for a 2x2 RGB image (needs 12).
        assert!(from_raw_rgb(2, 2, vec![1, 2, 3]).is_err());
    }

    /// A minimal one-page PDF whose only object is a single image XObject — the
    /// shared scaffold for the round-trip tests. `image_xobject` is `None` for a
    /// page with no image (the vector/text case).
    /// A synthetic document whose pages each either carry a full-page image or
    /// carry none. An image-free page is exactly the "born-digital vector page"
    /// the renderer refuses, so this builds a document with real skips in it
    /// without needing a JPEG-2000 fixture.
    fn build_multi_page_pdf(pages_spec: &[Option<lopdf::Stream>]) -> std::path::PathBuf {
        use lopdf::{Object, dictionary};

        let mut doc = lopdf::Document::with_version("1.5");
        let pages_id = doc.new_object_id();
        let mut kids: Vec<Object> = Vec::new();
        for image_xobject in pages_spec {
            let resources = match image_xobject.clone() {
                Some(stream) => {
                    let image_id = doc.add_object(stream);
                    dictionary! { "XObject" => dictionary! { "Im0" => image_id } }
                }
                None => dictionary! {},
            };
            let resources_id = doc.add_object(resources);
            let page_id = doc.add_object(dictionary! {
                "Type" => "Page",
                "Parent" => pages_id,
                "Resources" => resources_id,
                "MediaBox" => vec![0_i64.into(), 0_i64.into(), 100_i64.into(), 100_i64.into()],
            });
            kids.push(page_id.into());
        }
        let count = i64::try_from(pages_spec.len()).expect("page count fits");
        doc.objects.insert(
            pages_id,
            Object::Dictionary(dictionary! {
                "Type" => "Pages",
                "Kids" => kids,
                "Count" => count,
            }),
        );
        let catalog_id = doc.add_object(dictionary! {
            "Type" => "Catalog",
            "Pages" => pages_id,
        });
        doc.trailer.set("Root", catalog_id);

        use std::sync::atomic::{AtomicU32, Ordering};
        static SEQ: AtomicU32 = AtomicU32::new(0);
        let path = std::env::temp_dir().join(format!(
            "focr_pdf_walk_{}_{}.pdf",
            std::process::id(),
            SEQ.fetch_add(1, Ordering::Relaxed)
        ));
        doc.save(&path).expect("save synthesized pdf");
        path
    }

    /// A small JPEG image XObject, the "this page is a scan" case.
    fn jpeg_xobject() -> lopdf::Stream {
        use image::{ImageBuffer, Rgb};
        use lopdf::{Stream, dictionary};
        use std::io::Cursor;

        let (w, h) = (16u32, 12u32);
        let src = DynamicImage::ImageRgb8(ImageBuffer::from_fn(w, h, |x, _| {
            Rgb([(x * 16) as u8, 64, 128])
        }));
        let mut jpeg = Vec::new();
        src.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
            .expect("encode jpeg");
        Stream::new(
            dictionary! {
                "Type" => "XObject",
                "Subtype" => "Image",
                "Width" => i64::from(w),
                "Height" => i64::from(h),
                "ColorSpace" => "DeviceRGB",
                "BitsPerComponent" => 8,
                "Filter" => "DCTDecode",
            },
            jpeg,
        )
        .with_compression(false)
    }

    #[test]
    fn walk_reads_every_readable_page_and_skips_the_rest_with_reasons() {
        // Page 2 has no image: the renderer refuses it, and the walk must carry
        // on — one bad page in a book cannot cost the other pages.
        let path = build_multi_page_pdf(&[Some(jpeg_xobject()), None, Some(jpeg_xobject())]);
        let pages = PdfPages::open(&path).expect("open");
        let selected = select_pages(None, pages.len()).expect("all pages");

        let mut events: Vec<String> = Vec::new();
        let outcome = walk_document(
            &pages,
            &selected,
            |page, image| {
                assert!(image.width() > 0, "page {page} rasterized");
                Ok((format!("text of page {page}"), Vec::new()))
            },
            &mut |event| match event {
                DocumentEvent::PageStarted {
                    page,
                    index,
                    selected,
                } => {
                    events.push(format!("start {page} ({index}/{selected})"));
                }
                DocumentEvent::PageDone(p) => events.push(format!("done {}", p.page)),
                DocumentEvent::PageSkipped(s) => events.push(format!("skip {}", s.page)),
            },
        )
        .expect("walk succeeds when at least one page reads");

        assert_eq!(outcome.total_pages, 3);
        assert_eq!(
            outcome.pages.iter().map(|p| p.page).collect::<Vec<_>>(),
            vec![1, 3]
        );
        assert_eq!(outcome.skipped.len(), 1);
        assert_eq!(outcome.skipped[0].page, 2);
        assert!(
            !outcome.skipped[0].reason.is_empty(),
            "a skip must carry the engine's reason"
        );
        assert_eq!(outcome.markdown(), "text of page 1\n\ntext of page 3");
        // Observed in source order, one start per attempted page.
        assert_eq!(
            events,
            vec![
                "start 1 (0/3)".to_string(),
                "done 1".into(),
                "start 2 (1/3)".into(),
                "skip 2".into(),
                "start 3 (2/3)".into(),
                "done 3".into(),
            ]
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn walk_aborts_immediately_on_a_document_level_failure() {
        let path = build_multi_page_pdf(&[Some(jpeg_xobject()), Some(jpeg_xobject())]);
        let pages = PdfPages::open(&path).expect("open");
        let selected = select_pages(None, pages.len()).expect("all pages");

        let mut attempts = 0usize;
        let err = walk_document(
            &pages,
            &selected,
            |_page, _image| {
                attempts += 1;
                Err(FocrError::ModelNotFound("no model".into()))
            },
            &mut |_| {},
        )
        .expect_err("a missing model ends the run");

        assert!(matches!(err, FocrError::ModelNotFound(_)), "got {err:?}");
        // The point of the classification: it must NOT grind through the rest of
        // the book reporting one skip per page.
        assert_eq!(
            attempts, 1,
            "aborted on the first page, not after all of them"
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn walk_with_no_readable_page_errors_with_the_first_reason() {
        let path = build_multi_page_pdf(&[None, None]);
        let pages = PdfPages::open(&path).expect("open");
        let selected = select_pages(None, pages.len()).expect("all pages");

        let err = walk_document(
            &pages,
            &selected,
            |_page, _image| Ok((String::new(), Vec::new())),
            &mut |_| {},
        )
        .expect_err("nothing readable");
        assert!(matches!(err, FocrError::InputDecode(_)), "got {err:?}");
        // "nothing worked" still has to say WHY.
        assert!(!err.to_string().is_empty());
        let _ = std::fs::remove_file(&path);
    }

    fn build_single_page_pdf(image_xobject: Option<lopdf::Stream>) -> std::path::PathBuf {
        use lopdf::{Object, dictionary};

        let mut doc = lopdf::Document::with_version("1.5");
        let pages_id = doc.new_object_id();
        let resources = match image_xobject {
            Some(stream) => {
                let image_id = doc.add_object(stream);
                dictionary! { "XObject" => dictionary! { "Im0" => image_id } }
            }
            None => dictionary! {},
        };
        let resources_id = doc.add_object(resources);
        let page_id = doc.add_object(dictionary! {
            "Type" => "Page",
            "Parent" => pages_id,
            "Resources" => resources_id,
            "MediaBox" => vec![0_i64.into(), 0_i64.into(), 100_i64.into(), 100_i64.into()],
        });
        doc.objects.insert(
            pages_id,
            Object::Dictionary(dictionary! {
                "Type" => "Pages",
                "Kids" => vec![page_id.into()],
                "Count" => 1,
            }),
        );
        let catalog_id = doc.add_object(dictionary! {
            "Type" => "Catalog",
            "Pages" => pages_id,
        });
        doc.trailer.set("Root", catalog_id);

        // Unique temp path per call (tests run on parallel threads): pid + a
        // process-wide atomic sequence, not a stack-address pointer.
        use std::sync::atomic::{AtomicU32, Ordering};
        static SEQ: AtomicU32 = AtomicU32::new(0);
        let path = std::env::temp_dir().join(format!(
            "focr_pdf_test_{}_{}.pdf",
            std::process::id(),
            SEQ.fetch_add(1, Ordering::Relaxed)
        ));
        doc.save(&path).expect("save synthesized pdf");
        path
    }

    /// End-to-end through the real `lopdf` parser: synthesize a one-page PDF whose
    /// only XObject is a `DCTDecode` (JPEG) image, reopen it via [`PdfPages`], and
    /// confirm the page renders to an image of the JPEG's dimensions. Exercises
    /// `get_page_images` + the `DCTDecode` dispatch + the JPEG decoder — the
    /// dominant real scanned-PDF path.
    #[test]
    fn render_dctdecode_pdf_page_decodes_jpeg_xobject() {
        use image::{ImageBuffer, Rgb};
        use lopdf::{Stream, dictionary};
        use std::io::Cursor;

        let (w, h) = (16u32, 12u32);
        let src = DynamicImage::ImageRgb8(ImageBuffer::from_fn(w, h, |x, _| {
            Rgb([(x * 16) as u8, 64, 128])
        }));
        let mut jpeg = Vec::new();
        src.write_to(&mut Cursor::new(&mut jpeg), image::ImageFormat::Jpeg)
            .expect("encode jpeg");

        let image = Stream::new(
            dictionary! {
                "Type" => "XObject",
                "Subtype" => "Image",
                "Width" => i64::from(w),
                "Height" => i64::from(h),
                "ColorSpace" => "DeviceRGB",
                "BitsPerComponent" => 8,
                "Filter" => "DCTDecode",
            },
            jpeg,
        )
        .with_compression(false);
        let path = build_single_page_pdf(Some(image));

        let pages = PdfPages::open(&path).expect("open synthesized pdf");
        assert_eq!(pages.len(), 1);
        let page = pages.render(0).expect("render dct page");
        // The JPEG decoder reports the encoded dimensions back unchanged.
        assert_eq!((page.width(), page.height()), (w, h));

        let _ = std::fs::remove_file(&path);
    }

    /// A page with no image XObject (a vector/text page) must surface the precise,
    /// actionable [`FocrError::InputDecode`] rather than rendering garbage.
    #[test]
    fn render_image_free_page_errors_clearly() {
        let path = build_single_page_pdf(None);
        let pages = PdfPages::open(&path).expect("open synthesized pdf");
        assert_eq!(pages.len(), 1);
        let err = pages.render(0).expect_err("vector page must error");
        let msg = err.to_string();
        assert!(
            msg.contains("no image XObject"),
            "expected an actionable no-image message, got: {msg}"
        );
        let _ = std::fs::remove_file(&path);
    }

    /// A crafted image claiming gigapixel dimensions must be rejected by the
    /// dimension guard BEFORE any per-pixel allocation (no 280 TB reserve / no
    /// `width*height` overflow), regardless of the (never-reached) codec content.
    #[test]
    fn oversized_pdf_image_is_rejected_before_allocation() {
        use lopdf::{Stream, dictionary};

        let image = Stream::new(
            dictionary! {
                "Type" => "XObject",
                "Subtype" => "Image",
                "Width" => 100_000_i64,
                "Height" => 100_000_i64, // 1e10 px, far over the 1 Gpx cap
                "ColorSpace" => "DeviceRGB",
                "BitsPerComponent" => 8,
                "Filter" => "DCTDecode",
            },
            vec![0u8; 16], // dummy content; the guard fires before it is touched
        )
        .with_compression(false);
        let path = build_single_page_pdf(Some(image));
        let err = PdfPages::open(&path)
            .expect("open")
            .render(0)
            .expect_err("oversized image must error");
        assert!(err.to_string().contains("exceed"), "got: {err}");
        let _ = std::fs::remove_file(&path);
    }

    /// A multi-filter chain ending in an image codec (`[ASCII85Decode, DCTDecode]`)
    /// must be rejected with an accurate "chain ... unsupported" message rather than
    /// feeding still-ASCII-encoded bytes to the JPEG decoder.
    #[test]
    fn chained_filter_image_is_rejected() {
        use lopdf::{Object, Stream, dictionary};

        let image = Stream::new(
            dictionary! {
                "Type" => "XObject",
                "Subtype" => "Image",
                "Width" => 4_i64,
                "Height" => 4_i64,
                "ColorSpace" => "DeviceRGB",
                "BitsPerComponent" => 8,
                "Filter" => Object::Array(vec![
                    Object::Name(b"ASCII85Decode".to_vec()),
                    Object::Name(b"DCTDecode".to_vec()),
                ]),
            },
            vec![0u8; 16],
        )
        .with_compression(false);
        let path = build_single_page_pdf(Some(image));
        let err = PdfPages::open(&path)
            .expect("open")
            .render(0)
            .expect_err("chained filter must error");
        assert!(err.to_string().contains("chain"), "got: {err}");
        let _ = std::fs::remove_file(&path);
    }

    /// GH#4 end-to-end: a 1-bpc `[/Indexed /DeviceRGB 1 <000000FFFFFF>]` image —
    /// the exact shape of the reporter's file — must decode by expanding each
    /// packed index bit through the palette, not error "unsupported color space
    /// Indexed".
    #[test]
    fn render_indexed_1bpc_rgb_pdf_page_expands_palette() {
        use lopdf::{Object, Stream, StringFormat, dictionary};

        // 8x2, 1 bpc: row 0 = 0b1010_0000, row 1 = 0b0101_0000 (rows are
        // byte-padded, so each row is exactly one byte here).
        let image = Stream::new(
            dictionary! {
                "Type" => "XObject",
                "Subtype" => "Image",
                "Width" => 8_i64,
                "Height" => 2_i64,
                "ColorSpace" => Object::Array(vec![
                    Object::Name(b"Indexed".to_vec()),
                    Object::Name(b"DeviceRGB".to_vec()),
                    Object::Integer(1),
                    // <000000FFFFFF>: index 0 = black, index 1 = white.
                    Object::String(vec![0, 0, 0, 255, 255, 255], StringFormat::Hexadecimal),
                ]),
                "BitsPerComponent" => 1,
            },
            vec![0b1010_0000, 0b0101_0000],
        )
        .with_compression(false);
        let path = build_single_page_pdf(Some(image));

        let page = PdfPages::open(&path)
            .expect("open")
            .render(0)
            .expect("indexed 1-bpc page renders");
        assert_eq!((page.width(), page.height()), (8, 2));
        let rgb = page.to_rgb8();
        // Row 0: px0 white, px1 black, px2 white...
        assert_eq!(rgb.get_pixel(0, 0).0, [255, 255, 255]);
        assert_eq!(rgb.get_pixel(1, 0).0, [0, 0, 0]);
        assert_eq!(rgb.get_pixel(2, 0).0, [255, 255, 255]);
        // Row 1 is the complement.
        assert_eq!(rgb.get_pixel(0, 1).0, [0, 0, 0]);
        assert_eq!(rgb.get_pixel(1, 1).0, [255, 255, 255]);
        let _ = std::fs::remove_file(&path);
    }

    /// 8-bpc Indexed with a DeviceGray base and the palette in a REFERENCED
    /// stream object (both spec-legal forms the string-palette test does not
    /// cover), plus an out-of-range index that must clamp to hival, not panic.
    #[test]
    fn render_indexed_8bpc_gray_palette_stream_clamps_out_of_range() {
        use lopdf::{Object, Stream, dictionary};

        // Palette: 3 gray entries 10, 128, 250 (hival 2), as a stream object.
        // Build the PDF manually so the palette can live behind a reference.
        let mut doc = lopdf::Document::with_version("1.5");
        let palette_id = doc
            .add_object(Stream::new(dictionary! {}, vec![10u8, 128, 250]).with_compression(false));
        let image = Stream::new(
            dictionary! {
                "Type" => "XObject",
                "Subtype" => "Image",
                "Width" => 4_i64,
                "Height" => 1_i64,
                "ColorSpace" => Object::Array(vec![
                    Object::Name(b"Indexed".to_vec()),
                    Object::Name(b"DeviceGray".to_vec()),
                    Object::Integer(2),
                    Object::Reference(palette_id),
                ]),
                "BitsPerComponent" => 8,
            },
            // Index 9 is past hival=2 and must clamp to entry 2 (250).
            vec![0u8, 1, 2, 9],
        )
        .with_compression(false);
        let image_id = doc.add_object(image);
        let pages_id = doc.new_object_id();
        let resources_id = doc.add_object(dictionary! {
            "XObject" => dictionary! { "Im0" => image_id },
        });
        let page_id = doc.add_object(dictionary! {
            "Type" => "Page",
            "Parent" => pages_id,
            "Resources" => resources_id,
            "MediaBox" => vec![0_i64.into(), 0_i64.into(), 100_i64.into(), 100_i64.into()],
        });
        doc.objects.insert(
            pages_id,
            Object::Dictionary(dictionary! {
                "Type" => "Pages",
                "Kids" => vec![page_id.into()],
                "Count" => 1,
            }),
        );
        let catalog_id = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id });
        doc.trailer.set("Root", catalog_id);
        let path =
            std::env::temp_dir().join(format!("focr_pdf_indexed_gray_{}.pdf", std::process::id()));
        doc.save(&path).expect("save synthesized pdf");

        let page = PdfPages::open(&path)
            .expect("open")
            .render(0)
            .expect("indexed gray page renders");
        let gray = page.to_luma8();
        assert_eq!(
            [
                gray.get_pixel(0, 0).0[0],
                gray.get_pixel(1, 0).0[0],
                gray.get_pixel(2, 0).0[0],
                gray.get_pixel(3, 0).0[0],
            ],
            [10, 128, 250, 250], // last pixel: index 9 clamped to hival entry
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn unpack_indices_handles_all_legal_depths() {
        // 4 bpc, 3px wide: 0xAB 0xC0 -> [0xA, 0xB, 0xC].
        assert_eq!(
            unpack_indices(&[0xAB, 0xC0], 3, 1, 4).expect("4 bpc"),
            vec![0xA, 0xB, 0xC]
        );
        // 2 bpc, 5px wide (row pads to 2 bytes): 0b11_10_01_00, 0b01_000000.
        assert_eq!(
            unpack_indices(&[0b1110_0100, 0b0100_0000], 5, 1, 2).expect("2 bpc"),
            vec![3, 2, 1, 0, 1]
        );
        // 8 bpc is the identity.
        assert_eq!(
            unpack_indices(&[7, 0, 255], 3, 1, 8).expect("8 bpc"),
            vec![7, 0, 255]
        );
        // 16 bpc is not a legal Indexed depth.
        assert!(unpack_indices(&[0, 0], 1, 1, 16).is_err());
        // Truncated sample buffers error rather than panic.
        assert!(unpack_indices(&[0xFF], 8, 2, 1).is_err());
    }

    #[test]
    fn expected_sample_cap_clamps_a_hostile_bit_depth() {
        // A real 16-bit RGB image of these dims: 4 * w*h * 3 comps * 2 bytes.
        assert_eq!(
            expected_sample_cap(1024, 1024, 16, "DeviceRGB"),
            4 * 1024 * 1024 * 3 * 2
        );
        // A crafted /BitsPerComponent must NOT inflate the cap past the 16-bpc
        // figure — an unclamped i64::MAX would saturate `cap` to u64::MAX, which
        // makes bounded_inflate's `take(cap + 1)` effectively unbounded and
        // re-opens the decompression-bomb hole this guard exists to close.
        assert_eq!(
            expected_sample_cap(1024, 1024, i64::MAX, "DeviceRGB"),
            expected_sample_cap(1024, 1024, 16, "DeviceRGB")
        );
        // A zero/negative bit depth clamps UP to 1 (never a zero or giant cap).
        assert_eq!(expected_sample_cap(8, 8, -5, "DeviceGray"), 4 * 8 * 8);
        // Unknown color spaces take the 4-component (CMYK) upper bound.
        assert_eq!(expected_sample_cap(2, 2, 8, "Indexed"), 4 * 2 * 2 * 4);
    }

    #[test]
    fn bounded_inflate_passes_small_streams_and_rejects_a_bomb() {
        use std::io::Write;
        let zlib_of = |n: usize| -> Vec<u8> {
            let mut enc = flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::best());
            enc.write_all(&vec![0u8; n]).expect("encode");
            enc.finish().expect("finish")
        };

        // Inflates within the cap → Ok(Some(bytes)).
        let small = zlib_of(1000);
        let out = bounded_inflate(&small, 4096)
            .expect("no error")
            .expect("inflated");
        assert_eq!(out.len(), 1000);

        // A ~1000:1 "zip bomb" that inflates far past the cap → Err (the bomb signal),
        // having allocated at most cap + 1 bytes rather than the full inflation.
        let bomb = zlib_of(1_000_000);
        let err = bounded_inflate(&bomb, 4096).expect_err("bomb must be rejected");
        assert!(err.contains("cap"), "got: {err}");

        // Not standalone zlib → Ok(None) so the caller falls back to lopdf.
        assert!(
            bounded_inflate(b"not a zlib stream", 4096)
                .expect("no error")
                .is_none()
        );
    }
}