xberg 1.2.0

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

use crate::error::{Result, XbergError};
use crate::types::{ExtractedImage, ProcessingWarning};
use bytes::Bytes;
use std::borrow::Cow;
use std::io::Cursor;

/// Warning source tag for `.ppt` extraction diagnostics (#171 convention).
const PPT_WARNING_SOURCE: &str = "ppt";

/// Result of PPT text extraction.
#[cfg_attr(alef, alef(skip))]
pub struct PptExtractionResult {
    /// Full document text: every slide's text joined by double newlines,
    /// kept for diagnostics/plain-text consumers. Slide *structure* (numbers,
    /// per-slide boundaries) must come from `slides`, not from re-splitting
    /// this string (see #1418 -- a slide's own text can itself contain an
    /// internal "\n\n", which makes re-splitting on it ambiguous).
    pub text: String,
    /// Per-slide text, in persist order. `number` is the slide's 1-based
    /// position among `RT_SLIDE` containers as they occur in the
    /// "PowerPoint Document" stream -- the same order `slide_count` counts.
    /// A slide with no text atoms still gets an entry (with an empty
    /// `text`), so slide numbers stay contiguous with the real deck.
    pub slides: Vec<PptSlideText>,
    /// Number of slides found.
    pub slide_count: usize,
    /// Document metadata.
    pub metadata: PptMetadata,
    /// Speaker notes text per slide (if available).
    pub speaker_notes: Vec<String>,
    /// Pictures recovered from the OLE `Pictures` stream (raw
    /// `OfficeArtBlip` payloads). Empty when the deck has no `Pictures`
    /// stream, the stream is empty, or image extraction was not requested.
    /// `page_number` is the slide whose drawing displays the picture, resolved
    /// through `pib` -> `msofbtBSE.foDelay`; it stays `None` for a blip no live
    /// shape references (#1620).
    pub images: Vec<ExtractedImage>,
    /// Non-fatal degradations encountered while extracting (see
    /// `core::diagnostics`). Empty when extraction was complete.
    pub processing_warnings: Vec<ProcessingWarning>,
}

/// One slide's text, numbered by its position in the deck's own persist
/// order rather than by the position of a text block in a joined string.
#[cfg_attr(alef, alef(skip))]
pub struct PptSlideText {
    /// 1-based slide number, as encountered in persist order.
    pub number: u32,
    /// The slide's text (its atoms joined by `\n`). Empty for a slide with
    /// no text.
    pub text: String,
}

/// Metadata extracted from PPT files.
#[cfg_attr(alef, alef(skip))]
#[derive(Default)]
pub struct PptMetadata {
    /// Presentation title from the OLE summary information.
    pub title: Option<String>,
    /// Presentation subject from the OLE summary information.
    pub subject: Option<String>,
    /// Original author from the OLE summary information.
    pub author: Option<String>,
    /// Most recent editor from the OLE summary information.
    pub last_author: Option<String>,
}

const RT_TEXT_CHARS_ATOM: u16 = 0x0FA0;
const RT_TEXT_BYTES_ATOM: u16 = 0x0FA8;
/// A single slide's persisted content container (SlideAtom + shapes/text).
/// `SlideListWithText` (0x0FF0), by contrast, is a per-document container of
/// `SlidePersistAtom` entries used for the outline view -- it does not
/// enclose the slides' actual text and does not occur once per slide, so it
/// cannot be used as a slide boundary (#87).
const RT_SLIDE: u16 = 0x03EE;
const RT_MAIN_MASTER: u16 = 0x03F8;
/// Document-level outline collection. A legacy deck keeps a slide's title here rather than in
/// the slide's own drawing, and reading only the drawing lost every such title
/// (xberg-io/xberg#1612). This is NOT a slide boundary -- see
/// `test_extract_texts_segments_on_slide_not_slide_list_with_text`. ~keep
const RT_SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0;
/// Introduces one slide's entries inside [`RT_SLIDE_LIST_WITH_TEXT`]; the nth such atom starts
/// the outline records belonging to the nth slide, which is how outline text is attributed. ~keep
const RT_SLIDE_PERSIST_ATOM: u16 = 0x03F3;
const RT_NOTES: u16 = 0x03F0;

/// `OfficeArtBlip` record types for the raster formats a `Pictures` stream
/// can hold (MS-ODRAW 2.2.23). `RT_BLIP_JPEG_ALT` (0xF02A) is an alternate
/// `recType` documented for JPEG blips written by older Office versions; it
/// uses the same `OfficeArtBlipJPEG` layout as 0xF01D.
const RT_BLIP_JPEG: u16 = 0xF01D;
const RT_BLIP_JPEG_ALT: u16 = 0xF02A;
const RT_BLIP_PNG: u16 = 0xF01E;
const RT_BLIP_DIB: u16 = 0xF01F;

/// `msofbtBSE` -- one per blip in the document's `BStoreContainer`. A shape's `pib`
/// property is a 1-based index into these, in container order (MS-ODRAW 2.2.32). ~keep
const MSOFBT_BSE: u16 = 0xF007;
/// Byte offset of `foDelay` inside an `msofbtBSE`'s content, past `btWin32` (1), `btMacOS`
/// (1), `rgbUid` (16), `tag` (2), `size` (4) and `cRef` (4). `foDelay` is the blip record's
/// own start offset in the `Pictures` stream, which is the key `Pictures` is walked by. ~keep
const BSE_FO_DELAY_OFFSET: usize = 28;

/// `msofbtOPT` and its secondary/tertiary siblings, each a table of `OfficeArtFOPTE`
/// property entries (MS-ODRAW 2.3.1). `pib` is normally in the primary table, but a
/// shape that overflows its property set spills into the other two. ~keep
const MSOFBT_OPT: [u16; 3] = [0xF00B, 0xF121, 0xF122];
/// An `OfficeArtFOPTE` is a 2-byte `opid` followed by a 4-byte value.
const FOPT_ENTRY_LEN: usize = 6;
/// The low 14 bits of `opid` are the property number; bit 14 is `fBid` and bit 15 is
/// `fComplex`, neither of which changes where the entry sits. ~keep
const FOPT_PROPERTY_ID_MASK: u16 = 0x3FFF;
/// `pib` -- the 1-based `BStoreContainer` index of the blip a picture shape displays.
const MSO_PROPERTY_PIB: u16 = 0x0104;

/// Depth cap for the OfficeArt container walk. Real nesting is under a dozen levels; this
/// only stops a hostile self-describing container tree from exhausting the stack. ~keep
const MAX_OFFICE_ART_DEPTH: usize = 16;

/// `UserEditAtom` -- one per save, chained newest-to-oldest through `offsetLastEdit`.
const RT_USER_EDIT_ATOM: u16 = 0x0FF5;
/// `PersistDirectoryAtom` -- maps persist ids to stream offsets for one save.
const RT_PERSIST_DIRECTORY_ATOM: u16 = 0x1772;

/// Byte offset of `offsetToCurrentEdit` within the `Current User` stream: an 8-byte
/// record header, then `size` (4) and `headerToken` (4) precede it (MS-PPT 2.3.2). ~keep
const CURRENT_USER_OFFSET_TO_CURRENT_EDIT: usize = 16;

/// A `persistId` is the low 20 bits of a `PersistDirectoryEntry`'s first dword; the
/// high 12 bits are `cPersist`, the number of consecutive ids the entry covers
/// (MS-PPT 2.3.6). ~keep
const PERSIST_ID_MASK: u32 = 0x000F_FFFF;
const PERSIST_COUNT_SHIFT: u32 = 20;

/// Upper bound on `UserEditAtom` hops. A `.ppt` accumulates one per save, so a legitimate
/// chain is long but finite; this only exists so a corrupt or hostile `offsetLastEdit`
/// cycle cannot spin forever. Chains longer than this fall back to stream order. ~keep
const MAX_USER_EDIT_CHAIN: usize = 4096;

/// Maximum accepted size for a single embedded picture (100 MB), mirroring
/// the DOCX/PPTX image cap (`crate::extraction::docx::MAX_IMAGE_FILE_SIZE`).
/// Bounds allocation from a hostile `recLen` in the untrusted `Pictures`
/// stream.
const MAX_PICTURE_SIZE: usize = 100 * 1024 * 1024;

/// Extract text from PPT bytes.
///
/// Parses the OLE/CFB compound document, reads the "PowerPoint Document" stream,
/// and extracts text from TextCharsAtom and TextBytesAtom records.
///
/// When `include_master_slides` is `true`, master slide content (placeholder text
/// like "Click to edit Master title style") is included instead of being skipped.
#[cfg(test)]
pub(crate) fn extract_ppt_text(content: &[u8]) -> Result<PptExtractionResult> {
    extract_ppt_text_with_options(content, false, true)
}

