stet-pdf-reader 0.1.0

PDF parser and renderer
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
// stet-pdf-reader
// Copyright (c) 2026 Scott Bowman
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Stream decode filter chain for PDF streams.

use crate::error::PdfError;
use crate::objects::PdfDict;

/// A single decode filter.
#[derive(Debug, Clone, PartialEq)]
pub enum Filter {
    FlateDecode,
    LZWDecode,
    ASCIIHexDecode,
    ASCII85Decode,
    RunLengthDecode,
    DCTDecode,
    CCITTFaxDecode,
    JPXDecode,
    JBIG2Decode,
}

/// Parse the /Filter and /DecodeParms entries from a stream dict.
/// Pass a resolver to dereference indirect `/Filter` or `/DecodeParms` values.
/// `None` is acceptable during bootstrap (xref stream parsing) where no resolver
/// exists yet and indirect references don't occur.
pub fn parse_filters(
    dict: &PdfDict,
    resolver: Option<&crate::resolver::Resolver>,
) -> Result<(Vec<Filter>, Vec<Option<PdfDict>>), PdfError> {
    let filter_obj = match dict.get(b"Filter") {
        Some(obj) => obj,
        None => return Ok((Vec::new(), Vec::new())),
    };

    // Resolve indirect Filter reference if needed
    let resolved_filter;
    let filter_obj = if let crate::objects::PdfObj::Ref(_, _) = filter_obj {
        if let Some(r) = resolver {
            resolved_filter = r.deref(filter_obj).unwrap_or_else(|_| filter_obj.clone());
            &resolved_filter
        } else {
            filter_obj
        }
    } else {
        filter_obj
    };

    let filter_names: Vec<&[u8]> = match filter_obj {
        crate::objects::PdfObj::Name(n) => vec![n.as_slice()],
        crate::objects::PdfObj::Array(arr) => {
            // Array elements may also be indirect references
            arr.iter()
                .filter_map(|o| {
                    if let Some(n) = o.as_name() {
                        return Some(n);
                    }
                    None
                })
                .collect()
        }
        _ => return Ok((Vec::new(), Vec::new())),
    };

    let mut filters = Vec::new();
    for name in &filter_names {
        filters.push(filter_from_name(name)?);
    }

    // Parse DecodeParms (single dict or array of dicts/refs)
    let dp_obj = dict.get(b"DecodeParms");
    let resolved_dp;
    let dp_obj = match dp_obj {
        Some(crate::objects::PdfObj::Ref(_, _)) if resolver.is_some() => {
            resolved_dp = resolver.unwrap().deref(dp_obj.unwrap()).ok();
            resolved_dp.as_ref()
        }
        other => other,
    };

    let parms = match dp_obj {
        Some(crate::objects::PdfObj::Dict(d)) => vec![Some(d.clone())],
        Some(crate::objects::PdfObj::Array(arr)) => arr
            .iter()
            .map(|o| match o {
                crate::objects::PdfObj::Dict(d) => Some(d.clone()),
                crate::objects::PdfObj::Ref(_, _) if resolver.is_some() => resolver
                    .unwrap()
                    .deref(o)
                    .ok()
                    .and_then(|r| r.as_dict().cloned()),
                _ => None,
            })
            .collect(),
        _ => vec![None; filters.len()],
    };

    // Pad parms to match filters length
    let mut parms = parms;
    while parms.len() < filters.len() {
        parms.push(None);
    }

    // Fill in CCITT decode hints from the image/stream dict when missing.
    // PDF image streams always carry /Width and /Height, but malformed producers
    // sometimes omit the matching /Columns and /Rows in /DecodeParms. Without
    // /Rows the decoder has no target height and bails out mid-stream on
    // damaged Group 4 data. Copy them over so the CCITT filter can cap its
    // row count and pad short output with white scanlines.
    for (i, filter) in filters.iter().enumerate() {
        if *filter != Filter::CCITTFaxDecode {
            continue;
        }
        let dp = parms[i].get_or_insert_with(PdfDict::new);
        if dp.get_int(b"Columns").is_none()
            && let Some(w) = dict.get_int(b"Width")
        {
            dp.insert(b"Columns".to_vec(), crate::objects::PdfObj::Int(w));
        }
        if dp.get_int(b"Rows").is_none()
            && let Some(h) = dict.get_int(b"Height")
        {
            dp.insert(b"Rows".to_vec(), crate::objects::PdfObj::Int(h));
        }
    }

    Ok((filters, parms))
}

fn filter_from_name(name: &[u8]) -> Result<Filter, PdfError> {
    match name {
        b"FlateDecode" | b"Fl" => Ok(Filter::FlateDecode),
        b"LZWDecode" | b"LZW" => Ok(Filter::LZWDecode),
        b"ASCIIHexDecode" | b"AHx" => Ok(Filter::ASCIIHexDecode),
        b"ASCII85Decode" | b"A85" => Ok(Filter::ASCII85Decode),
        b"RunLengthDecode" | b"RL" => Ok(Filter::RunLengthDecode),
        b"DCTDecode" | b"DCT" => Ok(Filter::DCTDecode),
        b"CCITTFaxDecode" | b"CCF" => Ok(Filter::CCITTFaxDecode),
        b"JPXDecode" | b"JPX" => Ok(Filter::JPXDecode),
        b"JBIG2Decode" | b"JBIG2" => Ok(Filter::JBIG2Decode),
        // Tolerate truncated filter names from malformed PDFs
        _ if name.starts_with(b"Flate") => Ok(Filter::FlateDecode),
        _ if name.starts_with(b"LZW") => Ok(Filter::LZWDecode),
        _ if name.starts_with(b"ASCIIHex") => Ok(Filter::ASCIIHexDecode),
        _ if name.starts_with(b"ASCII85") => Ok(Filter::ASCII85Decode),
        _ if name.starts_with(b"RunLength") => Ok(Filter::RunLengthDecode),
        _ if name.starts_with(b"CCITT") => Ok(Filter::CCITTFaxDecode),
        _ if name.starts_with(b"JPX") => Ok(Filter::JPXDecode),
        _ if name.starts_with(b"JBIG2") => Ok(Filter::JBIG2Decode),
        _ => Err(PdfError::UnsupportedFilter(
            String::from_utf8_lossy(name).into(),
        )),
    }
}

/// Decode raw stream data through a chain of filters.
pub fn decode_stream(
    raw_data: &[u8],
    filters: &[Filter],
    decode_parms: &[Option<PdfDict>],
    jbig2_globals: Option<&[u8]>,
) -> Result<Vec<u8>, PdfError> {
    let mut data = raw_data.to_vec();

    for (i, filter) in filters.iter().enumerate() {
        let parms = decode_parms.get(i).and_then(|p| p.as_ref());
        data = match filter {
            Filter::FlateDecode => decode_flate(&data, parms)?,
            Filter::LZWDecode => decode_lzw(&data, parms)?,
            Filter::ASCIIHexDecode => decode_ascii_hex(&data)?,
            Filter::ASCII85Decode => decode_ascii85(&data)?,
            Filter::RunLengthDecode => decode_run_length(&data)?,
            Filter::DCTDecode => decode_dct(&data)?,
            Filter::CCITTFaxDecode => decode_ccittfax(&data, parms)?,
            #[cfg(feature = "jpx")]
            Filter::JPXDecode => decode_jpx(&data)?,
            #[cfg(not(feature = "jpx"))]
            Filter::JPXDecode => {
                return Err(PdfError::UnsupportedFilter("JPXDecode (disabled)".into()));
            }
            Filter::JBIG2Decode => decode_jbig2(&data, jbig2_globals)?,
        };
    }

    Ok(data)
}

