franken_ocr 0.10.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
//! 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`.
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 sized = expected_sample_bytes(width, height, bpc, color_space);
            let sole_flate = !chained && terminal == "FlateDecode";
            let samples = decompressed_stream(doc, img.id, img.content, sole_flate, cap, sized)?;
            // /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.
///
/// `sized` is the byte count the declared dimensions decode to
/// ([`expected_sample_bytes`]); the bounded path allocates it up front.
fn decompressed_stream(
    doc: &Document,
    id: ObjectId,
    raw: &[u8],
    sole_flate: bool,
    cap: u64,
    sized: 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, sized)?
    {
        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`.
///
/// The output starts at `sized` bytes (at most `cap`), the size a well-formed
/// stream inflates to. On an exact fit `read_to_end` probes for the end instead
/// of doubling, so the raster is one allocation. A buffer grown by doubling
/// leaves its freed blocks in the macOS allocator: walking 100 Flate pages
/// grew the process footprint by about one raster per page, though no raster
/// was kept (U2-D0).
fn bounded_inflate(raw: &[u8], cap: u64, sized: u64) -> Result<Option<Vec<u8>>, String> {
    use std::io::Read;
    let mut out = Vec::with_capacity(usize::try_from(sized.min(cap)).unwrap_or(0));
    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)
}

/// The bytes a well-formed image of these dimensions decodes to: `height` rows
/// of `ceil(width × components × bpc / 8)` bytes. A color space whose component
/// count is not known here gives 0 (no size to plan for).
fn expected_sample_bytes(width: u32, height: u32, bpc: i64, color_space: &str) -> u64 {
    let comps: u64 = match color_space {
        "DeviceGray" | "CalGray" | "Indexed" | "I" => 1,
        "DeviceRGB" | "CalRGB" => 3,
        "DeviceCMYK" => 4,
        _ => return 0,
    };
    let row = u64::from(width)
        .saturating_mul(comps)
        .saturating_mul(bpc.clamp(1, 16) as u64)
        .div_ceil(8);
    row.saturating_mul(u64::from(height))
}

/// 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
}

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

    #[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.
    pub(crate) 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.
    pub(crate) 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)
    }

    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, 0)
            .expect("no error")
            .expect("inflated");
        assert_eq!(out.len(), 1000);

        // Sized to the stream, the output is one allocation of exactly that size.
        let out = bounded_inflate(&small, 4096, 1000)
            .expect("no error")
            .expect("inflated");
        assert_eq!((out.len(), out.capacity()), (1000, 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.
        // A size hint past the cap is held to the cap.
        let bomb = zlib_of(1_000_000);
        let err = bounded_inflate(&bomb, 4096, u64::MAX).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, 0)
                .expect("no error")
                .is_none()
        );
    }

    #[test]
    fn expected_sample_bytes_counts_packed_rows() {
        assert_eq!(
            expected_sample_bytes(1200, 1600, 8, "DeviceRGB"),
            1200 * 1600 * 3
        );
        assert_eq!(
            expected_sample_bytes(1200, 1600, 16, "DeviceGray"),
            1200 * 1600 * 2
        );
        // Sub-byte rows round up per row: 10 one-bit pixels take 2 bytes.
        assert_eq!(expected_sample_bytes(10, 3, 1, "DeviceGray"), 2 * 3);
        assert_eq!(expected_sample_bytes(5, 2, 4, "Indexed"), 3 * 2);
        // An unknown component count plans nothing.
        assert_eq!(expected_sample_bytes(64, 64, 8, "Separation"), 0);
    }
}