/// Extract text from PPT bytes with configurable master slide inclusion and
/// image extraction.
///
/// When `include_master_slides` is `true`, `RT_MAIN_MASTER` containers are not
/// skipped, so master slide placeholder text is included in the output.
///
/// When `extract_images` is `true`, the OLE `Pictures` stream (if present)
/// is walked for embedded raster images (#1417).
pub(crate) fn extract_ppt_text_with_options(
    content: &[u8],
    include_master_slides: bool,
    extract_images: bool,
) -> Result<PptExtractionResult> {
    let cursor = Cursor::new(content);
    let mut comp = cfb::CompoundFile::open(cursor)
        .map_err(|e| XbergError::parsing(format!("Failed to open PPT as OLE container: {e}")))?;

    let metadata = extract_ppt_metadata(&mut comp);

    let ppt_stream = read_stream(&mut comp, "/PowerPoint Document")?;
    if ppt_stream.is_empty() {
        return Err(XbergError::parsing("PowerPoint Document stream is empty"));
    }

    let mut processing_warnings = Vec::new();
    // Absent or unreadable `Current User` stream leaves this `None`, and the walk keeps the
    // stream order it always used. See [`live_slide_offsets`] for why a partial answer is
    // deliberately not produced.
    let current_user_stream = read_stream(&mut comp, "/Current User").unwrap_or_default();
    let live_slides = live_slide_offsets(&ppt_stream, &current_user_stream);
    if live_slides.is_none() {
        tracing::debug!(
            target: "xberg::ppt",
            "no live slide list resolved from the persist chain; using stream order"
        );
    }

    let (mut slides, loose_texts, speaker_notes) = extract_texts_from_records(
        &ppt_stream,
        include_master_slides,
        live_slides.as_deref(),
        &mut processing_warnings,
    )?;

    // Computed from the pre-fallback data so `loose_texts` is never counted
    // twice below (once here, once folded into the synthetic slide).
    let text = slides
        .iter()
        .map(|s| s.text.as_str())
        .chain(loose_texts.iter().map(String::as_str))
        .filter(|t| !t.trim().is_empty())
        .collect::<Vec<_>>()
        .join("\n\n");

    // Defensive fallback for a stream with no `RT_SLIDE` containers at all
    // but with top-level text outside any slide/notes container: surface it
    // as a single synthetic slide rather than dropping it (matches the
    if slides.is_empty() && !loose_texts.is_empty() {
        slides.push(PptSlideText {
            number: 1,
            text: loose_texts.join("\n"),
        });
    }
    let slide_count = slides.len();

    let images = if extract_images {
        match read_stream(&mut comp, "/Pictures") {
            Ok(pictures_stream) if !pictures_stream.is_empty() => {
                let slide_numbers = picture_slide_numbers(&ppt_stream, live_slides.as_deref());
                extract_pictures_from_stream(&pictures_stream, &slide_numbers, &mut processing_warnings)
            }
            _ => Vec::new(),
        }
    } else {
        Vec::new()
    };

    Ok(PptExtractionResult {
        text: text.trim().to_string(),
        slides,
        slide_count,
        metadata,
        speaker_notes,
        images,
        processing_warnings,
    })
}

/// Read a little-endian `u32` at `offset`, or `None` if it does not fit in `data`.
fn read_u32_le(data: &[u8], offset: usize) -> Option<u32> {
    let bytes = data.get(offset..offset.checked_add(4)?)?;
    Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}

/// Resolve the live slide containers, in presentation order, as byte offsets into the
/// "PowerPoint Document" stream.
///
/// A `.ppt` stream is append-only across saves: editing a deck writes new copies of the
/// objects that changed and leaves the old ones in place. Walking the stream and calling
/// every `RT_SLIDE` container a slide therefore counts deleted and superseded revisions
/// as slides, and numbers them by byte order rather than by the order they are presented
/// in. The format states both answers explicitly and this reads them:
///
/// ```text
/// Current User stream
///   CurrentUserAtom.offsetToCurrentEdit ─▶ UserEditAtom (0x0FF5)
///                                            .offsetPersistDirectory ─▶ PersistDirectoryAtom (0x1772)
///                                            .offsetLastEdit         ─▶ the previous save's UserEditAtom
///
/// Document > SlideListWithText (0x0FF0, recInstance 0)
///   SlidePersistAtom (0x03F3) per slide, in presentation order,
///   each naming the persist id of that slide's Slide container
/// ```
///
/// Persist directories are merged newest-first, so a later save's entry for an id wins
/// and older revisions of the same object are never reachable.
///
/// Returns `None` whenever the chain cannot be read in full -- absent `Current User`
/// stream, unparseable atom, offset out of range, or a slide list naming an id no
/// directory resolves. The caller then keeps stream order, which is what this extractor
/// did unconditionally before. A partial answer would be worse than the old behaviour:
/// it would drop real slides. See GH#1614. ~keep
fn live_slide_offsets(ppt_stream: &[u8], current_user_stream: &[u8]) -> Option<Vec<usize>> {
    let first_edit = read_u32_le(current_user_stream, CURRENT_USER_OFFSET_TO_CURRENT_EDIT)? as usize;

    // persist id -> stream offset, newest save wins.
    let mut persist: ahash::AHashMap<u32, usize> = ahash::AHashMap::new();
    let mut next_edit = Some(first_edit);
    let mut hops = 0usize;

    while let Some(edit_offset) = next_edit {
        hops += 1;
        if hops > MAX_USER_EDIT_CHAIN {
            return None;
        }
        let header = ppt_stream.get(edit_offset..edit_offset.checked_add(8)?)?;
        if u16::from_le_bytes([header[2], header[3]]) != RT_USER_EDIT_ATOM {
            return None;
        }
        let content = edit_offset + 8;
        let offset_last_edit = read_u32_le(ppt_stream, content + 8)? as usize;
        let offset_persist_directory = read_u32_le(ppt_stream, content + 12)? as usize;

        merge_persist_directory(ppt_stream, offset_persist_directory, &mut persist)?;

        // `offsetLastEdit` is 0 at the first save. Anything that does not move BACKWARD is
        // a cycle or corruption, and following it would not terminate. ~keep
        next_edit = match offset_last_edit {
            0 => None,
            previous if previous < edit_offset => Some(previous),
            _ => return None,
        };
    }

    let slide_ids = slide_persist_ids_in_presentation_order(ppt_stream)?;
    if slide_ids.is_empty() {
        return None;
    }
    slide_ids
        .into_iter()
        .map(|id| {
            let offset = *persist.get(&id)?;
            let header = ppt_stream.get(offset..offset.checked_add(8)?)?;
            (u16::from_le_bytes([header[2], header[3]]) == RT_SLIDE).then_some(offset)
        })
        .collect()
}

/// Merge one save's `PersistDirectoryAtom` into `persist` without overwriting an entry a
/// newer save already claimed. Returns `None` if the atom is not where the `UserEditAtom`
/// says it is, or is internally inconsistent.
fn merge_persist_directory(
    ppt_stream: &[u8],
    directory_offset: usize,
    persist: &mut ahash::AHashMap<u32, usize>,
) -> Option<()> {
    let header = ppt_stream.get(directory_offset..directory_offset.checked_add(8)?)?;
    if u16::from_le_bytes([header[2], header[3]]) != RT_PERSIST_DIRECTORY_ATOM {
        return None;
    }
    let length = u32::from_le_bytes([header[4], header[5], header[6], header[7]]) as usize;
    let start = directory_offset + 8;
    let entries = ppt_stream.get(start..start.checked_add(length)?)?;

    let mut cursor = 0usize;
    while cursor + 4 <= entries.len() {
        let packed = read_u32_le(entries, cursor)?;
        let first_id = packed & PERSIST_ID_MASK;
        let count = (packed >> PERSIST_COUNT_SHIFT) as usize;
        cursor += 4;
        for index in 0..count {
            let offset = read_u32_le(entries, cursor)? as usize;
            cursor += 4;
            // `or_insert` and not `insert`: directories arrive newest-first, so the first
            // writer of an id is the live revision and later (older) saves must not
            // clobber it. ~keep
            persist.entry(first_id + index as u32).or_insert(offset);
        }
    }
    Some(())
}

/// The persist ids named by the document's `SlideListWithText` (`recInstance` 0), in the
/// order the deck presents them.
///
/// `recInstance` distinguishes the three lists a document can carry -- 0 slides,
/// 1 master, 2 notes -- and only the first is the presentation's slide order. It is the
/// top 12 bits of the record header's first `u16`. ~keep
fn slide_persist_ids_in_presentation_order(ppt_stream: &[u8]) -> Option<Vec<u32>> {
    let mut pos = 0usize;
    while pos + 8 <= ppt_stream.len() {
        let ver_instance = u16::from_le_bytes([ppt_stream[pos], ppt_stream[pos + 1]]);
        let rec_type = u16::from_le_bytes([ppt_stream[pos + 2], ppt_stream[pos + 3]]);
        let rec_len = u32::from_le_bytes([
            ppt_stream[pos + 4],
            ppt_stream[pos + 5],
            ppt_stream[pos + 6],
            ppt_stream[pos + 7],
        ]) as usize;
        let content_start = pos + 8;
        let content_end = content_start.checked_add(rec_len)?;
        if content_end > ppt_stream.len() {
            return None;
        }

        if rec_type == RT_SLIDE_LIST_WITH_TEXT && (ver_instance >> 4) == 0 {
            let mut ids = Vec::new();
            let mut inner = content_start;
            while inner + 8 <= content_end {
                let inner_type = u16::from_le_bytes([ppt_stream[inner + 2], ppt_stream[inner + 3]]);
                let inner_len = u32::from_le_bytes([
                    ppt_stream[inner + 4],
                    ppt_stream[inner + 5],
                    ppt_stream[inner + 6],
                    ppt_stream[inner + 7],
                ]) as usize;
                if inner_type == RT_SLIDE_PERSIST_ATOM {
                    ids.push(read_u32_le(ppt_stream, inner + 8)?);
                }
                inner = inner.checked_add(8)?.checked_add(inner_len)?;
            }
            return Some(ids);
        }

        // Descend into containers so a nested SlideListWithText is still found.
        pos = if (ver_instance & 0x000F) == 0x0F {
            content_start
        } else {
            content_end
        };
    }
    None
}