/// FlateDecode (zlib/deflate).
fn decode_flate(data: &[u8], parms: Option<&PdfDict>) -> Result<Vec<u8>, PdfError> {
    // Try zlib first. If it ends with an error (truncated output),
    // also try raw deflate (skip 2-byte zlib header) and pick the longer result.
    let (zlib_output, zlib_clean, _) = decode_flate_inner(data, true);
    let output = if zlib_clean {
        zlib_output?
    } else {
        // Zlib hit an error (corrupt checksum, etc).  Try raw deflate (skip
        // 2-byte zlib header) and prefer it only when zlib clearly truncated
        // mid-stream.  If zlib consumed (nearly) all input, the data is
        // complete — the error is just a bad trailing checksum, and raw
        // deflate may decode garbage past the stream boundary.
        let zlib_data = zlib_output.unwrap_or_default();
        if data.len() > 2 {
            let (raw_output, _, _) = decode_flate_inner(&data[2..], false);
            let raw_data = raw_output.unwrap_or_default();
            if raw_data.len() > zlib_data.len()
                && raw_data[..zlib_data.len()] == zlib_data[..]
                && looks_like_valid_continuation(&raw_data, zlib_data.len())
            {
                // Raw produced more data, the shared prefix matches, and the
                // extra bytes look like valid content — zlib truncated early
                // due to a checksum error; use the fuller raw output.
                raw_data
            } else if !zlib_data.is_empty() {
                zlib_data
            } else if !raw_data.is_empty() {
                raw_data
            } else {
                return Err(PdfError::DecompressionError(
                    "flate: decompression failed".into(),
                ));
            }
        } else if !zlib_data.is_empty() {
            zlib_data
        } else {
            return Err(PdfError::DecompressionError(
                "flate: decompression failed".into(),
            ));
        }
    };

    // Apply predictor if specified
    if let Some(parms) = parms {
        let predictor = parms.get_int(b"Predictor").unwrap_or(1);
        if predictor > 1 {
            return apply_predictor(&output, parms, predictor);
        }
    }

    Ok(output)
}

/// Check whether the extra bytes (past `start`) in `data` look like valid
/// stream content rather than garbage from decoding past a stream boundary.
/// Checks a sample of bytes for printable ASCII / whitespace, which is typical
/// for PDF content streams but not for accidentally-decoded binary data.
fn looks_like_valid_continuation(data: &[u8], start: usize) -> bool {
    if start >= data.len() {
        return false;
    }
    // Sample the first 64 bytes of the continuation
    let sample = &data[start..data.len().min(start + 64)];
    let printable = sample
        .iter()
        .filter(|&&b| b.is_ascii_graphic() || b.is_ascii_whitespace())
        .count();
    // If >80% of sampled bytes are printable, it's likely valid content
    printable * 5 >= sample.len() * 4
}

/// Inner flate decompression. `zlib` = true uses zlib wrapper, false uses raw deflate.
/// Returns (Result<data>, clean) where clean=true means StreamEnd was reached normally.
/// Returns (decompressed_data, clean_finish, bytes_consumed).
fn decode_flate_inner(data: &[u8], zlib: bool) -> (Result<Vec<u8>, PdfError>, bool, usize) {
    use flate2::Decompress;

    let mut decompressor = Decompress::new(zlib);
    let mut output = Vec::with_capacity(data.len() * 3);
    let mut buf = [0u8; 8192];
    let mut input_offset = 0;

    loop {
        let before_in = decompressor.total_in() as usize;
        let before_out = decompressor.total_out() as usize;
        let result = decompressor.decompress(
            &data[input_offset..],
            &mut buf,
            flate2::FlushDecompress::None,
        );

        let consumed = decompressor.total_in() as usize - before_in;
        let produced = decompressor.total_out() as usize - before_out;
        input_offset += consumed;
        output.extend_from_slice(&buf[..produced]);

        match result {
            Ok(status) => match status {
                flate2::Status::StreamEnd => return (Ok(output), true, input_offset),
                flate2::Status::Ok | flate2::Status::BufError => {
                    if consumed == 0 && produced == 0 {
                        return (Ok(output), true, input_offset);
                    }
                }
            },
            Err(_) if !output.is_empty() => {
                // Partial output — checksum/trailing data error.
                return (Ok(output), false, input_offset);
            }
            Err(e) => {
                return (
                    Err(PdfError::DecompressionError(format!("flate: {e}"))),
                    false,
                    input_offset,
                );
            }
        }
    }
}

/// LZWDecode — native PDF-compatible LZW decoder.
///
/// Handles EarlyChange correctly and tolerates premature EOF (missing EOD code),
/// which is common in real-world PDFs.
fn decode_lzw(data: &[u8], parms: Option<&PdfDict>) -> Result<Vec<u8>, PdfError> {
    let early_change = parms.and_then(|p| p.get_int(b"EarlyChange")).unwrap_or(1) != 0;

    let output = lzw_decode(data, early_change)
        .ok_or_else(|| PdfError::DecompressionError("lzw: decode failed".into()))?;

    // Apply predictor if specified
    if let Some(parms) = parms {
        let predictor = parms.get_int(b"Predictor").unwrap_or(1);
        if predictor > 1 {
            return apply_predictor(&output, parms, predictor);
        }
    }

    Ok(output)
}

// --- Native PDF LZW decoder ---

const LZW_CLEAR_TABLE: usize = 256;
const LZW_EOD: usize = 257;
const LZW_MAX_ENTRIES: usize = 4096;
const LZW_INITIAL_SIZE: usize = 258;

/// Decode an LZW-compressed byte stream per the PDF spec.
fn lzw_decode(data: &[u8], early_change: bool) -> Option<Vec<u8>> {
    let mut table = LzwTable::new(early_change);
    let mut bit_size = table.code_length();
    let mut reader = LzwBitReader::new(data);
    let mut decoded = Vec::new();
    let mut prev: Option<usize> = None;

    loop {
        let next = match reader.read(bit_size) {
            Some(code) => code as usize,
            None => {
                // Premature EOF — missing EOD code. Return what we have.
                return Some(decoded);
            }
        };

        match next {
            LZW_CLEAR_TABLE => {
                table.clear();
                prev = None;
                bit_size = table.code_length();
            }
            LZW_EOD => return Some(decoded),
            new => {
                if new > table.size() {
                    // Invalid code — return partial data if we have any
                    if decoded.is_empty() {
                        return None;
                    }
                    return Some(decoded);
                }

                if new < table.size() {
                    let entry = table.get(new)?;
                    let first_byte = entry[0];
                    decoded.extend_from_slice(entry);

                    if let Some(prev_code) = prev {
                        table.register(prev_code, first_byte);
                    }
                } else if new == table.size() && prev.is_some() {
                    // KwKwK case: code references the entry about to be created
                    let prev_code = prev.unwrap();
                    let prev_entry = table.get(prev_code)?;
                    let first_byte = prev_entry[0];

                    let new_entry = table.register(prev_code, first_byte)?;
                    decoded.extend_from_slice(new_entry);
                } else {
                    if decoded.is_empty() {
                        return None;
                    }
                    return Some(decoded);
                }

                bit_size = table.code_length();
                prev = Some(new);
            }
        }
    }
}

/// LZW string table.
struct LzwTable {
    early_change: bool,
    entries: Vec<Option<Vec<u8>>>,
}

impl LzwTable {
    fn new(early_change: bool) -> Self {
        let mut entries: Vec<_> = (0..=255u8).map(|b| Some(vec![b])).collect();
        entries.push(None); // 256 = CLEAR_TABLE
        entries.push(None); // 257 = EOD
        Self {
            early_change,
            entries,
        }
    }

    fn push(&mut self, entry: Vec<u8>) -> Option<&[u8]> {
        if self.entries.len() >= LZW_MAX_ENTRIES {
            None
        } else {
            self.entries.push(Some(entry));
            self.entries.last()?.as_deref()
        }
    }

    fn register(&mut self, prev: usize, new_byte: u8) -> Option<&[u8]> {
        let prev_entry = self.get(prev)?;
        let mut new_entry = Vec::with_capacity(prev_entry.len() + 1);
        new_entry.extend(prev_entry);
        new_entry.push(new_byte);
        self.push(new_entry)
    }

    fn get(&self, index: usize) -> Option<&[u8]> {
        self.entries.get(index)?.as_deref()
    }

    fn clear(&mut self) {
        self.entries.truncate(LZW_INITIAL_SIZE);
    }

    fn size(&self) -> usize {
        self.entries.len()
    }

    fn code_length(&self) -> u8 {
        let adjusted = self.entries.len() + if self.early_change { 1 } else { 0 };
        if adjusted >= 2048 {
            12
        } else if adjusted >= 1024 {
            11
        } else if adjusted >= 512 {
            10
        } else {
            9
        }
    }
}

/// MSB-first bit reader for LZW.
struct LzwBitReader<'a> {
    data: &'a [u8],
    bit_pos: usize,
}

impl<'a> LzwBitReader<'a> {
    fn new(data: &'a [u8]) -> Self {
        Self { data, bit_pos: 0 }
    }