/// Parse PowerPoint record headers and extract text atoms.
///
/// Returns `(slides, loose_texts, speaker_notes)`, where `slides` carries
/// one entry per `RT_SLIDE` container in persist order (including empty
/// slides), and `loose_texts` carries text found outside any slide/notes
/// container (rare, but preserved for the `slide_count == 0` fallback).
///
/// When `include_master_slides` is `true`, master slide containers are not
/// skipped, allowing their placeholder text to appear in the output.
fn extract_texts_from_records(
    data: &[u8],
    include_master_slides: bool,
    live_slides: Option<&[usize]>,
    warnings: &mut Vec<ProcessingWarning>,
) -> Result<(Vec<PptSlideText>, Vec<String>, Vec<String>)> {
    let mut slides: Vec<PptSlideText> = Vec::new();
    let mut loose_texts = Vec::new();
    let mut current_slide_number: u32 = 0;
    let mut pos = 0;
    let mut in_slide_text = false;
    let mut slide_end: Option<usize> = None;
    let mut current_slide_texts: Vec<String> = Vec::new();
    let mut speaker_notes = Vec::new();
    let mut in_notes = false;
    let mut notes_end: Option<usize> = None;
    let mut current_notes_texts: Vec<String> = Vec::new();
    // Outline text keyed by slide position, harvested from `SlideListWithText` (#1612).
    let mut outline_texts: Vec<Vec<String>> = Vec::new();
    let mut outline_end: Option<usize> = None;
    let mut outline_slide_index: Option<usize> = None;

    while pos + 8 <= data.len() {
        // A slide/notes container's text only spans its own declared byte
        // range; close it out as soon as the walk passes that range's end,
        // rather than leaving `in_slide_text`/`in_notes` stuck on until the
        // *next* occurrence (which, for `in_slide_text`, previously ran on
        // to the end of the stream -- see `RT_SLIDE` below).
        if let Some(end) = slide_end
            && pos >= end
        {
            // Push even when empty: a slide with no text atoms still exists
            // and must keep its persist-order number (#1418), rather than
            // vanishing and shifting every later slide's number down.
            slides.push(PptSlideText {
                number: current_slide_number,
                text: current_slide_texts.join("\n"),
            });
            current_slide_texts.clear();
            in_slide_text = false;
            slide_end = None;
        }
        if let Some(end) = outline_end
            && pos >= end
        {
            outline_end = None;
            outline_slide_index = None;
        }
        if let Some(end) = notes_end
            && pos >= end
        {
            if !current_notes_texts.is_empty() {
                let notes_text = current_notes_texts.join("\n");
                let trimmed = notes_text.trim().to_string();
                if !trimmed.is_empty() {
                    speaker_notes.push(trimmed);
                }
                current_notes_texts.clear();
            }
            in_notes = false;
            notes_end = None;
        }

        let rec_ver_instance = u16::from_le_bytes([data[pos], data[pos + 1]]);
        let rec_ver = rec_ver_instance & 0x000F;
        let rec_type = u16::from_le_bytes([data[pos + 2], data[pos + 3]]);
        let rec_len = u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]]) as usize;

        if rec_len > data.len() - pos {
            crate::core::diagnostics::push_warning(
                warnings,
                PPT_WARNING_SOURCE,
                "Record stream ended with a truncated record; the remaining presentation content was not extracted",
            );
            break;
        }

        let is_container = rec_ver == 0x0F;
        let content_start = pos + 8;
        let content_end = content_start + rec_len;

        match rec_type {
            RT_SLIDE => {
                // With a resolved persist chain, only the containers the live slide list
                // names are slides, and their number is their position in that list. A
                // container the list does not name is a deleted or superseded revision the
                // stream still carries, and must not be extracted or counted (#1614).
                let presentation_number = match live_slides {
                    Some(offsets) => match offsets.iter().position(|&offset| offset == pos) {
                        Some(index) => index as u32 + 1,
                        None => {
                            pos = content_end;
                            continue;
                        }
                    },
                    None => current_slide_number + 1,
                };
                if in_slide_text {
                    slides.push(PptSlideText {
                        number: current_slide_number,
                        text: current_slide_texts.join("\n"),
                    });
                    current_slide_texts.clear();
                }
                current_slide_number = presentation_number;
                in_slide_text = true;
                slide_end = Some(content_end);
                pos += 8;
                continue;
            }
            RT_NOTES => {
                if in_notes && !current_notes_texts.is_empty() {
                    let notes_text = current_notes_texts.join("\n");
                    let trimmed = notes_text.trim().to_string();
                    if !trimmed.is_empty() {
                        speaker_notes.push(trimmed);
                    }
                    current_notes_texts.clear();
                }
                in_notes = true;
                notes_end = Some(content_end);
                pos += 8;
                continue;
            }
            RT_MAIN_MASTER if !include_master_slides => {
                pos = content_end;
                continue;
            }
            RT_SLIDE_LIST_WITH_TEXT => {
                outline_end = Some(content_end);
                outline_slide_index = None;
                pos += 8;
                continue;
            }
            RT_SLIDE_PERSIST_ATOM if outline_end.is_some() => {
                let next = outline_slide_index.map_or(0, |i| i + 1);
                outline_slide_index = Some(next);
                if outline_texts.len() <= next {
                    outline_texts.resize(next + 1, Vec::new());
                }
                pos = content_end;
                continue;
            }
            RT_TEXT_CHARS_ATOM => {
                if content_end <= data.len() {
                    let text_data = &data[content_start..content_end];
                    let chars: Vec<u16> = text_data
                        .chunks_exact(2)
                        .map(|c| u16::from_le_bytes([c[0], c[1]]))
                        .collect();
                    let text = String::from_utf16_lossy(&chars);
                    let cleaned = clean_ppt_text(&text);
                    if !cleaned.is_empty() {
                        if let Some(index) = outline_slide_index {
                            // Outline text belongs to a slide, not to `loose_texts` -- which is
                            // discarded whenever any slide exists, and is where every legacy
                            // title used to end up (#1612).
                            outline_texts[index].push(cleaned);
                        } else {
                            if in_notes {
                                current_notes_texts.push(cleaned.clone());
                            }
                            if in_slide_text {
                                current_slide_texts.push(cleaned);
                            } else if !in_notes {
                                loose_texts.push(cleaned);
                            }
                        }
                    }
                }
                pos = content_end;
                continue;
            }
            RT_TEXT_BYTES_ATOM => {
                if content_end <= data.len() {
                    let text_data = &data[content_start..content_end];
                    let text: String = text_data.iter().map(|&b| cp1252_to_char(b)).collect();
                    let cleaned = clean_ppt_text(&text);
                    if !cleaned.is_empty() {
                        if let Some(index) = outline_slide_index {
                            // Outline text belongs to a slide, not to `loose_texts` -- which is
                            // discarded whenever any slide exists, and is where every legacy
                            // title used to end up (#1612).
                            outline_texts[index].push(cleaned);
                        } else {
                            if in_notes {
                                current_notes_texts.push(cleaned.clone());
                            }
                            if in_slide_text {
                                current_slide_texts.push(cleaned);
                            } else if !in_notes {
                                loose_texts.push(cleaned);
                            }
                        }
                    }
                }
                pos = content_end;
                continue;
            }
            _ => {}
        }

        if is_container {
            pos += 8;
        } else {
            pos = content_end;
        }
    }

    // The stream ended while still inside a slide's declared byte range
    // (e.g. a truncated record broke the walk early): still record it,
    // rather than silently dropping the last slide's text and number.
    if in_slide_text {
        slides.push(PptSlideText {
            number: current_slide_number,
            text: current_slide_texts.join("\n"),
        });
    }

    if !current_notes_texts.is_empty() {
        let notes_text = current_notes_texts.join("\n");
        let trimmed = notes_text.trim().to_string();
        if !trimmed.is_empty() {
            speaker_notes.push(trimmed);
        }
    }

    // Presentation order, not stream order: with a live slide list the walk visits the
    // containers in whatever order the saves left them, and the number assigned above is
    // the authority. Sorting here also restores the positional contract the outline merge
    // below depends on -- the nth entry of `slides` is the nth slide of the deck (#1614).
    if live_slides.is_some() {
        slides.sort_by_key(|slide| slide.number);
    }

    // Prepend each slide's outline text, skipping any line the slide's own drawing already
    // carries. A title drawn on the canvas appears in both places, and those decks are exactly
    // the ones whose titles already survived -- recovering the outline copy must not double
    // them (#1612). Attribution is positional: the nth `SlidePersistAtom` introduces the nth
    // slide's outline records, matching the persist order `slides` is built in.
    for (index, outline) in outline_texts.iter().enumerate() {
        let Some(slide) = slides.get_mut(index) else {
            continue;
        };
        let recovered: Vec<&str> = outline
            .iter()
            .map(String::as_str)
            .filter(|line| !slide.text.lines().any(|existing| existing == *line))
            .collect();
        if recovered.is_empty() {
            continue;
        }
        let joined = recovered.join("\n");
        slide.text = if slide.text.is_empty() {
            joined
        } else {
            format!("{joined}\n{}", slide.text)
        };
    }

    Ok((slides, loose_texts, speaker_notes))
}

/// One record header from the PowerPoint/OfficeArt record tree, flattened out of its
/// containers so callers can filter by type without re-walking.
struct ArtRecord {
    rec_instance: u16,
    rec_type: u16,
    content_start: usize,
    content_end: usize,
}

/// Collect every record header in `data[start..end]`, descending into containers.
///
/// A record is a container when `recVer` (the low nibble of the first field) is 0xF; its
/// children are the records inside its own declared byte range. A `recLen` that would run
/// past `end` stops the walk at that level rather than over-reading -- the stream is
/// untrusted, and a truncated tail is the common shape of a salvageable corrupt deck.
fn collect_art_records(data: &[u8], start: usize, end: usize, depth: usize, out: &mut Vec<ArtRecord>) {
    if depth > MAX_OFFICE_ART_DEPTH {
        return;
    }
    let mut pos = start;
    while pos + 8 <= end {
        let rec_ver_instance = u16::from_le_bytes([data[pos], data[pos + 1]]);
        let rec_type = u16::from_le_bytes([data[pos + 2], data[pos + 3]]);
        let rec_len = u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]]) as usize;
        let content_start = pos + 8;
        let Some(content_end) = content_start.checked_add(rec_len).filter(|&candidate| candidate <= end) else {
            return;
        };
        out.push(ArtRecord {
            rec_instance: rec_ver_instance >> 4,
            rec_type,
            content_start,
            content_end,
        });
        if rec_ver_instance & 0x000F == 0x0F {
            collect_art_records(data, content_start, content_end, depth + 1, out);
        }
        pos = content_end;
    }
}

/// The `Pictures`-stream offset of every blip, in `BStoreContainer` order, so that a
/// shape's 1-based `pib` indexes straight into the result.
fn blip_stream_offsets(data: &[u8], records: &[ArtRecord]) -> Vec<u32> {
    records
        .iter()
        .filter(|record| record.rec_type == MSOFBT_BSE)
        .filter_map(|record| {
            let at = record.content_start.checked_add(BSE_FO_DELAY_OFFSET)?;
            (at.checked_add(4)? <= record.content_end).then(|| read_u32_le(data, at))?
        })
        .collect()
}

/// The blip indices (`pib`) referenced by shapes inside one slide's byte range.
///
/// Reading `pib` wherever it appears in the slide's property tables -- rather than only
/// under a shape whose `msofbtSp` says `msosptPictureFrame` -- is deliberate: a picture
/// placed as the fill of an ordinary autoshape carries the same property and displays the
/// same blip on the same slide. ~keep
fn slide_blip_indices(data: &[u8], records: &[ArtRecord], slide_start: usize, slide_end: usize) -> Vec<u32> {
    let mut indices = Vec::new();
    for record in records
        .iter()
        .filter(|record| MSOFBT_OPT.contains(&record.rec_type))
        .filter(|record| record.content_start >= slide_start && record.content_end <= slide_end)
    {
        for entry in 0..record.rec_instance as usize {
            let Some(at) = entry
                .checked_mul(FOPT_ENTRY_LEN)
                .and_then(|o| record.content_start.checked_add(o))
            else {
                break;
            };
            if at + FOPT_ENTRY_LEN > record.content_end {
                break;
            }
            let opid = u16::from_le_bytes([data[at], data[at + 1]]);
            if opid & FOPT_PROPERTY_ID_MASK == MSO_PROPERTY_PIB
                && let Some(pib) = read_u32_le(data, at + 2)
                && pib > 0
            {
                indices.push(pib);
            }
        }
    }
    indices
}

/// Map each blip's `Pictures`-stream offset to the slide that displays it (#1620).
///
/// `Pictures` is a blob store in save order and says nothing about slides; what owns a
/// picture is the drawing, via `pib` -> `msofbtBSE.foDelay` -> that offset. Without this
/// every `.ppt` image came back with no page at all.
///
/// A blip displayed on several slides is recorded against the first, so that a logo
/// repeated through a deck stays one extracted image rather than one per slide. A blip no
/// live shape references is absent from the map and keeps today's behaviour. ~keep
fn picture_slide_numbers(data: &[u8], live_slides: Option<&[usize]>) -> std::collections::HashMap<u32, u32> {
    let mut records = Vec::new();
    collect_art_records(data, 0, data.len(), 0, &mut records);

    let blip_offsets = blip_stream_offsets(data, &records);
    let mut by_offset = std::collections::HashMap::new();
    if blip_offsets.is_empty() {
        return by_offset;
    }

    let slide_ranges: Vec<(usize, usize)> = match live_slides {
        // Presentation order, already resolved from the persist chain (#1614).
        Some(offsets) => offsets
            .iter()
            .filter_map(|&offset| {
                records
                    .iter()
                    .find(|record| record.rec_type == RT_SLIDE && record.content_start == offset + 8)
                    .map(|record| (record.content_start, record.content_end))
            })
            .collect(),
        // Mirrors the text walk's fallback: number the `RT_SLIDE` containers in stream order.
        None => records
            .iter()
            .filter(|record| record.rec_type == RT_SLIDE)
            .map(|record| (record.content_start, record.content_end))
            .collect(),
    };

    for (index, (slide_start, slide_end)) in slide_ranges.iter().enumerate() {
        let slide_number = index as u32 + 1;
        for pib in slide_blip_indices(data, &records, *slide_start, *slide_end) {
            if let Some(&offset) = blip_offsets.get(pib as usize - 1) {
                by_offset.entry(offset).or_insert(slide_number);
            }
        }
    }
    by_offset
}

/// Walk a `Pictures` stream (a flat run of `OfficeArtBlip` records, MS-ODRAW
/// 2.2.23) and emit one `ExtractedImage` per raster blip.
///
/// Only the raster formats stored as `rgbUid` + optional second `rgbUid` +
/// `tag` + `BLIPFileData` are handled: JPEG (0xF01D / the alternate 0xF02A),
/// PNG (0xF01E), and DIB (0xF01F). Metafile blips (EMF/WMF/PICT) use a
/// different, larger header and are not raster images; they are skipped.
///
/// Every length is validated against the remaining buffer before slicing,
/// so a hostile `recLen` can only shrink the walk (skip a record or stop
/// early), never over-read or allocate unboundedly.
fn extract_pictures_from_stream(
    data: &[u8],
    slide_numbers: &std::collections::HashMap<u32, u32>,
    warnings: &mut Vec<ProcessingWarning>,
) -> Vec<ExtractedImage> {
    let mut images = Vec::new();
    let mut pos = 0usize;
    let mut image_index: u32 = 0;

    while pos + 8 <= data.len() {
        let rec_ver_instance = u16::from_le_bytes([data[pos], data[pos + 1]]);
        // recInstance occupies the upper 12 bits of the packed 16-bit field
        // (recVer, the low 4 bits, is checked nowhere here -- MS-ODRAW
        // requires it to be 0 for blips, but a non-zero value doesn't change
        // where the UID/tag/data fields are).
        let rec_instance = rec_ver_instance >> 4;
        let rec_type = u16::from_le_bytes([data[pos + 2], data[pos + 3]]);
        let rec_len = u32::from_le_bytes([data[pos + 4], data[pos + 5], data[pos + 6], data[pos + 7]]) as usize;

        let remaining = data.len() - (pos + 8);
        if rec_len > remaining {
            crate::core::diagnostics::push_warning(
                warnings,
                PPT_WARNING_SOURCE,
                "Pictures stream ended with a truncated record; the remaining embedded images were not extracted",
            );
            break;
        }

        let content_start = pos + 8;
        let content_end = content_start + rec_len;

        let format: Option<Cow<'static, str>> = match rec_type {
            RT_BLIP_JPEG | RT_BLIP_JPEG_ALT => Some(Cow::Borrowed("jpeg")),
            RT_BLIP_PNG => Some(Cow::Borrowed("png")),
            RT_BLIP_DIB => Some(Cow::Borrowed("dib")),
            _ => None,
        };

        if let Some(format) = format {
            // One `rgbUid` (16 bytes) + `tag` (1 byte) = 17-byte header, or
            // two `rgbUid`s + `tag` = 33 bytes; per MS-ODRAW 2.2.27-2.2.29
            // the low bit of `recInstance` is what distinguishes the two
            // UID counts for every raster blip type (e.g. JPEG 0x46A vs
            // 0x46B, PNG 0x6E0 vs 0x6E1, DIB 0x7A8 vs 0x7A9).
            let header_len = if rec_instance & 0x1 == 1 { 33 } else { 17 };

            if rec_len < header_len {
                crate::core::diagnostics::push_warning(
                    warnings,
                    PPT_WARNING_SOURCE,
                    format!(
                        "Blip record at offset {pos} (recLen={rec_len}) is shorter than its UID header \
                         ({header_len} bytes); skipped"
                    ),
                );
                pos = content_end;
                continue;
            }

            let picture_len = rec_len - header_len;
            if picture_len == 0 {
                pos = content_end;
                continue;
            }

            if picture_len > MAX_PICTURE_SIZE {
                crate::core::diagnostics::push_warning(
                    warnings,
                    PPT_WARNING_SOURCE,
                    format!(
                        "Embedded picture at offset {pos} ({picture_len} bytes) exceeds the \
                         {MAX_PICTURE_SIZE}-byte size cap and was skipped"
                    ),
                );
                pos = content_end;
                continue;
            }

            let picture_start = content_start + header_len;
            let picture_bytes = &data[picture_start..content_end];

            images.push(ExtractedImage {
                data: Bytes::copy_from_slice(picture_bytes),
                format,
                image_index,
                // `foDelay` in the BSE names this record's own start offset, so `pos` is the
                // key the drawing refers to it by (#1620). ~keep
                page_number: u32::try_from(pos)
                    .ok()
                    .and_then(|offset| slide_numbers.get(&offset))
                    .copied(),
                width: None,
                height: None,
                colorspace: None,
                bits_per_component: None,
                is_mask: false,
                description: None,
                ocr_result: None,
                bounding_box: None,
                source_path: None,
                image_kind: None,
                kind_confidence: None,
                cluster_id: None,
                caption: None,
                qr_codes: None,
                data_base64: None,
            });
            image_index += 1;
        }

        pos = content_end;
    }

    images
}

/// Clean PPT text: replace control characters and normalize whitespace.
fn clean_ppt_text(text: &str) -> String {
    let mut result = String::with_capacity(text.len());

    for c in text.chars() {
        match c {
            '\r' => result.push('\n'),
            '\x0B' => result.push('\n'),
            c if c < '\x20' && c != '\n' && c != '\t' => {}
            _ => result.push(c),
        }
    }

    let cleaned = result
        .lines()
        .map(|line| line.trim_end())
        .collect::<Vec<_>>()
        .join("\n");

    let trimmed = cleaned.trim();
    if trimmed.chars().all(|c| c == '*' || c == '\n' || c.is_whitespace()) {
        return String::new();
    }

    cleaned
}

/// Convert CP1252 byte to Unicode char.
fn cp1252_to_char(b: u8) -> char {
    match b {
        0x80 => '\u{20AC}',
        0x82 => '\u{201A}',
        0x83 => '\u{0192}',
        0x84 => '\u{201E}',
        0x85 => '\u{2026}',
        0x86 => '\u{2020}',
        0x87 => '\u{2021}',
        0x88 => '\u{02C6}',
        0x89 => '\u{2030}',
        0x8A => '\u{0160}',
        0x8B => '\u{2039}',
        0x8C => '\u{0152}',
        0x8E => '\u{017D}',
        0x91 => '\u{2018}',
        0x92 => '\u{2019}',
        0x93 => '\u{201C}',
        0x94 => '\u{201D}',
        0x95 => '\u{2022}',
        0x96 => '\u{2013}',
        0x97 => '\u{2014}',
        0x98 => '\u{02DC}',
        0x99 => '\u{2122}',
        0x9A => '\u{0161}',
        0x9B => '\u{203A}',
        0x9C => '\u{0153}',
        0x9E => '\u{017E}',
        0x9F => '\u{0178}',
        b => b as char,
    }
}