    fn read(&mut self, bit_size: u8) -> Option<u32> {
        let byte_pos = self.bit_pos / 8;
        if byte_pos >= self.data.len() {
            return None;
        }
        let bit_offset = self.bit_pos % 8;
        let end_byte = (self.bit_pos + bit_size as usize - 1) / 8;

        // Read up to 8 bytes into a u64 for extraction
        let mut buf = [0u8; 8];
        for (i, b) in buf.iter_mut().enumerate().take(end_byte - byte_pos + 1) {
            *b = *self.data.get(byte_pos + i)?;
        }
        let bits = u64::from_be_bytes(buf);
        let shift = 64 - bit_offset - bit_size as usize;
        let mask = (1u64 << bit_size) - 1;
        let value = ((bits >> shift) & mask) as u32;

        self.bit_pos += bit_size as usize;
        Some(value)
    }
}

/// ASCIIHexDecode.
fn decode_ascii_hex(data: &[u8]) -> Result<Vec<u8>, PdfError> {
    let mut result = Vec::with_capacity(data.len() / 2);
    let mut high: Option<u8> = None;

    for &b in data {
        if b == b'>' {
            break;
        }
        if b.is_ascii_whitespace() {
            continue;
        }
        let nibble = hex_digit(b)
            .ok_or_else(|| PdfError::DecompressionError(format!("invalid hex digit: 0x{b:02x}")))?;
        match high {
            None => high = Some(nibble),
            Some(h) => {
                result.push(h << 4 | nibble);
                high = None;
            }
        }
    }
    if let Some(h) = high {
        result.push(h << 4);
    }

    Ok(result)
}

/// ASCII85Decode.
fn decode_ascii85(data: &[u8]) -> Result<Vec<u8>, PdfError> {
    let mut result = Vec::with_capacity(data.len() * 4 / 5);
    let mut tuple: u64 = 0;
    let mut count = 0u8;

    for &b in data {
        if b == b'~' {
            break; // ~> end marker
        }
        if b.is_ascii_whitespace() {
            continue;
        }
        if b == b'z' && count == 0 {
            result.extend_from_slice(&[0, 0, 0, 0]);
            continue;
        }
        if !(b'!'..=b'u').contains(&b) {
            continue; // skip invalid
        }
        tuple = tuple * 85 + (b - b'!') as u64;
        count += 1;
        if count == 5 {
            result.push((tuple >> 24) as u8);
            result.push((tuple >> 16) as u8);
            result.push((tuple >> 8) as u8);
            result.push(tuple as u8);
            tuple = 0;
            count = 0;
        }
    }

    // Handle remainder
    if count > 0 {
        for _ in count..5 {
            tuple = tuple * 85 + 84; // pad with 'u'
        }
        for i in 0..(count - 1) {
            result.push((tuple >> (24 - i * 8)) as u8);
        }
    }

    Ok(result)
}

/// RunLengthDecode (PackBits).
fn decode_run_length(data: &[u8]) -> Result<Vec<u8>, PdfError> {
    let mut result = Vec::new();
    let mut i = 0;

    while i < data.len() {
        let length_byte = data[i];
        i += 1;
        if length_byte < 128 {
            // Copy next (length_byte + 1) bytes literally
            let count = length_byte as usize + 1;
            if i + count > data.len() {
                break;
            }
            result.extend_from_slice(&data[i..i + count]);
            i += count;
        } else if length_byte > 128 {
            // Repeat next byte (257 - length_byte) times
            if i >= data.len() {
                break;
            }
            let count = 257 - length_byte as usize;
            let val = data[i];
            i += 1;
            for _ in 0..count {
                result.push(val);
            }
        } else {
            // 128 = EOD
            break;
        }
    }

    Ok(result)
}

/// DCTDecode (JPEG).
/// For PDF image streams, DCTDecode returns raw pixel data.
/// However, when used as a filter in a filter chain, the JPEG data
/// is typically the final representation — return the raw JPEG bytes
/// since the image decoder will handle them. For standalone streams,
/// decode the JPEG to raw pixels.
fn decode_dct(data: &[u8]) -> Result<Vec<u8>, PdfError> {
    use jpeg_decoder::Decoder;

    // wasm32: prefer zune-jpeg over jpeg-decoder as the primary decoder.
    // jpeg-decoder's wasm SIMD IDCT path traps (raw `unreachable`, bypasses
    // std::panic::set_hook) on JPEGs whose bitstream ends early — the native
    // scalar reader returns a clean `Err("failed to fill whole buffer")`
    // which the fallback chain below catches, but on wasm32 the SIMD path
    // writes past the end of an intermediate buffer before the stream check
    // fires, tripping wasm's bounds check. Starting with zune avoids that
    // code path entirely for the most common JPEGs. jpeg-decoder is still
    // tried below as a secondary fallback (e.g. for Adobe YCCK streams
    // where zune's color transform would give wrong results).
    #[cfg(target_arch = "wasm32")]
    if let Some(pixels) = decode_dct_via_zune(data) {
        return Ok(pixels);
    }

    let mut decoder = Decoder::new(data);

    // Work around jpeg_decoder bug: it checks component IDs (1,2,3) → YCbCr
    // before checking Adobe APP14 ColorTransform. When ColorTransform=0 (raw
    // RGB) is present but component IDs are (1,2,3), the decoder incorrectly
    // applies YCbCr→RGB conversion to already-RGB data. Detect this case and
    // override with ColorTransform::RGB.
    if has_adobe_rgb_marker(data) || is_raw_rgb_jpeg(data) {
        decoder.set_color_transform(jpeg_decoder::ColorTransform::RGB);
    } else if needs_ycck_override(data) {
        decoder.set_color_transform(jpeg_decoder::ColorTransform::YCCK);
    }

    let pixels = match decoder.decode() {
        Ok(p) => p,
        Err(e) => {
            // jpeg_decoder doesn't support 2-component JPEGs (DeviceN spot
            // color images). Fall back to zune-jpeg which handles arbitrary
            // component counts.
            if let Some(pixels) = decode_dct_zune(data) {
                return Ok(pixels);
            }
            // Some JPEGs use DNL (Define Number of Lines) markers to specify
            // the height after encoding. Patch the SOF header with the DNL
            // height and retry.
            if let Some(patched) = patch_jpeg_dnl_height(data) {
                return decode_dct(&patched);
            }
            // Truncated JPEGs: try tolerant decode that returns partial data.
            if let Some(pixels) = decode_dct_tolerant(data) {
                return Ok(pixels);
            }
            // Last resort: append EOI marker to truncated JPEG and retry.
            // jpeg-decoder may succeed when the stream is terminated properly.
            {
                let mut padded = data.to_vec();
                // Strip any partial marker at end, then add EOI
                if padded.last() == Some(&0xFF) {
                    padded.pop();
                }
                padded.extend_from_slice(&[0xFF, 0xD9]);
                let mut retry_dec = Decoder::new(&padded[..]);
                if has_adobe_rgb_marker(&padded) || is_raw_rgb_jpeg(&padded) {
                    retry_dec.set_color_transform(jpeg_decoder::ColorTransform::RGB);
                } else if needs_ycck_override(&padded) {
                    retry_dec.set_color_transform(jpeg_decoder::ColorTransform::YCCK);
                }
                if let Ok(pixels) = retry_dec.decode() {
                    // Apply same CMYK inversion as the normal path
                    if let Some(info) = retry_dec.info()
                        && info.pixel_format == jpeg_decoder::PixelFormat::CMYK32
                    {
                        let mut result = pixels;
                        for b in result.iter_mut() {
                            *b = 255 - *b;
                        }
                        return Ok(result);
                    }
                    return Ok(pixels);
                }
            }
            return Err(PdfError::DecompressionError(format!("DCTDecode: {e}")));
        }
    };

    // For 4-component (CMYK) JPEG, the jpeg_decoder applies a CMYK color
    // transform that inverts all channels (255-x). However, for PDF streams the
    // raw JPEG data is already in the correct byte order for the PDF /Decode
    // array to process. Undo the decoder's inversion so the PDF renderer gets
    // the original sample values.
    if let Some(info) = decoder.info()
        && info.pixel_format == jpeg_decoder::PixelFormat::CMYK32
    {
        let mut result = pixels;
        for b in result.iter_mut() {
            *b = 255 - *b;
        }
        return Ok(result);
    }

    Ok(pixels)
}

/// Run a closure that may panic, suppressing the panic message and returning
/// `None` on panic.  Used for third-party JPEG decoders that can panic on
/// malformed input.
fn catch_silent<F, T>(f: F) -> Option<T>
where
    F: FnOnce() -> Option<T> + std::panic::UnwindSafe,
{
    let prev = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    let result = std::panic::catch_unwind(f).ok().flatten();
    std::panic::set_hook(prev);
    result
}

/// Primary JPEG decoder on wasm32. Uses zune-jpeg directly (no `catch_silent`
/// wrapper — `catch_unwind` is a no-op under `panic=abort` and the hook swap
/// would clobber the WASM panic hook). Picks the output colorspace from the
/// SOF component count so 1/3/4-component JPEGs all decode to their natural
/// format. Returns `None` if zune-jpeg can't decode — caller falls back to
/// jpeg-decoder.
#[cfg(target_arch = "wasm32")]
fn decode_dct_via_zune(data: &[u8]) -> Option<Vec<u8>> {
    use zune_jpeg::JpegDecoder;
    let n_comps = jpeg_dimensions_and_components(data)
        .map(|(_, _, n)| n)
        .unwrap_or(3);
    let out_cs = match n_comps {
        1 => zune_core::colorspace::ColorSpace::Luma,
        4 => zune_core::colorspace::ColorSpace::CMYK,
        _ => zune_core::colorspace::ColorSpace::RGB,
    };
    let options = zune_core::options::DecoderOptions::default().jpeg_set_out_colorspace(out_cs);
    let mut decoder = JpegDecoder::new_with_options(std::io::Cursor::new(data), options);
    decoder.decode().ok()
}

/// Fallback JPEG decoder using zune-jpeg for component counts that
/// jpeg_decoder doesn't support (e.g., 2-component DeviceN images).
fn decode_dct_zune(data: &[u8]) -> Option<Vec<u8>> {
    use zune_jpeg::JpegDecoder;
    // Request raw 2-component output (LumaA) to avoid unwanted color
    // conversion. PDF DeviceN images need the original channel values
    // for the tinting function.
    let data = data.to_vec();
    catch_silent(move || {
        let options = zune_core::options::DecoderOptions::default()
            .jpeg_set_out_colorspace(zune_core::colorspace::ColorSpace::LumaA);
        let mut decoder = JpegDecoder::new_with_options(std::io::Cursor::new(&data), options);
        decoder.decode().ok()
    })
}

/// Tolerant JPEG decoder for truncated streams.
/// Returns partial pixel data for whatever MCU rows decoded successfully.
/// Applies the same CMYK channel inversion as the primary decoder path.
fn decode_dct_tolerant(data: &[u8]) -> Option<Vec<u8>> {
    // Detect component count from SOF to set the right output colorspace.
    // Without this, zune-jpeg converts CMYK to RGB, producing wrong data.
    let n_comps = jpeg_dimensions_and_components(data)
        .map(|(_, _, n)| n)
        .unwrap_or(3);
    let data = data.to_vec();
    catch_silent(move || {
        use zune_jpeg::JpegDecoder;
        let out_cs = match n_comps {
            1 => zune_core::colorspace::ColorSpace::Luma,
            4 => zune_core::colorspace::ColorSpace::CMYK,
            _ => zune_core::colorspace::ColorSpace::RGB,
        };
        let options = zune_core::options::DecoderOptions::default()
            .set_strict_mode(false)
            .jpeg_set_out_colorspace(out_cs);
        let mut decoder = JpegDecoder::new_with_options(std::io::Cursor::new(&data), options);
        decoder.decode().ok()
    })
}

/// Patch a JPEG that uses DNL (Define Number of Lines, marker 0xFFDC) to specify
/// its height. Finds the DNL marker, extracts the height, writes it into the SOF
/// header, and strips the DNL marker from the scan data so standard decoders can
/// parse it.
fn patch_jpeg_dnl_height(data: &[u8]) -> Option<Vec<u8>> {
    // Find DNL marker (0xFF 0xDC) and extract height
    let dnl_height = {
        let mut pos = 0;
        let mut found = None;
        while pos + 4 < data.len() {
            if data[pos] == 0xFF && data[pos + 1] == 0xDC {
                // DNL: FF DC 00 04 <height_hi> <height_lo>
                if pos + 5 < data.len() {
                    let h = ((data[pos + 4] as u16) << 8) | data[pos + 5] as u16;
                    found = Some((pos, h));
                }
                break;
            }
            pos += 1;
        }
        found
    };
    let (dnl_pos, height) = dnl_height?;
    if height == 0 {
        return None;
    }

    // Find SOF marker (0xFFC0..0xFFC3) and patch height field
    let mut patched = data.to_vec();
    let mut pos = 2; // skip SOI
    while pos + 8 < patched.len() {
        if patched[pos] != 0xFF {
            pos += 1;
            continue;
        }
        let marker = patched[pos + 1];
        if (0xC0..=0xC3).contains(&marker) {
            // SOF: FF Cn LL LL PP HH HH WW WW ...
            // Height is at offset +5 (2 bytes, big-endian)
            patched[pos + 5] = (height >> 8) as u8;
            patched[pos + 6] = (height & 0xFF) as u8;
            break;
        }
        if marker == 0xDA {
            break; // SOS — stop before scan data
        }
        // Skip marker segment
        if pos + 3 < patched.len() {
            let seg_len = ((patched[pos + 2] as usize) << 8) | patched[pos + 3] as usize;
            pos += 2 + seg_len;
        } else {
            break;
        }
    }

    // Remove the DNL marker (6 bytes: FF DC 00 04 HH HH)
    if dnl_pos + 6 <= patched.len() {
        patched.drain(dnl_pos..dnl_pos + 6);
    }

    Some(patched)
}

/// Extract image dimensions from a JPEG's SOF marker.
/// Returns `(width, height)` if found.
///
/// Patch the SOF height field in raw JPEG data.
/// Used when the SOF header has a streaming-encoder placeholder height (e.g.
/// 60000) that exceeds the PDF dict's authoritative /Height value.
pub fn patch_jpeg_sof_height(data: &mut [u8], new_height: u16) {
    if data.len() < 2 || data[0] != 0xFF || data[1] != 0xD8 {
        return;
    }
    let mut pos = 2;
    while pos + 4 < data.len() {
        if data[pos] != 0xFF {
            pos += 1;
            continue;
        }
        let marker = data[pos + 1];
        if (0xC0..=0xCF).contains(&marker) && marker != 0xC4 && marker != 0xC8 && marker != 0xCC {
            if pos + 6 < data.len() {
                data[pos + 5] = (new_height >> 8) as u8;
                data[pos + 6] = (new_height & 0xFF) as u8;
            }
            return;
        }
        if marker == 0xDA {
            return; // SOS — too late
        }
        let seg_len = if pos + 3 < data.len() {
            ((data[pos + 2] as usize) << 8) | data[pos + 3] as usize
        } else {
            return;
        };
        pos += 2 + seg_len;
    }
}

/// Extract width, height, and component count from a JPEG SOF header.
pub(crate) fn jpeg_dimensions_and_components(data: &[u8]) -> Option<(u32, u32, u8)> {
    if data.len() < 2 || data[0] != 0xFF || data[1] != 0xD8 {
        return None;
    }
    let mut pos = 2;
    while pos + 4 < data.len() {
        if data[pos] != 0xFF {
            pos += 1;
            continue;
        }
        let marker = data[pos + 1];
        if (0xC0..=0xCF).contains(&marker) && marker != 0xC4 && marker != 0xC8 && marker != 0xCC {
            if pos + 9 < data.len() {
                let h = ((data[pos + 5] as u32) << 8) | data[pos + 6] as u32;
                let w = ((data[pos + 7] as u32) << 8) | data[pos + 8] as u32;
                let n = data[pos + 9];
                return Some((w, h, n));
            }
        }
        if marker == 0xDA {
            break;
        }
        let seg_len = ((data[pos + 2] as usize) << 8) | data[pos + 3] as usize;
        pos += 2 + seg_len;
    }
    None
}

/// When the JPEG uses DNL (Define Number of Lines, marker 0xFFDC) — indicated by
/// a dummy SOF height of 0 or 0xFFFF — scans the bitstream for the DNL marker
/// and returns its height instead.
pub fn jpeg_dimensions(data: &[u8]) -> Option<(u32, u32)> {
    if data.len() < 2 || data[0] != 0xFF || data[1] != 0xD8 {
        return None;
    }
    let mut pos = 2;
    while pos + 4 < data.len() {
        if data[pos] != 0xFF {
            pos += 1;
            continue;
        }
        let marker = data[pos + 1];
        // SOF markers: 0xC0-0xCF except 0xC4 (DHT), 0xC8 (JPG), 0xCC (DAC)
        if (0xC0..=0xCF).contains(&marker) && marker != 0xC4 && marker != 0xC8 && marker != 0xCC {
            if pos + 9 < data.len() {
                let mut h = ((data[pos + 5] as u32) << 8) | data[pos + 6] as u32;
                let w = ((data[pos + 7] as u32) << 8) | data[pos + 8] as u32;
                // SOF height 0 or 0xFFFF means "defined by DNL marker later"
                if h == 0 || h == 0xFFFF {
                    if let Some(dnl_h) = find_dnl_height(data) {
                        h = dnl_h as u32;
                    }
                }
                return Some((w, h));
            }
        }
        if marker == 0xDA {
            break; // SOS — no more markers
        }
        let seg_len = ((data[pos + 2] as usize) << 8) | data[pos + 3] as usize;
        pos += 2 + seg_len;
    }
    None
}