/// Read a named stream from the CFB compound file.
fn read_stream(comp: &mut cfb::CompoundFile<Cursor<&[u8]>>, name: &str) -> Result<Vec<u8>> {
    use std::io::Read;
    let mut stream = comp
        .open_stream(name)
        .map_err(|e| XbergError::parsing(format!("Failed to open stream '{name}': {e}")))?;
    let mut data = Vec::new();
    stream
        .read_to_end(&mut data)
        .map_err(|e| XbergError::parsing(format!("Failed to read stream '{name}': {e}")))?;
    Ok(data)
}

/// Extract metadata from OLE summary information streams.
fn extract_ppt_metadata(comp: &mut cfb::CompoundFile<Cursor<&[u8]>>) -> PptMetadata {
    let mut meta = PptMetadata::default();

    if let Ok(data) = read_stream(comp, "/\x05SummaryInformation") {
        parse_summary_info(&data, &mut meta);
    }

    meta
}

/// Parse OLE SummaryInformation for PPT metadata.
fn parse_summary_info(data: &[u8], meta: &mut PptMetadata) {
    if data.len() < 48 {
        return;
    }

    let set_offset = u32::from_le_bytes([data[44], data[45], data[46], data[47]]) as usize;

    if set_offset + 8 > data.len() {
        return;
    }

    let num_props = u32::from_le_bytes([
        data[set_offset + 4],
        data[set_offset + 5],
        data[set_offset + 6],
        data[set_offset + 7],
    ]) as usize;

    let props_start = set_offset + 8;

    for i in 0..num_props {
        let entry_offset = props_start + i * 8;
        if entry_offset + 8 > data.len() {
            break;
        }

        let prop_id = u32::from_le_bytes([
            data[entry_offset],
            data[entry_offset + 1],
            data[entry_offset + 2],
            data[entry_offset + 3],
        ]);
        let prop_offset = u32::from_le_bytes([
            data[entry_offset + 4],
            data[entry_offset + 5],
            data[entry_offset + 6],
            data[entry_offset + 7],
        ]) as usize;

        let abs_offset = set_offset + prop_offset;
        if abs_offset + 8 > data.len() {
            continue;
        }

        if let Some(value) = read_property_value(data, abs_offset) {
            match prop_id {
                2 => meta.title = Some(value),
                3 => meta.subject = Some(value),
                4 => meta.author = Some(value),
                8 => meta.last_author = Some(value),
                _ => {}
            }
        }
    }
}