/// Scan JPEG data for a DNL (Define Number of Lines) marker and return its height.
fn find_dnl_height(data: &[u8]) -> Option<u16> {
    let mut pos = 0;
    while pos + 5 < data.len() {
        if data[pos] == 0xFF && data[pos + 1] == 0xDC && pos + 5 < data.len() {
            return Some(((data[pos + 4] as u16) << 8) | data[pos + 5] as u16);
        }
        pos += 1;
    }
    None
}

/// Check if a JPEG has Adobe APP14 ColorTransform=0 AND uniform sampling factors,
/// confirming the data is truly raw RGB (not YCbCr mislabeled with ColorTransform=0).
/// YCbCr JPEGs use chroma subsampling (e.g., Y=2×2, Cb/Cr=1×1) while RGB JPEGs
/// use uniform sampling (all components 1×1).
fn has_adobe_rgb_marker(data: &[u8]) -> bool {
    let mut has_ct0 = false;
    let mut uniform_sampling = false;
    let mut i = 2; // skip SOI
    while i + 4 < data.len() {
        if data[i] != 0xFF {
            break;
        }
        let marker = data[i + 1];
        if marker == 0xDA {
            break; // SOS — done with headers
        }
        let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
        if i + 2 + len > data.len() {
            break;
        }
        // APP14 (Adobe) marker: check ColorTransform
        // Segment layout: length(2) + "Adobe"(5) + version(2) + flags0(2) + flags1(2) + CT(1) = 14
        if marker == 0xEE && len >= 14 {
            let color_transform = data[i + 2 + 13];
            has_ct0 = color_transform == 0;
        }
        // SOF0/SOF2: check sampling factors
        if (marker == 0xC0 || marker == 0xC2) && i + 9 < data.len() {
            let ncomp = data[i + 9] as usize;
            if ncomp == 3 && i + 10 + ncomp * 3 <= data.len() {
                let s0 = data[i + 11]; // component 0 sampling
                let s1 = data[i + 14]; // component 1 sampling
                let s2 = data[i + 17]; // component 2 sampling
                uniform_sampling = s0 == s1 && s1 == s2;
            }
        }
        i += 2 + len;
    }
    has_ct0 && uniform_sampling
}

/// Detect raw RGB JPEGs that have no APP14/JFIF markers and non-standard
/// component IDs (e.g. 0,1,2 instead of the YCbCr standard 1,2,3).
/// These JPEGs store raw RGB data — applying YCbCr→RGB conversion produces
/// completely wrong colors (e.g. blue → magenta).
fn is_raw_rgb_jpeg(data: &[u8]) -> bool {
    let mut has_jfif = false;
    let mut has_adobe = false;
    let mut non_standard_ids = false;
    let mut uniform_sampling = false;
    let mut n_components = 0u8;
    let mut i = 2; // skip SOI
    while i + 4 < data.len() {
        if data[i] != 0xFF {
            break;
        }
        let marker = data[i + 1];
        if marker == 0xDA {
            break;
        }
        let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
        if i + 2 + len > data.len() {
            break;
        }
        if marker == 0xE0 && len >= 7 && &data[i + 4..i + 9] == b"JFIF\x00" {
            has_jfif = true;
        }
        if marker == 0xEE && len >= 7 && &data[i + 4..i + 9] == b"Adobe" {
            has_adobe = true;
        }
        if (marker == 0xC0 || marker == 0xC2) && i + 9 < data.len() {
            n_components = data[i + 9];
            if n_components == 3 && i + 10 + 9 <= data.len() {
                let id0 = data[i + 10];
                let id1 = data[i + 13];
                let id2 = data[i + 16];
                // Standard YCbCr uses IDs (1,2,3). Anything else suggests raw RGB.
                non_standard_ids = !(id0 == 1 && id1 == 2 && id2 == 3);
                let s0 = data[i + 11];
                let s1 = data[i + 14];
                let s2 = data[i + 17];
                uniform_sampling = s0 == s1 && s1 == s2;
            }
        }
        i += 2 + len;
    }
    // Raw RGB: 3 components, non-standard IDs, uniform sampling, no JFIF/Adobe markers
    n_components == 3 && non_standard_ids && uniform_sampling && !has_jfif && !has_adobe
}

/// Work around jpeg_decoder bug: it checks `"Adobe\0"` (6 bytes) in APP14
/// but the spec defines only 5-byte `"Adobe"`. The 6th byte is the high byte
/// of the version field. When version >= 256 (high byte != 0), jpeg_decoder
/// misses the APP14 marker entirely and misidentifies YCCK as plain CMYK.
/// Returns true when the last APP14 has ColorTransform=2 (YCCK) and jpeg_decoder
/// would fail to detect it.
fn needs_ycck_override(data: &[u8]) -> bool {
    let mut last_ct = None;
    let mut decoder_would_miss = false;
    let mut n_components = 0u8;
    let mut i = 2; // skip SOI
    while i + 4 < data.len() {
        if data[i] != 0xFF {
            break;
        }
        let marker = data[i + 1];
        if marker == 0xDA {
            break; // SOS
        }
        let len = u16::from_be_bytes([data[i + 2], data[i + 3]]) as usize;
        if i + 2 + len > data.len() {
            break;
        }
        // APP14 (Adobe): "Adobe"(5) + version(2) + flags0(2) + flags1(2) + CT(1)
        if marker == 0xEE && len >= 14 && &data[i + 4..i + 9] == b"Adobe" {
            let ct = data[i + 2 + 13];
            last_ct = Some(ct);
            // jpeg_decoder checks data[0..6] == "Adobe\0", so byte index 5
            // (= data[i+9], the version high byte) must be 0 for it to detect.
            decoder_would_miss = data[i + 9] != 0;
        }
        // SOF0/SOF2: get number of components
        if (marker == 0xC0 || marker == 0xC2) && i + 9 < data.len() {
            n_components = data[i + 9];
        }
        i += 2 + len;
    }
    // Only override when: last APP14 says YCCK, jpeg_decoder would miss it,
    // and the JPEG has 4 components (CMYK/YCCK domain).
    last_ct == Some(2) && decoder_would_miss && n_components == 4
}

/// CCITTFaxDecode (Group 3 / Group 4 fax compression).
fn decode_ccittfax(data: &[u8], parms: Option<&PdfDict>) -> Result<Vec<u8>, PdfError> {
    use crate::objects::PdfObj;

    let k = parms.and_then(|p| p.get_int(b"K")).unwrap_or(0) as i32;
    let columns = parms.and_then(|p| p.get_int(b"Columns")).unwrap_or(1728) as u16;
    let rows_limit = parms.and_then(|p| p.get_int(b"Rows")).unwrap_or(0) as u32;
    let end_of_block = parms
        .and_then(|p| match p.get(b"EndOfBlock") {
            Some(PdfObj::Bool(b)) => Some(*b),
            _ => None,
        })
        .unwrap_or(true);
    let black_is1 = parms
        .and_then(|p| match p.get(b"BlackIs1") {
            Some(PdfObj::Bool(b)) => Some(*b),
            _ => None,
        })
        .unwrap_or(false);

    let encoded_byte_align = parms
        .and_then(|p| match p.get(b"EncodedByteAlign") {
            Some(PdfObj::Bool(b)) => Some(*b),
            _ => None,
        })
        .unwrap_or(false);

    let encoding = if k < 0 {
        hayro_ccitt::EncodingMode::Group4
    } else if k == 0 {
        hayro_ccitt::EncodingMode::Group3_1D
    } else {
        hayro_ccitt::EncodingMode::Group3_2D { k: k as u32 }
    };

    let settings = hayro_ccitt::DecodeSettings {
        columns: columns as u32,
        rows: if rows_limit > 0 { rows_limit } else { u32::MAX },
        end_of_block,
        end_of_line: false,
        rows_are_byte_aligned: encoded_byte_align,
        encoding,
        invert_black: false,
    };

    decode_ccitt_hayro(data, &settings, black_is1)
}

/// A byte-oriented CCITT pixel decoder used by hayro-ccitt.
/// Packs decoded pixels into bytes (MSB first), with `black_is1` polarity control.
struct CcittByteDecoder {
    output: Vec<u8>,
    current_byte: u8,
    bit_pos: u8,
    black_is1: bool,
}

impl CcittByteDecoder {
    fn new(black_is1: bool) -> Self {
        Self {
            output: Vec::new(),
            current_byte: 0,
            bit_pos: 0,
            black_is1,
        }
    }

    fn flush_byte(&mut self) {
        if self.bit_pos > 0 {
            // Shift remaining bits to MSB position and pad
            let remaining = 8 - self.bit_pos;
            self.current_byte <<= remaining;
            if !self.black_is1 {
                // Pad unfilled bits as white (1)
                self.current_byte |= (1u8 << remaining) - 1;
            }
            self.output.push(self.current_byte);
            self.current_byte = 0;
            self.bit_pos = 0;
        }
    }
}

impl hayro_ccitt::Decoder for CcittByteDecoder {
    fn push_pixel(&mut self, white: bool) {
        // black_is1=true: black=1, white=0
        // black_is1=false: black=0, white=1
        let bit = if self.black_is1 { !white } else { white };
        self.current_byte = (self.current_byte << 1) | (bit as u8);
        self.bit_pos += 1;
        if self.bit_pos == 8 {
            self.output.push(self.current_byte);
            self.current_byte = 0;
            self.bit_pos = 0;
        }
    }

    fn push_pixel_chunk(&mut self, white: bool, chunk_count: u32) {
        // If there are partial bits pending, we can't directly push bytes —
        // the bit boundary wouldn't align. Fall back to pixel-by-pixel.
        if self.bit_pos != 0 {
            for _ in 0..chunk_count * 8 {
                self.push_pixel(white);
            }
            return;
        }
        let byte = if (self.black_is1 && !white) || (!self.black_is1 && white) {
            0xFF
        } else {
            0x00
        };
        for _ in 0..chunk_count {
            self.output.push(byte);
        }
    }

    fn next_line(&mut self) {
        self.flush_byte();
    }
}

/// Decode CCITT data using hayro-ccitt (supports Group 3 and Group 4), with
/// a fall-through to the `fax` crate when hayro rejects the stream with a
/// hard error (Overflow, InvalidCode, LineLengthMismatch). The `fax` crate is
/// more lenient with malformed Group 4 streams produced by old Acrobat
/// Distiller versions, where hayro's strict position-arithmetic checks can
/// bail out mid-stream even though the image is still decodable.
fn decode_ccitt_hayro(
    data: &[u8],
    settings: &hayro_ccitt::DecodeSettings,
    black_is1: bool,
) -> Result<Vec<u8>, PdfError> {
    let mut decoder = CcittByteDecoder::new(black_is1);
    let hayro_err = hayro_ccitt::decode(data, &mut decoder, settings).err();

    // If hayro failed with anything other than a soft EOF, try `fax` as a
    // fallback. Keep whichever decoder produced more byte output.
    if let Some(e) = hayro_err
        && e != hayro_ccitt::DecodeError::UnexpectedEof
    {
        let fallback = decode_ccitt_fax(data, settings, black_is1);
        use std::sync::atomic::{AtomicBool, Ordering};
        static WARNED: AtomicBool = AtomicBool::new(false);
        if fallback.len() > decoder.output.len() {
            if !WARNED.swap(true, Ordering::Relaxed) {
                eprintln!(
                    "[CCITT] hayro-ccitt error: {} — fell back to `fax` crate",
                    e
                );
            }
            return Ok(fallback);
        }
        if !WARNED.swap(true, Ordering::Relaxed) {
            eprintln!("[CCITT] decode warning: {} (using partial data)", e);
        }
    }
    Ok(decoder.output)
}

/// Decode CCITT data using the `fax` crate as a fallback. Returns a byte-packed
/// buffer with the same polarity/layout as the hayro path.
fn decode_ccitt_fax(
    data: &[u8],
    settings: &hayro_ccitt::DecodeSettings,
    black_is1: bool,
) -> Vec<u8> {
    let width = settings.columns as u16;
    let row_bytes = settings.columns.div_ceil(8) as usize;
    let mut out: Vec<u8> = Vec::new();
    // Byte value for a full chunk of "white" and "black" pixels after polarity.
    // black_is1=false (PDF default): 0=black, 1=white → white row = 0xFF, black = 0x00
    // black_is1=true: 0=white, 1=black → white row = 0x00, black = 0xFF
    let white_byte: u8 = if black_is1 { 0x00 } else { 0xFF };
    let black_byte: u8 = !white_byte;

    let rows_limit = if settings.rows == u32::MAX || settings.rows == 0 {
        None
    } else {
        Some(settings.rows.min(u16::MAX as u32) as u16)
    };

    let mut emit_row = |transitions: &[u16]| {
        // Rebuild one packed row from the transition list.
        let mut row = vec![white_byte; row_bytes];
        // Row starts white; each transition flips color starting at that index.
        let mut color_white = true;
        let mut cursor: u16 = 0;
        // Add the sentinel `width` transition so we close the final run.
        let iter = transitions.iter().copied().chain(std::iter::once(width));
        for next in iter {
            let end = next.min(width);
            if !color_white && end > cursor {
                fill_bits(&mut row, cursor as usize, end as usize, black_byte != 0);
            }
            color_white = !color_white;
            cursor = end;
            if cursor >= width {
                break;
            }
        }
        out.extend_from_slice(&row);
    };

    match settings.encoding {
        hayro_ccitt::EncodingMode::Group4 => {
            let _ = fax::decoder::decode_g4(data.iter().copied(), width, rows_limit, &mut emit_row);
        }
        hayro_ccitt::EncodingMode::Group3_1D | hayro_ccitt::EncodingMode::Group3_2D { .. } => {
            let _ = fax::decoder::decode_g3(data.iter().copied(), &mut emit_row);
        }
    }

    // Pad truncated output with white scanlines so downstream image handling
    // sees the full-height buffer. Without this, a Group 4 stream that the
    // decoder can't finish (malformed PDF) would produce a buffer short by
    // thousands of bytes; the image code fills the missing rows with zeros,
    // which lands as a solid black rectangle covering part of the page.
    if let Some(target_rows) = rows_limit {
        let expected = row_bytes * target_rows as usize;
        if out.len() < expected {
            out.resize(expected, white_byte);
        }
    }

    out
}

/// Flip bits in a byte-packed (MSB-first) row between `[start, end)` to black.
/// `start`/`end` are pixel indices; the buffer is pre-filled with the "white"
/// polarity, so this routine only needs to set the black-colored runs.
fn fill_bits(row: &mut [u8], start: usize, end: usize, black_is_one: bool) {
    if end <= start {
        return;
    }
    for x in start..end {
        let byte = x / 8;
        let bit = 0x80u8 >> (x % 8);
        if black_is_one {
            row[byte] |= bit;
        } else {
            row[byte] &= !bit;
        }
    }
}

/// JBIG2Decode.
fn decode_jbig2(data: &[u8], globals: Option<&[u8]>) -> Result<Vec<u8>, PdfError> {
    // Native builds run the decode on a sidecar thread with a 2-second
    // watchdog, guarding against malformed streams that hang the decoder
    // (e.g. issue15942.pdf). wasm32-unknown-unknown has no thread support,
    // so the watchdog is skipped there and we call the decoder directly —
    // a hanging stream will hang the page, but normal streams (like those
    // in pdf_samples/1321.pdf) will now decode instead of panicking at
    // `std::thread::spawn`.
    #[cfg(not(target_arch = "wasm32"))]
    let image = {
        let data_owned = data.to_vec();
        let globals_owned = globals.map(|g| g.to_vec());
        let (tx, rx) = std::sync::mpsc::channel();
        std::thread::spawn(move || {
            let result = hayro_jbig2::decode_embedded(&data_owned, globals_owned.as_deref());
            let _ = tx.send(result);
        });
        // Scale timeout with data size: 5s base + 5s per MB of compressed data.
        // Large scanned-document pages (e.g. 19k×25k bilevel at 2MB) need more
        // than the original 2s, while the watchdog still catches malformed
        // streams that hang the decoder indefinitely.
        let timeout_secs = 5 + (data.len() as u64 / (1024 * 1024)) * 5;
        rx.recv_timeout(std::time::Duration::from_secs(timeout_secs))
            .map_err(|_| PdfError::DecompressionError("JBIG2: decode timed out".into()))?
            .map_err(|e| PdfError::DecompressionError(format!("JBIG2: {e}")))?
    };

    #[cfg(target_arch = "wasm32")]
    let image = hayro_jbig2::decode_embedded(data, globals)
        .map_err(|e| PdfError::DecompressionError(format!("JBIG2: {e}")))?;

    // Convert Vec<bool> to packed bytes (8 pixels/byte, MSB first)
    // JBIG2: true = black, false = white
    // PDF DeviceGray: 0 = black, 1 = white
    // So: start all-white (0xFF), clear bits for black pixels
    let row_bytes = (image.width as usize).div_ceil(8);
    let mut packed = vec![0xFFu8; row_bytes * image.height as usize];
    for y in 0..image.height as usize {
        for x in 0..image.width as usize {
            if image.data[y * image.width as usize + x] {
                packed[y * row_bytes + x / 8] &= !(0x80 >> (x % 8));
            }
        }
    }
    Ok(packed)
}