/// Read a property value from an OLE property entry.
fn read_property_value(data: &[u8], offset: usize) -> Option<String> {
    if offset + 8 > data.len() {
        return None;
    }

    let vt_type = u32::from_le_bytes([data[offset], data[offset + 1], data[offset + 2], data[offset + 3]]);

    match vt_type {
        30 => {
            let len =
                u32::from_le_bytes([data[offset + 4], data[offset + 5], data[offset + 6], data[offset + 7]]) as usize;
            if len == 0 || offset + 8 + len > data.len() {
                return None;
            }
            let bytes = &data[offset + 8..offset + 8 + len];
            let trimmed = bytes.iter().take_while(|&&b| b != 0).copied().collect::<Vec<_>>();
            Some(String::from_utf8_lossy(&trimmed).to_string())
        }
        31 => {
            let len =
                u32::from_le_bytes([data[offset + 4], data[offset + 5], data[offset + 6], data[offset + 7]]) as usize;
            if len == 0 || offset + 8 + len * 2 > data.len() {
                return None;
            }
            let bytes = &data[offset + 8..offset + 8 + len * 2];
            let chars: Vec<u16> = bytes
                .chunks_exact(2)
                .map(|c| u16::from_le_bytes([c[0], c[1]]))
                .take_while(|&c| c != 0)
                .collect();
            Some(String::from_utf16_lossy(&chars))
        }
        _ => None,
    }
}

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

    #[test]
    fn test_clean_ppt_text() {
        assert_eq!(clean_ppt_text("Hello\rWorld"), "Hello\nWorld");
        assert_eq!(clean_ppt_text("A\x0BB"), "A\nB");
    }

    #[test]
    fn test_cp1252_to_char() {
        assert_eq!(cp1252_to_char(b'A'), 'A');
        assert_eq!(cp1252_to_char(0x80), '\u{20AC}');
    }

    #[test]
    fn test_extract_ppt_real_file() {
        let test_file = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test_documents/ppt/simple.ppt");
        if !test_file.exists() {
            return;
        }
        let content = std::fs::read(&test_file).expect("Failed to read test PPT");
        let result = extract_ppt_text(&content).expect("Failed to extract PPT text");
        assert!(!result.text.is_empty(), "PPT extraction should produce text");
    }

    #[test]
    fn test_extract_ppt_invalid_data() {
        let result = extract_ppt_text(b"not a ppt file");
        assert!(result.is_err());
    }

    /// #87 regression: `test_documents/ppt/simple.ppt` has exactly two
    /// top-level `Slide` (0x03EE) containers and three `SlideListWithText`
    /// (0x0FF0) containers holding only outline-view `SlidePersistAtom`
    /// entries. Segmenting on `SlideListWithText` collapsed all real slide
    /// text into a single trailing blob and reported the wrong slide count.
    #[test]
    fn test_extract_ppt_real_file_reports_two_slides() {
        let test_file = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../test_documents/ppt/simple.ppt");
        if !test_file.exists() {
            return;
        }
        let content = std::fs::read(&test_file).expect("Failed to read test PPT");
        let result = extract_ppt_text(&content).expect("Failed to extract PPT text");
        assert_eq!(result.slide_count, 2, "simple.ppt has exactly two Slide containers");
    }

    /// Build one PowerPoint record header (8 bytes: recVerInstance, recType, recLen).
    fn record_header(rec_ver_instance: u16, rec_type: u16, rec_len: u32) -> Vec<u8> {
        let mut buf = Vec::with_capacity(8);
        buf.extend_from_slice(&rec_ver_instance.to_le_bytes());
        buf.extend_from_slice(&rec_type.to_le_bytes());
        buf.extend_from_slice(&rec_len.to_le_bytes());
        buf
    }

    /// Build a container record (recVer nibble = 0xF) wrapping `children`.
    fn container(rec_type: u16, children: &[u8]) -> Vec<u8> {
        let mut buf = record_header(0x000F, rec_type, children.len() as u32);
        buf.extend_from_slice(children);
        buf
    }

    /// Build a `TextCharsAtom` (UTF-16LE) record for `text`.
    fn text_chars_atom(text: &str) -> Vec<u8> {
        let utf16: Vec<u8> = text.encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
        let mut buf = record_header(0x0000, RT_TEXT_CHARS_ATOM, utf16.len() as u32);
        buf.extend_from_slice(&utf16);
        buf
    }

    /// Build a `SlidePersistAtom` naming `persist_id`. Only the leading `persistIdRef`
    /// matters to the reader; the remaining 16 bytes are the documented tail.
    fn slide_persist_atom(persist_id: u32) -> Vec<u8> {
        let mut buf = record_header(0x0000, RT_SLIDE_PERSIST_ATOM, 20);
        buf.extend_from_slice(&persist_id.to_le_bytes());
        buf.extend_from_slice(&[0u8; 16]);
        buf
    }

    /// Build a `PersistDirectoryAtom` holding one single-id entry per `(id, offset)` pair.
    fn persist_directory(entries: &[(u32, u32)]) -> Vec<u8> {
        let mut body = Vec::new();
        for (id, offset) in entries {
            body.extend_from_slice(&((1u32 << PERSIST_COUNT_SHIFT) | (id & PERSIST_ID_MASK)).to_le_bytes());
            body.extend_from_slice(&offset.to_le_bytes());
        }
        let mut buf = record_header(0x0000, RT_PERSIST_DIRECTORY_ATOM, body.len() as u32);
        buf.extend_from_slice(&body);
        buf
    }

    /// Build a `UserEditAtom`. `offset_last_edit` is 0 for the first save.
    fn user_edit_atom(offset_last_edit: u32, offset_persist_directory: u32) -> Vec<u8> {
        let mut buf = record_header(0x0000, RT_USER_EDIT_ATOM, 28);
        buf.extend_from_slice(&1u32.to_le_bytes()); // lastSlideIdRef
        buf.extend_from_slice(&[0u8; 4]); // version / minorVersion / majorVersion
        buf.extend_from_slice(&offset_last_edit.to_le_bytes());
        buf.extend_from_slice(&offset_persist_directory.to_le_bytes());
        buf.extend_from_slice(&[0u8; 12]); // docPersistIdRef, persistIdSeed, lastView, unused
        buf
    }

    /// Build a `Current User` stream whose `CurrentUserAtom` points at `offset_to_current_edit`.
    fn current_user_stream(offset_to_current_edit: u32) -> Vec<u8> {
        let mut buf = record_header(0x0000, 0x0FF6, 0x14);
        buf.extend_from_slice(&0x14u32.to_le_bytes()); // size
        buf.extend_from_slice(&0xE391_C05Fu32.to_le_bytes()); // headerToken
        buf.extend_from_slice(&offset_to_current_edit.to_le_bytes());
        buf.extend_from_slice(&[0u8; 8]);
        buf
    }

    /// GH#1614: a `.ppt` stream is append-only across saves, so a superseded copy of a
    /// slide is still present in the bytes. Walking the stream counts it as a slide of the
    /// presentation; the live persist directory does not name it.
    #[test]
    fn a_superseded_slide_revision_is_not_extracted_as_a_slide() {
        let stale = container(RT_SLIDE, &text_chars_atom("stale revision"));
        let live_one = container(RT_SLIDE, &text_chars_atom("first slide"));
        let live_two = container(RT_SLIDE, &text_chars_atom("second slide"));

        let mut data = Vec::new();
        let stale_offset = data.len() as u32;
        data.extend_from_slice(&stale);
        let one_offset = data.len() as u32;
        data.extend_from_slice(&live_one);
        let two_offset = data.len() as u32;
        data.extend_from_slice(&live_two);

        let slide_list = container(
            RT_SLIDE_LIST_WITH_TEXT,
            &[slide_persist_atom(1), slide_persist_atom(2)].concat(),
        );
        data.extend_from_slice(&slide_list);

        // Older save: persist id 1 pointed at the stale copy. Newer save: it points at the
        // live one, and adds id 2.
        let old_dir_offset = data.len() as u32;
        data.extend_from_slice(&persist_directory(&[(1, stale_offset)]));
        let new_dir_offset = data.len() as u32;
        data.extend_from_slice(&persist_directory(&[(1, one_offset), (2, two_offset)]));

        let old_edit_offset = data.len() as u32;
        data.extend_from_slice(&user_edit_atom(0, old_dir_offset));
        let new_edit_offset = data.len() as u32;
        data.extend_from_slice(&user_edit_atom(old_edit_offset, new_dir_offset));

        let live =
            live_slide_offsets(&data, &current_user_stream(new_edit_offset)).expect("the persist chain must resolve");
        assert_eq!(
            live,
            vec![one_offset as usize, two_offset as usize],
            "the stale revision's offset must not appear in the live slide list"
        );

        let mut warnings = Vec::new();
        let (slides, _, _) = extract_texts_from_records(&data, false, Some(&live), &mut warnings)
            .expect("record parsing should succeed");

        assert_eq!(slides.len(), 2, "three Slide containers, two live slides");
        assert_eq!(slides[0].text, "first slide");
        assert_eq!(slides[1].text, "second slide");
        assert!(
            !slides.iter().any(|slide| slide.text.contains("stale")),
            "a superseded revision must not reach the output"
        );

        // The fixture reproduces the defect, rather than merely being consistent with the
        // fix: walked without the live list -- which is what this extractor did for every
        // deck -- the stale revision is extracted and numbered as slide 1. ~keep
        let mut stream_order_warnings = Vec::new();
        let (stream_order_slides, _, _) = extract_texts_from_records(&data, false, None, &mut stream_order_warnings)
            .expect("record parsing should succeed");
        assert_eq!(
            stream_order_slides.len(),
            3,
            "stream order counts the superseded revision"
        );
        assert_eq!(stream_order_slides[0].text, "stale revision");
    }

    /// GH#1614, the other half: `SlideListWithText` states the presentation order, which
    /// need not be the byte order the saves left the containers in.
    #[test]
    fn slides_are_numbered_by_presentation_order_not_stream_order() {
        let first_in_stream = container(RT_SLIDE, &text_chars_atom("appears second"));
        let second_in_stream = container(RT_SLIDE, &text_chars_atom("appears first"));

        let mut data = Vec::new();
        let stream_a = data.len() as u32;
        data.extend_from_slice(&first_in_stream);
        let stream_b = data.len() as u32;
        data.extend_from_slice(&second_in_stream);

        // Persist id 1 is the deck's first slide and lives LATER in the stream.
        let slide_list = container(
            RT_SLIDE_LIST_WITH_TEXT,
            &[slide_persist_atom(1), slide_persist_atom(2)].concat(),
        );
        data.extend_from_slice(&slide_list);

        let dir_offset = data.len() as u32;
        data.extend_from_slice(&persist_directory(&[(1, stream_b), (2, stream_a)]));
        let edit_offset = data.len() as u32;
        data.extend_from_slice(&user_edit_atom(0, dir_offset));

        let live =
            live_slide_offsets(&data, &current_user_stream(edit_offset)).expect("the persist chain must resolve");
        assert_eq!(live, vec![stream_b as usize, stream_a as usize]);

        let mut warnings = Vec::new();
        let (slides, _, _) = extract_texts_from_records(&data, false, Some(&live), &mut warnings)
            .expect("record parsing should succeed");

        assert_eq!(
            slides.iter().map(|s| (s.number, s.text.as_str())).collect::<Vec<_>>(),
            vec![(1, "appears first"), (2, "appears second")],
            "slide numbers and order come from the slide list, not the byte order"
        );
    }

    /// A deck whose chain cannot be read must keep the stream-order behaviour this
    /// extractor had before, rather than losing slides to a partial answer.
    #[test]
    fn an_unreadable_persist_chain_falls_back_to_stream_order() {
        let mut data = Vec::new();
        data.extend_from_slice(&container(RT_SLIDE, &text_chars_atom("one")));
        data.extend_from_slice(&container(RT_SLIDE, &text_chars_atom("two")));

        assert!(
            live_slide_offsets(&data, &[]).is_none(),
            "an empty Current User stream resolves nothing"
        );
        assert!(
            live_slide_offsets(&data, &current_user_stream(9_999)).is_none(),
            "an offsetToCurrentEdit past the end of the stream resolves nothing"
        );

        let mut warnings = Vec::new();
        let (slides, _, _) =
            extract_texts_from_records(&data, false, None, &mut warnings).expect("record parsing should succeed");
        assert_eq!(slides.len(), 2, "stream order still yields both slides");
    }

    /// #87: `SlideListWithText` (0x0FF0) is a per-document container of
    /// `SlidePersistAtom` outline-view entries -- it does not occur once per
    /// slide, and (as in real files) commonly holds no text of its own. The
    /// actual per-slide text lives in each `Slide` (0x03EE) container.
    /// Segmenting on `SlideListWithText` merges every slide's text into a
    /// single blob attributed to the wrong slide count; segmenting on
    /// `Slide` keeps each slide's text separate.
    #[test]
    fn test_extract_texts_segments_on_slide_not_slide_list_with_text() {
        const RT_SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0;
        const RT_SLIDE_PERSIST_ATOM: u16 = 0x03F3;

        // A SlideListWithText container holding only SlidePersistAtom entries
        // (no text), exactly as real files lay it out -- this used to be
        // mistaken for a slide boundary.
        let slide_persist_atom = record_header(0x0000, RT_SLIDE_PERSIST_ATOM, 0);
        let bogus_slwt = container(RT_SLIDE_LIST_WITH_TEXT, &slide_persist_atom);

        let slide1 = container(RT_SLIDE, &text_chars_atom("Slide One"));
        let slide2 = container(RT_SLIDE, &text_chars_atom("Slide Two"));

        let mut data = Vec::new();
        data.extend_from_slice(&bogus_slwt);
        data.extend_from_slice(&slide1);
        data.extend_from_slice(&slide2);

        let mut warnings = Vec::new();
        let (slides, loose_texts, notes) =
            extract_texts_from_records(&data, false, None, &mut warnings).expect("record parsing should succeed");

        assert_eq!(
            slides.len(),
            2,
            "each Slide container is one slide, not each SlideListWithText"
        );
        assert_eq!(slides[0].number, 1);
        assert_eq!(slides[0].text, "Slide One");
        assert_eq!(slides[1].number, 2);
        assert_eq!(slides[1].text, "Slide Two");
        assert!(loose_texts.is_empty());
        assert!(notes.is_empty());
        assert!(warnings.is_empty(), "well-formed records should not warn: {warnings:?}");
    }

    /// xberg-io/xberg#1612: a legacy deck keeps a slide's title in the document-level
    /// outline collection (`SlideListWithText`) and only the body in the slide's own drawing.
    /// The walk collected text from `Slide` containers only, so every such title landed in
    /// `loose_texts` -- which is discarded unless there are no slides at all -- and vanished.
    ///
    /// This does NOT re-segment on `SlideListWithText`; see
    /// `test_extract_texts_segments_on_slide_not_slide_list_with_text`, which still pins that.
    /// Slides are still one-per-`Slide`; the outline text is attributed to them by the order of
    /// the `SlidePersistAtom` entries that introduce each slide's outline records. ~keep
    #[test]
    fn test_extract_texts_recovers_titles_from_slide_list_with_text() {
        const RT_SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0;
        const RT_SLIDE_PERSIST_ATOM: u16 = 0x03F3;

        let mut outline = Vec::new();
        outline.extend_from_slice(&record_header(0x0000, RT_SLIDE_PERSIST_ATOM, 0));
        outline.extend_from_slice(&text_chars_atom("Search strategy development"));
        outline.extend_from_slice(&record_header(0x0000, RT_SLIDE_PERSIST_ATOM, 0));
        outline.extend_from_slice(&text_chars_atom("Results and discussion"));
        let slwt = container(RT_SLIDE_LIST_WITH_TEXT, &outline);

        let slide1 = container(RT_SLIDE, &text_chars_atom("=> FILE HCAPLUS"));
        let slide2 = container(RT_SLIDE, &text_chars_atom("=> DISPLAY L1"));

        let mut data = Vec::new();
        data.extend_from_slice(&slwt);
        data.extend_from_slice(&slide1);
        data.extend_from_slice(&slide2);

        let mut warnings = Vec::new();
        let (slides, loose_texts, notes) =
            extract_texts_from_records(&data, false, None, &mut warnings).expect("record parsing should succeed");

        assert_eq!(slides.len(), 2, "still one slide per Slide container");
        assert_eq!(slides[0].number, 1);
        assert_eq!(slides[0].text, "Search strategy development\n=> FILE HCAPLUS");
        assert_eq!(slides[1].number, 2);
        assert_eq!(slides[1].text, "Results and discussion\n=> DISPLAY L1");
        assert!(
            loose_texts.is_empty(),
            "outline text belongs to a slide, not to loose text"
        );
        assert!(notes.is_empty());
        assert!(warnings.is_empty(), "well-formed records should not warn: {warnings:?}");
    }

    /// A title that is *also* drawn on the slide canvas must appear once, not twice: the
    /// reporter noted that decks where the title is drawn are exactly the ones whose titles
    /// already survived, so recovering the outline copy must not double them. ~keep
    #[test]
    fn test_outline_title_already_drawn_on_the_slide_is_not_duplicated() {
        const RT_SLIDE_LIST_WITH_TEXT: u16 = 0x0FF0;
        const RT_SLIDE_PERSIST_ATOM: u16 = 0x03F3;

        let mut outline = Vec::new();
        outline.extend_from_slice(&record_header(0x0000, RT_SLIDE_PERSIST_ATOM, 0));
        outline.extend_from_slice(&text_chars_atom("Title Slide"));
        let slwt = container(RT_SLIDE_LIST_WITH_TEXT, &outline);

        let mut slide_children = Vec::new();
        slide_children.extend_from_slice(&text_chars_atom("Title Slide"));
        slide_children.extend_from_slice(&text_chars_atom("With a subtitle"));
        let slide1 = container(RT_SLIDE, &slide_children);

        let mut data = Vec::new();
        data.extend_from_slice(&slwt);
        data.extend_from_slice(&slide1);

        let mut warnings = Vec::new();
        let (slides, _loose, _notes) =
            extract_texts_from_records(&data, false, None, &mut warnings).expect("record parsing should succeed");

        assert_eq!(slides.len(), 1);
        assert_eq!(slides[0].text, "Title Slide\nWith a subtitle");
    }

    /// A `Notes` container's text must not bleed into the slide that follows
    /// it once its own byte range has ended.
    #[test]
    fn test_extract_texts_closes_notes_range_before_next_slide() {
        let notes = container(RT_NOTES, &text_chars_atom("Speaker notes"));
        let slide1 = container(RT_SLIDE, &text_chars_atom("Slide One"));

        let mut data = Vec::new();
        data.extend_from_slice(&notes);
        data.extend_from_slice(&slide1);

        let mut warnings = Vec::new();
        let (slides, loose_texts, speaker_notes) =
            extract_texts_from_records(&data, false, None, &mut warnings).expect("record parsing should succeed");

        assert_eq!(slides.len(), 1);
        assert_eq!(slides[0].number, 1);
        assert_eq!(slides[0].text, "Slide One");
        assert!(loose_texts.is_empty());
        assert_eq!(speaker_notes, vec!["Speaker notes".to_string()]);
    }

    /// #1418: a slide's number must come from its position among `RT_SLIDE`
    /// containers, not from the position of a text block after joining and
    /// re-splitting on `"\n\n"`. A slide with no text atoms must still get a
    /// number instead of vanishing and shifting every later slide down.
    #[test]
    fn should_number_slides_by_persist_order_when_a_middle_slide_has_no_text() {
        let slide1 = container(RT_SLIDE, &text_chars_atom("Slide One"));
        let slide2 = container(RT_SLIDE, &[]); // no text atoms at all
        let slide3 = container(RT_SLIDE, &text_chars_atom("Slide Three"));

        let mut data = Vec::new();
        data.extend_from_slice(&slide1);
        data.extend_from_slice(&slide2);
        data.extend_from_slice(&slide3);

        let mut warnings = Vec::new();
        let (slides, _loose_texts, _notes) =
            extract_texts_from_records(&data, false, None, &mut warnings).expect("record parsing should succeed");

        assert_eq!(
            slides.len(),
            3,
            "the empty middle slide must still produce a slide entry"
        );
        assert_eq!(slides[0].number, 1);
        assert_eq!(slides[0].text, "Slide One");
        assert_eq!(slides[1].number, 2);
        assert_eq!(
            slides[1].text, "",
            "a slide with no text atoms has empty text, not a missing entry"
        );
        assert_eq!(slides[2].number, 3);
        assert_eq!(slides[2].text, "Slide Three");
    }

    /// #1418 root-cause regression: a single slide whose own atoms, once
    /// joined by `clean_ppt_text`'s newline mapping, contain an internal
    /// `"\n\n"` (a text atom ending in a blank trailing paragraph, i.e. two
    /// consecutive `\r` paragraph marks) must still be reported as exactly
    /// one slide. The old algorithm re-split the whole document's text on
    /// `"\n\n"`, so this single slide's own text was itself indistinguishable
    /// from a slide boundary.
    #[test]
    fn should_keep_one_slide_entry_when_slide_text_contains_internal_blank_line() {
        let atom_with_trailing_blank_paragraph = text_chars_atom("Title\r\r");
        let atom_body = text_chars_atom("Body");
        let mut slide_children = Vec::new();
        slide_children.extend_from_slice(&atom_with_trailing_blank_paragraph);
        slide_children.extend_from_slice(&atom_body);
        let slide1 = container(RT_SLIDE, &slide_children);

        let mut data = Vec::new();
        data.extend_from_slice(&slide1);

        let mut warnings = Vec::new();
        let (slides, _loose_texts, _notes) =
            extract_texts_from_records(&data, false, None, &mut warnings).expect("record parsing should succeed");

        assert_eq!(
            slides.len(),
            1,
            "one Slide container is one slide, however its joined text looks"
        );
        assert_eq!(slides[0].number, 1);
        assert_eq!(
            slides[0].text, "Title\n\nBody",
            "the slide's own text legitimately contains an internal blank line"
        );
    }

    /// Build a raster `OfficeArtBlip` record with a single 16-byte UID
    /// (MS-ODRAW 2.2.27-2.2.29 "one UID" layout: `rgbUid1(16) + tag(1) +
    /// BLIPFileData`). `rec_instance` must be even per spec (e.g. JPEG
    /// 0x46A, PNG 0x6E0, DIB 0x7A8).
    fn blip_record_one_uid(rec_instance: u16, rec_type: u16, picture_bytes: &[u8]) -> Vec<u8> {
        assert_eq!(rec_instance & 0x1, 0, "one-UID recInstance must be even");
        let rec_ver_instance = rec_instance << 4;
        let rec_len = (17 + picture_bytes.len()) as u32;
        let mut buf = record_header(rec_ver_instance, rec_type, rec_len);
        buf.extend_from_slice(&[0u8; 16]);
        buf.push(0xFF);
        buf.extend_from_slice(picture_bytes);
        buf
    }

    /// Build a raster `OfficeArtBlip` record with two 16-byte UIDs
    /// ("two UID" layout: `rgbUid1(16) + rgbUid2(16) + tag(1) +
    /// BLIPFileData`). `rec_instance` must be odd per spec (e.g. JPEG
    /// 0x46B, PNG 0x6E1, DIB 0x7A9).
    fn blip_record_two_uid(rec_instance: u16, rec_type: u16, picture_bytes: &[u8]) -> Vec<u8> {
        assert_eq!(rec_instance & 0x1, 1, "two-UID recInstance must be odd");
        let rec_ver_instance = rec_instance << 4;
        let rec_len = (33 + picture_bytes.len()) as u32;
        let mut buf = record_header(rec_ver_instance, rec_type, rec_len);
        buf.extend_from_slice(&[0u8; 32]);
        buf.push(0xFF);
        buf.extend_from_slice(picture_bytes);
        buf
    }

    #[test]
    fn should_extract_jpeg_bytes_when_pictures_stream_has_one_uid_jpeg_blip() {
        let picture = b"\xFF\xD8\xFFfake-jpeg-payload";
        let data = blip_record_one_uid(0x46A, RT_BLIP_JPEG, picture);

        let mut warnings = Vec::new();
        let images = extract_pictures_from_stream(&data, &Default::default(), &mut warnings);

        assert_eq!(images.len(), 1);
        assert_eq!(images[0].format, "jpeg");
        assert_eq!(images[0].image_index, 0);
        assert_eq!(&images[0].data[..], &picture[..]);
        assert!(warnings.is_empty());
    }

    #[test]
    fn should_extract_png_bytes_when_pictures_stream_has_two_uid_png_blip() {
        let picture = b"\x89PNG\r\n\x1a\nfake-png-payload";
        let data = blip_record_two_uid(0x6E1, RT_BLIP_PNG, picture);

        let mut warnings = Vec::new();
        let images = extract_pictures_from_stream(&data, &Default::default(), &mut warnings);

        assert_eq!(images.len(), 1);
        assert_eq!(images[0].format, "png");
        assert_eq!(&images[0].data[..], &picture[..]);
        assert!(warnings.is_empty());
    }

    #[test]
    fn should_extract_dib_bytes_and_tag_format_dib_when_pictures_stream_has_dib_blip() {
        let picture = b"fake-dib-bitmap-payload";
        let data = blip_record_one_uid(0x7A8, RT_BLIP_DIB, picture);

        let mut warnings = Vec::new();
        let images = extract_pictures_from_stream(&data, &Default::default(), &mut warnings);

        assert_eq!(images.len(), 1);
        assert_eq!(images[0].format, "dib");
        assert_eq!(&images[0].data[..], &picture[..]);
    }

    #[test]
    fn should_assign_sequential_image_index_when_pictures_stream_has_multiple_blips() {
        let jpeg = blip_record_one_uid(0x46A, RT_BLIP_JPEG, b"jpeg-one");
        let png = blip_record_one_uid(0x6E0, RT_BLIP_PNG, b"png-two");

        let mut data = Vec::new();
        data.extend_from_slice(&jpeg);
        data.extend_from_slice(&png);

        let mut warnings = Vec::new();
        let images = extract_pictures_from_stream(&data, &Default::default(), &mut warnings);

        assert_eq!(images.len(), 2);
        assert_eq!(images[0].image_index, 0);
        assert_eq!(images[0].format, "jpeg");
        assert_eq!(images[1].image_index, 1);
        assert_eq!(images[1].format, "png");
    }

    #[test]
    fn should_skip_non_blip_records_when_walking_pictures_stream() {
        // An arbitrary non-blip OfficeArt record (a group shape record,
        // 0xF003) sitting between two real blips must not be mistaken for a
        // picture and must not stop the walk.
        const RT_UNRELATED: u16 = 0xF003;
        let unrelated = record_header(0x0000, RT_UNRELATED, 4)
            .into_iter()
            .chain([1, 2, 3, 4])
            .collect::<Vec<u8>>();
        let jpeg = blip_record_one_uid(0x46A, RT_BLIP_JPEG, b"real-jpeg");

        let mut data = Vec::new();
        data.extend_from_slice(&unrelated);
        data.extend_from_slice(&jpeg);

        let mut warnings = Vec::new();
        let images = extract_pictures_from_stream(&data, &Default::default(), &mut warnings);

        assert_eq!(images.len(), 1);
        assert_eq!(images[0].format, "jpeg");
    }

    /// Safety: a record whose declared `recLen` overruns the remaining
    /// buffer must never panic or over-read -- the walk stops and a
    /// diagnostic warning is recorded instead.
    #[test]
    fn should_stop_without_panicking_when_blip_declares_length_past_buffer_end() {
        let mut data = record_header(0x46A << 4, RT_BLIP_JPEG, u32::MAX);
        data.extend_from_slice(&[0u8; 4]); // far short of the declared recLen

        let mut warnings = Vec::new();
        let images = extract_pictures_from_stream(&data, &Default::default(), &mut warnings);

        assert!(images.is_empty());
        assert!(
            warnings.iter().any(|w| w.message.contains("truncated")),
            "expected a truncation warning, got: {warnings:?}"
        );
    }

    /// Safety: a blip record declaring fewer bytes than its own UID header
    /// requires must be skipped, not underflow-subtracted into a bogus
    /// picture length.
    #[test]
    fn should_skip_and_warn_when_blip_declared_length_is_shorter_than_uid_header() {
        // recLen = 5, far short of the 17-byte one-UID header.
        let data = record_header(0x46A << 4, RT_BLIP_JPEG, 5)
            .into_iter()
            .chain([0u8; 5])
            .collect::<Vec<u8>>();

        let mut warnings = Vec::new();
        let images = extract_pictures_from_stream(&data, &Default::default(), &mut warnings);

        assert!(images.is_empty());
        assert!(
            warnings
                .iter()
                .any(|w| w.message.contains("shorter than its UID header")),
            "expected a UID-header-too-short warning, got: {warnings:?}"
        );
    }

    #[test]
    fn should_return_no_images_when_pictures_stream_is_empty() {
        let mut warnings = Vec::new();
        let images = extract_pictures_from_stream(&[], &Default::default(), &mut warnings);
        assert!(images.is_empty());
        assert!(warnings.is_empty());
    }

    /// Build a minimal OLE/CFB container with a "PowerPoint Document" stream
    /// and, optionally, a "Pictures" stream, mirroring what a real `.ppt`
    /// looks like closely enough to drive `extract_ppt_text_with_options`
    /// end-to-end. `test_documents/ppt/simple.ppt` has a `Pictures` stream
    /// but it is empty (verified: 0 bytes), so this synthetic container is
    /// the only way to exercise the `/Pictures` read path with real blips.
    fn build_test_ppt_ole(ppt_document_stream: &[u8], pictures_stream: Option<&[u8]>) -> Vec<u8> {
        use std::io::Write;
        let cursor = Cursor::new(Vec::new());
        let mut comp = cfb::CompoundFile::create(cursor).expect("create in-memory OLE container");
        comp.create_stream("/PowerPoint Document")
            .expect("create PowerPoint Document stream")
            .write_all(ppt_document_stream)
            .expect("write PowerPoint Document stream");
        if let Some(pictures) = pictures_stream {
            comp.create_stream("/Pictures")
                .expect("create Pictures stream")
                .write_all(pictures)
                .expect("write Pictures stream");
        }
        comp.into_inner().into_inner()
    }

    #[test]
    fn should_populate_images_when_pictures_stream_has_a_blip_and_extract_images_is_true() {
        let ppt_stream = container(RT_SLIDE, &text_chars_atom("Slide One"));
        let picture = b"\xFF\xD8\xFFsynthetic-jpeg-bytes";
        let pictures_stream = blip_record_one_uid(0x46A, RT_BLIP_JPEG, picture);
        let content = build_test_ppt_ole(&ppt_stream, Some(&pictures_stream));

        let result =
            extract_ppt_text_with_options(&content, false, true).expect("synthetic OLE container should parse");

        assert_eq!(result.images.len(), 1);
        assert_eq!(result.images[0].format, "jpeg");
        assert_eq!(result.images[0].data.len(), picture.len());
        assert_eq!(&result.images[0].data[..], &picture[..]);
    }

    #[test]
    fn should_return_no_images_when_extract_images_is_false() {
        let ppt_stream = container(RT_SLIDE, &text_chars_atom("Slide One"));
        let pictures_stream = blip_record_one_uid(0x46A, RT_BLIP_JPEG, b"jpeg-bytes");
        let content = build_test_ppt_ole(&ppt_stream, Some(&pictures_stream));

        let result =
            extract_ppt_text_with_options(&content, false, false).expect("synthetic OLE container should parse");

        assert!(
            result.images.is_empty(),
            "extract_images=false must skip the Pictures stream entirely"
        );
    }

    #[test]
    fn should_return_no_images_when_pictures_stream_is_absent() {
        let ppt_stream = container(RT_SLIDE, &text_chars_atom("Slide One"));
        let content = build_test_ppt_ole(&ppt_stream, None);

        let result =
            extract_ppt_text_with_options(&content, false, true).expect("synthetic OLE container should parse");

        assert!(result.images.is_empty());
    }

    /// Build an `msofbtBSE` whose `foDelay` names `pictures_offset`. Only `foDelay` is
    /// read; the surrounding documented fields are present so offsets are realistic.
    fn bse_record(pictures_offset: u32) -> Vec<u8> {
        let mut content = Vec::new();
        content.extend_from_slice(&[0x06, 0x06]); // btWin32, btMacOS
        content.extend_from_slice(&[0u8; 16]); // rgbUid
        content.extend_from_slice(&[0u8; 2]); // tag
        content.extend_from_slice(&0u32.to_le_bytes()); // size
        content.extend_from_slice(&1u32.to_le_bytes()); // cRef
        content.extend_from_slice(&pictures_offset.to_le_bytes()); // foDelay
        content.extend_from_slice(&[0u8; 4]); // unused1..3, cbName
        let mut buf = record_header(0x0000, MSOFBT_BSE, content.len() as u32);
        buf.extend_from_slice(&content);
        buf
    }

    /// Build an `msofbtOPT` property table carrying one `pib` entry.
    fn opt_with_pib(pib: u32) -> Vec<u8> {
        let mut content = Vec::new();
        // `fBid` (bit 14) set, as a real picture shape writes it.
        content.extend_from_slice(&(MSO_PROPERTY_PIB | 0x4000).to_le_bytes());
        content.extend_from_slice(&pib.to_le_bytes());
        let mut buf = record_header(1 << 4, MSOFBT_OPT[0], content.len() as u32);
        buf.extend_from_slice(&content);
        buf
    }

    /// #1620: a picture's slide comes from the drawing that references it, not from the
    /// `Pictures` stream, which is in save order and names no slide at all.
    #[test]
    fn should_attribute_each_picture_to_the_slide_whose_drawing_references_it() {
        let first_picture = b"\xFF\xD8\xFFfirst-picture";
        let second_picture = b"\xFF\xD8\xFFsecond";
        let first_blip = blip_record_one_uid(0x46A, RT_BLIP_JPEG, first_picture);
        let second_blip = blip_record_one_uid(0x46A, RT_BLIP_JPEG, second_picture);
        let second_offset = first_blip.len() as u32;
        let mut pictures_stream = first_blip.clone();
        pictures_stream.extend_from_slice(&second_blip);

        // `pib` 1 -> the blip at 0, `pib` 2 -> the blip after it.
        let mut bstore = bse_record(0);
        bstore.extend_from_slice(&bse_record(second_offset));
        let drawing_group = container(0xF001, &bstore);

        // Slide 1 shows the *second* blip and slide 2 the first, so a passing test cannot
        // be explained by the stream order the walk would otherwise fall back to.
        let mut stream = drawing_group;
        stream.extend_from_slice(&container(RT_SLIDE, &opt_with_pib(2)));
        let mut slide_two = text_chars_atom("Slide Two");
        slide_two.extend_from_slice(&opt_with_pib(1));
        stream.extend_from_slice(&container(RT_SLIDE, &slide_two));

        let content = build_test_ppt_ole(&stream, Some(&pictures_stream));
        let result = extract_ppt_text_with_options(&content, false, true).expect("synthetic deck should parse");

        assert_eq!(result.images.len(), 2, "both blips must still be extracted");
        assert_eq!(&result.images[0].data[..], &first_picture[..]);
        assert_eq!(
            result.images[0].page_number,
            Some(2),
            "first blip is referenced by slide 2"
        );
        assert_eq!(&result.images[1].data[..], &second_picture[..]);
        assert_eq!(
            result.images[1].page_number,
            Some(1),
            "second blip is referenced by slide 1"
        );
    }

    /// #1620: a blip in `Pictures` that no live shape displays keeps the pre-fix
    /// behaviour -- still extracted, but attributed to no slide.
    #[test]
    fn should_leave_a_picture_no_shape_references_without_a_slide_number() {
        let picture = b"\xFF\xD8\xFForphan";
        let pictures_stream = blip_record_one_uid(0x46A, RT_BLIP_JPEG, picture);
        let mut stream = container(0xF001, &bse_record(0));
        stream.extend_from_slice(&container(RT_SLIDE, &text_chars_atom("Slide One")));

        let content = build_test_ppt_ole(&stream, Some(&pictures_stream));
        let result = extract_ppt_text_with_options(&content, false, true).expect("synthetic deck should parse");

        assert_eq!(result.images.len(), 1);
        assert_eq!(result.images[0].page_number, None);
    }

    /// #1620: a `pib` pointing past the end of the `BStoreContainer` is a corrupt deck,
    /// not a panic -- the picture simply resolves to no slide.
    #[test]
    fn should_ignore_a_blip_index_beyond_the_blip_store() {
        let picture = b"\xFF\xD8\xFFonly";
        let pictures_stream = blip_record_one_uid(0x46A, RT_BLIP_JPEG, picture);
        let mut stream = container(0xF001, &bse_record(0));
        stream.extend_from_slice(&container(RT_SLIDE, &opt_with_pib(99)));

        let content = build_test_ppt_ole(&stream, Some(&pictures_stream));
        let result = extract_ppt_text_with_options(&content, false, true).expect("synthetic deck should parse");

        assert_eq!(result.images.len(), 1);
        assert_eq!(result.images[0].page_number, None);
    }
}