/// JPXDecode (JPEG 2000).
///
/// Uses hayro-jpeg2000 to decode JP2 or raw J2K codestreams into interleaved pixel data.
#[cfg(feature = "jpx")]
fn decode_jpx(data: &[u8]) -> Result<Vec<u8>, PdfError> {
    if data.is_empty() {
        return Ok(Vec::new());
    }

    let image = hayro_jpeg2000::Image::new(data, &hayro_jpeg2000::DecodeSettings::default())
        .map_err(|e| PdfError::DecompressionError(format!("JPXDecode: {e}")))?;

    image
        .decode()
        .map_err(|e| PdfError::DecompressionError(format!("JPXDecode: {e}")))
}

/// JPXDecode without resolving the JP2-internal palette.
///
/// Some Adobe-generated JP2 files declare 4-bit palette column precision but
/// store 8-bit values.  hayro-jpeg2000's palette resolution rescales based on
/// the declared precision, corrupting the colors.  When the PDF provides its
/// own Indexed color space, we skip the JP2 palette and let the PDF lookup
/// table handle it.
///
/// Returns `(decoded_data, original_bit_depth)`.  The original bit depth is
/// needed to un-normalize hayro's 8-bit output back to raw palette indices
/// (hayro rescales sub-8-bit data to 0-255).
#[cfg(feature = "jpx")]
pub fn decode_jpx_no_palette(data: &[u8]) -> Result<(Vec<u8>, u8), PdfError> {
    if data.is_empty() {
        return Ok((Vec::new(), 8));
    }

    let settings = hayro_jpeg2000::DecodeSettings {
        resolve_palette_indices: false,
        ..Default::default()
    };
    let image = hayro_jpeg2000::Image::new(data, &settings)
        .map_err(|e| PdfError::DecompressionError(format!("JPXDecode: {e}")))?;
    let bit_depth = image.original_bit_depth();

    let pixels = image
        .decode()
        .map_err(|e| PdfError::DecompressionError(format!("JPXDecode: {e}")))?;
    Ok((pixels, bit_depth))
}

/// Query the number of color channels (excluding alpha) and whether alpha is
/// present in a JPEG 2000 image, without fully decoding the pixel data.
/// Returns `(color_channels, has_alpha)`.
#[cfg(feature = "jpx")]
pub fn jpx_color_info(data: &[u8]) -> Option<(u8, bool)> {
    let image =
        hayro_jpeg2000::Image::new(data, &hayro_jpeg2000::DecodeSettings::default()).ok()?;
    Some((image.color_space().num_channels(), image.has_alpha()))
}

/// Extract image dimensions from a JPEG 2000 stream without full decode.
/// Returns `(width, height)`.
#[cfg(feature = "jpx")]
pub fn jpx_dimensions(data: &[u8]) -> Option<(u32, u32)> {
    let image =
        hayro_jpeg2000::Image::new(data, &hayro_jpeg2000::DecodeSettings::default()).ok()?;
    Some((image.width(), image.height()))
}

/// Decode filters preceding JPXDecode in a filter chain (e.g. ASCIIHexDecode).
/// Returns the raw JP2/J2K data ready for `jpx_dimensions` / `jpx_color_info`.
pub fn decode_pre_jpx(raw: &[u8], dict: &crate::objects::PdfDict) -> Vec<u8> {
    let (filters, parms) = parse_filters(dict, None).unwrap_or_default();
    // Apply all filters except JPXDecode
    let pre_count = filters
        .iter()
        .take_while(|f| !matches!(f, Filter::JPXDecode))
        .count();
    if pre_count == 0 {
        return raw.to_vec();
    }
    let pre_parms: Vec<_> = parms.into_iter().take(pre_count).collect();
    decode_stream(raw, &filters[..pre_count], &pre_parms, None).unwrap_or_else(|_| raw.to_vec())
}

/// Apply PNG or TIFF predictor to decoded data.
fn apply_predictor(data: &[u8], parms: &PdfDict, predictor: i64) -> Result<Vec<u8>, PdfError> {
    let columns = parms.get_int(b"Columns").unwrap_or(1) as usize;
    let colors = parms.get_int(b"Colors").unwrap_or(1) as usize;
    let bpc = parms.get_int(b"BitsPerComponent").unwrap_or(8) as usize;

    let bytes_per_pixel = (colors * bpc).div_ceil(8);
    let row_bytes = (columns * colors * bpc).div_ceil(8);

    if predictor == 2 {
        // TIFF horizontal differencing
        if bpc < 8 {
            // Sub-byte samples: operate at sample level, not byte level
            apply_tiff_predictor_subbyte(data, columns, colors, bpc, row_bytes)
        } else if bpc == 16 {
            // 16-bit samples: add as 16-bit values, not byte-by-byte
            apply_tiff_predictor_16bit(data, columns, colors, row_bytes)
        } else {
            apply_tiff_predictor(data, row_bytes, bytes_per_pixel)
        }
    } else if predictor >= 10 {
        // PNG predictors
        apply_png_predictor(data, row_bytes, bytes_per_pixel)
    } else {
        Ok(data.to_vec())
    }
}

/// TIFF predictor 2 for sub-byte samples (BPC = 1, 2, or 4).
/// Operates at the individual sample level within packed bytes.
fn apply_tiff_predictor_subbyte(
    data: &[u8],
    columns: usize,
    colors: usize,
    bpc: usize,
    row_bytes: usize,
) -> Result<Vec<u8>, PdfError> {
    let samples_per_row = columns * colors;
    let mask = (1u8 << bpc) - 1; // e.g., 1 for bpc=1, 3 for bpc=2, 15 for bpc=4
    let mut result = Vec::with_capacity(data.len());

    for row in data.chunks(row_bytes) {
        let mut out_row = vec![0u8; row.len()];
        // Copy the raw bytes first, then undo differencing at sample level
        out_row[..row.len()].copy_from_slice(row);

        // Extract all samples, undo differencing, re-pack
        let mut prev = vec![0u8; colors];
        for col in 0..columns {
            for c in 0..colors {
                let sample_idx = col * colors + c;
                if sample_idx >= samples_per_row {
                    break;
                }
                let bit_offset = sample_idx * bpc;
                let byte_idx = bit_offset / 8;
                let bit_pos = 8 - bpc - (bit_offset % 8); // MSB-first packing
                if byte_idx >= row.len() {
                    break;
                }
                let encoded = (row[byte_idx] >> bit_pos) & mask;
                let decoded = (encoded.wrapping_add(prev[c])) & mask;
                prev[c] = decoded;
                // Write back
                out_row[byte_idx] = (out_row[byte_idx] & !(mask << bit_pos)) | (decoded << bit_pos);
            }
        }
        result.extend_from_slice(&out_row);
    }

    Ok(result)
}

/// TIFF predictor 2 for 16-bit samples.
///
/// Each sample is 2 bytes (big-endian). The byte-level predictor doesn't
/// propagate carry between high and low bytes, producing wrong results.
fn apply_tiff_predictor_16bit(
    data: &[u8],
    columns: usize,
    colors: usize,
    row_bytes: usize,
) -> Result<Vec<u8>, PdfError> {
    let mut result = Vec::with_capacity(data.len());

    for row in data.chunks(row_bytes) {
        let mut out_row = vec![0u8; row.len()];
        let mut prev = vec![0u16; colors];

        for col in 0..columns {
            for c in 0..colors {
                let byte_idx = (col * colors + c) * 2;
                if byte_idx + 1 >= row.len() {
                    break;
                }
                let encoded = u16::from_be_bytes([row[byte_idx], row[byte_idx + 1]]);
                let decoded = encoded.wrapping_add(prev[c]);
                prev[c] = decoded;
                let [hi, lo] = decoded.to_be_bytes();
                out_row[byte_idx] = hi;
                out_row[byte_idx + 1] = lo;
            }
        }
        result.extend_from_slice(&out_row);
    }

    Ok(result)
}

/// TIFF predictor 2: horizontal differencing.
fn apply_tiff_predictor(
    data: &[u8],
    row_bytes: usize,
    bytes_per_pixel: usize,
) -> Result<Vec<u8>, PdfError> {
    let mut result = Vec::with_capacity(data.len());

    for row in data.chunks(row_bytes) {
        let mut out_row = vec![0u8; row.len()];
        for i in 0..row.len() {
            let left = if i >= bytes_per_pixel {
                out_row[i - bytes_per_pixel]
            } else {
                0
            };
            out_row[i] = row[i].wrapping_add(left);
        }
        result.extend_from_slice(&out_row);
    }

    Ok(result)
}

/// PNG predictors (10-15): per-row predictor byte.
fn apply_png_predictor(
    data: &[u8],
    row_bytes: usize,
    bytes_per_pixel: usize,
) -> Result<Vec<u8>, PdfError> {
    // Each row has a leading predictor byte + row_bytes data bytes
    let stride = row_bytes + 1;

    // Detect data that lacks predictor bytes despite DecodeParms claiming them.
    // If data divides evenly into row_bytes but NOT into stride, the stream
    // was written without per-row predictor prefixes — return as-is.
    if row_bytes > 0
        && !data.is_empty()
        && data.len().is_multiple_of(row_bytes)
        && !data.len().is_multiple_of(stride)
    {
        return Ok(data.to_vec());
    }

    let num_rows = data.len() / stride;
    let mut result = Vec::with_capacity(num_rows * row_bytes);
    let mut prev_row = vec![0u8; row_bytes];

    for row_idx in 0..num_rows {
        let row_start = row_idx * stride;
        if row_start >= data.len() {
            break;
        }
        let filter_type = data[row_start];
        let row_data = &data[row_start + 1..std::cmp::min(row_start + stride, data.len())];
        let mut out_row = vec![0u8; row_data.len()];

        match filter_type {
            0 => {
                // None
                out_row.copy_from_slice(row_data);
            }
            1 => {
                // Sub
                for i in 0..row_data.len() {
                    let left = if i >= bytes_per_pixel {
                        out_row[i - bytes_per_pixel]
                    } else {
                        0
                    };
                    out_row[i] = row_data[i].wrapping_add(left);
                }
            }
            2 => {
                // Up
                for i in 0..row_data.len() {
                    let up = if i < prev_row.len() { prev_row[i] } else { 0 };
                    out_row[i] = row_data[i].wrapping_add(up);
                }
            }
            3 => {
                // Average
                for i in 0..row_data.len() {
                    let left = if i >= bytes_per_pixel {
                        out_row[i - bytes_per_pixel] as u16
                    } else {
                        0
                    };
                    let up = if i < prev_row.len() {
                        prev_row[i] as u16
                    } else {
                        0
                    };
                    out_row[i] = row_data[i].wrapping_add(((left + up) / 2) as u8);
                }
            }
            4 => {
                // Paeth
                for i in 0..row_data.len() {
                    let left = if i >= bytes_per_pixel {
                        out_row[i - bytes_per_pixel]
                    } else {
                        0
                    };
                    let up = if i < prev_row.len() { prev_row[i] } else { 0 };
                    let up_left = if i >= bytes_per_pixel && i - bytes_per_pixel < prev_row.len() {
                        prev_row[i - bytes_per_pixel]
                    } else {
                        0
                    };
                    out_row[i] = row_data[i].wrapping_add(paeth(left, up, up_left));
                }
            }
            _ => {
                // Unknown predictor type — pass through
                out_row.copy_from_slice(row_data);
            }
        }

        prev_row[..out_row.len()].copy_from_slice(&out_row);
        result.extend_from_slice(&out_row);
    }

    Ok(result)
}

/// Paeth predictor function.
fn paeth(a: u8, b: u8, c: u8) -> u8 {
    let a = a as i16;
    let b = b as i16;
    let c = c as i16;
    let p = a + b - c;
    let pa = (p - a).abs();
    let pb = (p - b).abs();
    let pc = (p - c).abs();
    if pa <= pb && pa <= pc {
        a as u8
    } else if pb <= pc {
        b as u8
    } else {
        c as u8
    }
}

fn hex_digit(b: u8) -> Option<u8> {
    match b {
        b'0'..=b'9' => Some(b - b'0'),
        b'a'..=b'f' => Some(b - b'a' + 10),
        b'A'..=b'F' => Some(b - b'A' + 10),
        _ => None,
    }
}

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

    #[test]
    fn flate_round_trip() {
        use flate2::Compression;
        use flate2::write::ZlibEncoder;
        use std::io::Write;

        let original = b"Hello, PDF world! This is a test of FlateDecode.";
        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
        enc.write_all(original).unwrap();
        let compressed = enc.finish().unwrap();

        let decoded = decode_flate(&compressed, None).unwrap();
        assert_eq!(&decoded, original);
    }

    #[test]
    fn ascii_hex_decode() {
        let decoded = decode_ascii_hex(b"48656C6C6F>").unwrap();
        assert_eq!(&decoded, b"Hello");
    }

    #[test]
    fn ascii_hex_odd_digits() {
        let decoded = decode_ascii_hex(b"ABC>").unwrap();
        assert_eq!(decoded, vec![0xAB, 0xC0]);
    }

    #[test]
    fn ascii85_decode() {
        // "Hello" in ASCII85 = 87cURD]j7
        // Full encoding: <~87cURD]j7BEbo7~>  (for "Hello, World")
        // Simple test: encode "test" = FCfN8
        let decoded = decode_ascii85(b"FCfN8~>").unwrap();
        assert_eq!(&decoded, b"test");
    }

    #[test]
    fn ascii85_z_shortcut() {
        let decoded = decode_ascii85(b"z~>").unwrap();
        assert_eq!(decoded, vec![0, 0, 0, 0]);
    }

    #[test]
    fn run_length_decode() {
        // 2 = copy 3 bytes, then 253 = repeat next byte 4 times, then 128 = EOD
        let data = vec![2, b'A', b'B', b'C', 253, b'X', 128];
        let decoded = decode_run_length(&data).unwrap();
        assert_eq!(&decoded, b"ABCXXXX");
    }

    #[test]
    fn png_predictor_none() {
        // Row of 3 bytes, predictor type 0 (none)
        let data = vec![0, 10, 20, 30];
        let result = apply_png_predictor(&data, 3, 1).unwrap();
        assert_eq!(result, vec![10, 20, 30]);
    }

    #[test]
    fn png_predictor_sub() {
        // Row of 3 bytes, predictor type 1 (sub), bpp=1
        // input: [5, 3, 4] -> output: [5, 8, 12]
        let data = vec![1, 5, 3, 4];
        let result = apply_png_predictor(&data, 3, 1).unwrap();
        assert_eq!(result, vec![5, 8, 12]);
    }

    #[test]
    fn png_predictor_up() {
        // Two rows, predictor type 2 (up)
        // Row 0: [0, 10, 20, 30]  (type 0 = none)
        // Row 1: [2, 5, 5, 5]    (type 2 = up)
        let data = vec![0, 10, 20, 30, 2, 5, 5, 5];
        let result = apply_png_predictor(&data, 3, 1).unwrap();
        assert_eq!(result, vec![10, 20, 30, 15, 25, 35]);
    }

    #[test]
    fn filter_chain() {
        use flate2::Compression;
        use flate2::write::ZlibEncoder;
        use std::io::Write;

        let original = b"filter chain test data";
        let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
        enc.write_all(original).unwrap();
        let compressed = enc.finish().unwrap();

        // Encode as ASCII hex
        let mut hex = String::new();
        for b in &compressed {
            hex.push_str(&format!("{b:02X}"));
        }
        hex.push('>');

        let filters = vec![Filter::ASCIIHexDecode, Filter::FlateDecode];
        let parms = vec![None, None];
        let decoded = decode_stream(hex.as_bytes(), &filters, &parms, None).unwrap();
        assert_eq!(&decoded, original);
    }
}