xberg 1.2.6

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
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
//! 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.

mod embedded;
pub(crate) use embedded::extract_ppt_embedded_objects;

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).
pub(super) 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,
    /// The slide's title, read from the outline collection's own `TextHeaderAtom` (`Title` /
    /// `CenterTitle`) rather than guessed from `text`'s first line (xberg-io/xberg#1635).
    /// `None` when the file states no outline title for this slide -- a deck whose title is
    /// drawn on the canvas and never entered in the outline view still has one, just not
    /// here; the consumer's first-line fallback covers that case.
    pub title: Option<String>,
    /// This slide's speaker notes, resolved via `NotesAtom.slideIdRef` against the live
    /// `SlideListWithText` (xberg-io/xberg#1640) -- not by position among the deck's
    /// non-empty notes pages, which misattributes a note as soon as one slide in between
    /// has none. `None` when the slide has no notes, or the file cannot be read that way.
    pub notes: Option<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;
/// Byte offset of `SlidePersistAtom.slideId` within its 20-byte payload, past
/// `persistIdRef` (4), `flags` (4) and `numberTexts` (4) (MS-PPT 2.4.14). What
/// `NotesAtom.slideIdRef` names a notes page's slide by -- a different value than
/// `persistIdRef`, which only orders the persist directory (xberg-io/xberg#1640). ~keep
const SLIDE_PERSIST_ATOM_SLIDE_ID_OFFSET: usize = 12;
const RT_NOTES: u16 = 0x03F0;
/// Inside an [`RT_NOTES`] container, states which slide the notes page belongs to
/// (MS-PPT 2.5.7). ~keep
const RT_NOTES_ATOM: u16 = 0x03F1;
/// `NotesAtom.slideIdRef` sentinel meaning "this is the notes master", not a per-slide
/// notes page. Its placeholder text ("Click to edit Master text styles...") must never
/// reach `speaker_notes` (xberg-io/xberg#1640). ~keep
const NOTES_MASTER_SLIDE_ID_REF: u32 = 0x8000_0000;
/// Precedes a text atom inside [`RT_SLIDE_LIST_WITH_TEXT`] and types it (MS-PPT 2.13.33
/// `TextTypeEnum`); read here only to tell a slide's outline *title* apart from its outline
/// *body* (xberg-io/xberg#1635). ~keep
const RT_TEXT_HEADER_ATOM: u16 = 0x0F9F;
/// `TextHeaderAtom.textType == Title`. ~keep
const TEXT_TYPE_TITLE: u32 = 0;
/// `TextHeaderAtom.textType == CenterTitle` -- a title-slide's centred title placeholder.
/// `5` is `CenterBody` (body text, not a title); confirmed against Apache POI's
/// `TextHeaderAtom` constants, which the MS-PPT spec text alone does not make obvious. ~keep
const TEXT_TYPE_CENTER_TITLE: u32 = 6;

/// `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;
/// The deck's own top-level container, holding (among other things) the live
/// `SlideListWithText` (MS-PPT 2.4.1). A `.ppt` stream carries one of these per save;
/// `UserEditAtom.docPersistIdRef` names which one is current (xberg-io/xberg#1639). ~keep
const RT_DOCUMENT: u16 = 0x03E8;

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

/// Depth cap for [`slide_persist_ids_in_presentation_order`]'s descent into nested
/// containers. Real decks keep `SlideListWithText` a direct child of `DocumentContainer`;
/// this only stops a hostile self-nesting container from recursing without bound.
const MAX_SLIDE_LIST_SEARCH_DEPTH: usize = 16;

/// 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_ref(),
        &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"),
            title: None,
            notes: None,
        });
    }
    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_ref().map(|l| l.offsets.as_slice()));
                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`.
pub(super) 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]]))
}

/// The deck's live slides, resolved through the persist chain (#1614, #1639).
pub(super) struct LiveSlides {
    /// Live `Slide` container offsets, presentation order (#1614).
    pub(super) offsets: Vec<usize>,
    /// Absolute stream offset of the live `SlideListWithText` record header itself -- the
    /// only occurrence [`extract_texts_from_records`] may harvest outline text (titles
    /// included) from. An older save's list, or the master/notes lists sharing the same
    /// record type, must not be read as the presentation's outline (#1639). ~keep
    outline_record_offset: usize,
    /// `SlidePersistAtom.slideId` for each live slide, aligned by index with `offsets` --
    /// what `NotesAtom.slideIdRef` names a notes page's slide by (#1640).
    slide_ids: Vec<u32>,
    /// The merged persist directory (persist id -> stream offset, newest save wins), kept
    /// so other persist-referenced records -- an embedded object's `ExOleObjStg`, named by
    /// `ExOleObjAtom.persistIdRef` (GH#1660) -- resolve through the same chain. ~keep
    pub(super) persist: ahash::AHashMap<u32, usize>,
    /// Payload range `[start, end)` of the live `DocumentContainer` in the stream, so a
    /// document-level list (`ExObjList`) is read from the current save, not an older one. ~keep
    pub(super) document_payload: (usize, usize),
}

/// 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
///                                            .docPersistIdRef        ─▶ the live DocumentContainer
///
/// DocumentContainer (0x03E8) > 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. The slide list itself is
/// read from the **live** `DocumentContainer` -- resolved the same way, through
/// `docPersistIdRef` on the newest `UserEditAtom` -- not from the first `SlideListWithText`
/// the stream happens to contain, which is the oldest save's (#1639).
///
/// Returns `None` whenever the chain cannot be read in full -- absent `Current User`
/// stream, unparseable atom, offset out of range, an unresolvable `DocumentContainer`, 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
pub(super) fn live_slide_offsets(ppt_stream: &[u8], current_user_stream: &[u8]) -> Option<LiveSlides> {
    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 document_id: Option<u32> = None;
    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;
        // `docPersistIdRef`: only the FIRST (newest) edit's value matters -- it names the
        // live `DocumentContainer`, which carries the presentation's own slide list rather
        // than an earlier save's (#1639). ~keep
        document_id.get_or_insert(read_u32_le(ppt_stream, content + 16)?);

        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 document_offset = *persist.get(&document_id?)?;
    let document_header = ppt_stream.get(document_offset..document_offset.checked_add(8)?)?;
    if u16::from_le_bytes([document_header[2], document_header[3]]) != RT_DOCUMENT {
        return None;
    }
    let document_len = u32::from_le_bytes([
        document_header[4],
        document_header[5],
        document_header[6],
        document_header[7],
    ]) as usize;
    let document_content_start = document_offset.checked_add(8)?;
    let document_content_end = document_content_start.checked_add(document_len)?;
    let document_payload = ppt_stream.get(document_content_start..document_content_end)?;

    let (relative_outline_offset, entries) = slide_persist_ids_in_presentation_order(document_payload, 0)?;
    if entries.is_empty() {
        return None;
    }
    let outline_record_offset = document_content_start + relative_outline_offset;

    let offsets = entries
        .iter()
        .map(|&(persist_id, _)| {
            let offset = *persist.get(&persist_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::<Option<Vec<usize>>>()?;
    let slide_ids = entries.iter().map(|&(_, slide_id)| slide_id).collect();

    Some(LiveSlides {
        offsets,
        outline_record_offset,
        slide_ids,
        persist,
        document_payload: (document_content_start, document_content_end),
    })
}

/// 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 `container`'s own `SlideListWithText` (`recInstance` 0), in the
/// order the deck presents them, plus that record's own offset relative to `container`.
///
/// `container` is the **live** `DocumentContainer`'s payload, resolved by the caller
/// through the persist chain (#1639) -- so an older save's slide list elsewhere in the
/// stream is never seen. `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
///
/// A proper depth-first descent (not a linear walk that never returns to a sibling): a
/// `SlideListWithText` not found in one child container is looked for in the next.
///
/// Each entry is `(persistIdRef, slideId)`: `persistIdRef` resolves the `Slide` container's
/// stream offset through the persist directory; `slideId` is what `NotesAtom.slideIdRef`
/// names the slide by, and is a different value (xberg-io/xberg#1640).
fn slide_persist_ids_in_presentation_order(container: &[u8], depth: usize) -> Option<(usize, Vec<(u32, u32)>)> {
    if depth > MAX_SLIDE_LIST_SEARCH_DEPTH {
        return None;
    }
    let mut pos = 0usize;
    while pos + 8 <= container.len() {
        let ver_instance = u16::from_le_bytes([container[pos], container[pos + 1]]);
        let rec_type = u16::from_le_bytes([container[pos + 2], container[pos + 3]]);
        let rec_len = u32::from_le_bytes([
            container[pos + 4],
            container[pos + 5],
            container[pos + 6],
            container[pos + 7],
        ]) as usize;
        let content_start = pos + 8;
        let content_end = content_start.checked_add(rec_len)?;
        if content_end > container.len() {
            return None;
        }

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

        if (ver_instance & 0x000F) == 0x0F
            && let Some((relative, entries)) =
                slide_persist_ids_in_presentation_order(&container[content_start..content_end], depth + 1)
        {
            // `relative` is relative to the nested slice; translate it back into
            // `container`'s own coordinate space so the caller's offset stays meaningful.
            return Some((content_start + relative, entries));
        }

        pos = 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.
/// Push one outline atom's cleaned text into `outline_texts[index]`, and -- when
/// `text_type` names the slide's title (`Title` / `CenterTitle`) and no title has been
/// captured for this slide yet -- also into `outline_titles[index]` (#1635). The first
/// title-typed atom wins: an outline states a slide's title once.
fn record_outline_text(
    outline_texts: &mut [Vec<String>],
    outline_titles: &mut [Option<String>],
    index: usize,
    text_type: Option<u32>,
    cleaned: String,
) {
    if matches!(text_type, Some(TEXT_TYPE_TITLE | TEXT_TYPE_CENTER_TITLE)) && outline_titles[index].is_none() {
        outline_titles[index] = Some(cleaned.clone());
    }
    outline_texts[index].push(cleaned);
}

/// Commit one just-closed `RT_NOTES` container's accumulated text into `notes_by_slide`,
/// keyed by the slide it belongs to (xberg-io/xberg#1640).
///
/// The notes master (`slideIdRef == NOTES_MASTER_SLIDE_ID_REF`) is layout, not content, and
/// is dropped -- the same reason `RT_MAIN_MASTER` is skipped by default. With a resolved
/// persist chain, `current_notes_slide_id` is looked up in `slide_number_by_id`; a notes
/// page whose id names no live slide is a stale revision, like a `Slide` container the live
/// list does not name (#1614), and is dropped too. Without a resolved chain, notes fall back
/// to the deck's own encounter order via `next_positional_slide_number` -- the old, purely
/// positional behaviour, now at least skipping the master.
fn commit_notes(
    current_notes_texts: &mut Vec<String>,
    current_notes_slide_id: Option<u32>,
    slide_number_by_id: &ahash::AHashMap<u32, u32>,
    next_positional_slide_number: &mut u32,
    notes_by_slide: &mut std::collections::BTreeMap<u32, String>,
) {
    if current_notes_texts.is_empty() {
        return;
    }
    let notes_text = current_notes_texts.join("\n");
    current_notes_texts.clear();
    let trimmed = notes_text.trim();
    if trimmed.is_empty() || current_notes_slide_id == Some(NOTES_MASTER_SLIDE_ID_REF) {
        return;
    }
    let slide_number = if slide_number_by_id.is_empty() {
        let number = *next_positional_slide_number;
        *next_positional_slide_number += 1;
        Some(number)
    } else {
        current_notes_slide_id.and_then(|id| slide_number_by_id.get(&id).copied())
    };
    if let Some(number) = slide_number {
        notes_by_slide.insert(number, trimmed.to_string());
    }
}

fn extract_texts_from_records(
    data: &[u8],
    include_master_slides: bool,
    live: Option<&LiveSlides>,
    warnings: &mut Vec<ProcessingWarning>,
) -> Result<(Vec<PptSlideText>, Vec<String>, Vec<String>)> {
    let live_slides = live.map(|l| l.offsets.as_slice());
    // The only `SlideListWithText` occurrence outline text may be harvested from; `None`
    // means the persist chain did not resolve, in which case every occurrence is read, as
    // this extractor always did before #1639.
    let live_outline_offset = live.map(|l| l.outline_record_offset);
    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 in_notes = false;
    let mut notes_end: Option<usize> = None;
    let mut current_notes_texts: Vec<String> = Vec::new();
    // `NotesAtom.slideIdRef` of the notes container currently open; `None` until its
    // `NotesAtom` (0x03F1) is read (#1640).
    let mut current_notes_slide_id: Option<u32> = None;
    // Speaker notes, keyed by the slide number they belong to -- resolved from
    // `slideIdRef` when a persist chain is available, positional (skipping the master)
    // otherwise (xberg-io/xberg#1640).
    let mut notes_by_slide: std::collections::BTreeMap<u32, String> = std::collections::BTreeMap::new();
    let mut next_positional_slide_number: u32 = 1;
    let slide_number_by_id: ahash::AHashMap<u32, u32> = live
        .map(|l| {
            l.slide_ids
                .iter()
                .enumerate()
                .map(|(i, &id)| (id, i as u32 + 1))
                .collect()
        })
        .unwrap_or_default();
    // 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;
    // The outline's own title, one atom per slide, typed by the `TextHeaderAtom` that
    // precedes it (#1635) -- `None` where the file's outline states no title.
    let mut outline_titles: Vec<Option<String>> = Vec::new();
    // `TextHeaderAtom.textType` of the outline atom about to follow; reset after every text
    // atom so an untyped run never inherits a stale type from an earlier one. ~keep
    let mut outline_text_type: Option<u32> = 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"),
                title: None,
                notes: None,
            });
            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
        {
            commit_notes(
                &mut current_notes_texts,
                current_notes_slide_id,
                &slide_number_by_id,
                &mut next_positional_slide_number,
                &mut notes_by_slide,
            );
            current_notes_slide_id = None;
            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"),
                        title: None,
                        notes: None,
                    });
                    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 {
                    commit_notes(
                        &mut current_notes_texts,
                        current_notes_slide_id,
                        &slide_number_by_id,
                        &mut next_positional_slide_number,
                        &mut notes_by_slide,
                    );
                }
                in_notes = true;
                current_notes_slide_id = None;
                notes_end = Some(content_end);
                pos += 8;
                continue;
            }
            RT_NOTES_ATOM => {
                if in_notes && let Some(bytes) = data.get(content_start..content_start + 4) {
                    current_notes_slide_id = Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]));
                }
                pos = content_end;
                continue;
            }
            RT_MAIN_MASTER if !include_master_slides => {
                pos = content_end;
                continue;
            }
            RT_SLIDE_LIST_WITH_TEXT => {
                // Only the live document's own list (#1639); a stale save's, or the
                // master/notes lists sharing this record type, are skipped.
                if live_outline_offset.is_none_or(|offset| offset == pos) {
                    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());
                    outline_titles.resize(next + 1, None);
                }
                outline_text_type = None;
                pos = content_end;
                continue;
            }
            RT_TEXT_HEADER_ATOM => {
                if outline_slide_index.is_some()
                    && let Some(bytes) = data.get(content_start..content_start + 4)
                {
                    outline_text_type = Some(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]));
                }
                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).
                            record_outline_text(
                                &mut outline_texts,
                                &mut outline_titles,
                                index,
                                outline_text_type,
                                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);
                            }
                        }
                    }
                    outline_text_type = None;
                }
                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).
                            record_outline_text(
                                &mut outline_texts,
                                &mut outline_titles,
                                index,
                                outline_text_type,
                                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);
                            }
                        }
                    }
                    outline_text_type = None;
                }
                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"),
            title: None,
            notes: None,
        });
    }

    commit_notes(
        &mut current_notes_texts,
        current_notes_slide_id,
        &slide_number_by_id,
        &mut next_positional_slide_number,
        &mut notes_by_slide,
    );

    // 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;
        };
        // The file's own outline title (#1635), not the first-line guess the caller falls
        // back to when this is `None`.
        slide.title = outline_titles.get(index).cloned().flatten();
        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)
        };
    }

    // Every non-empty flat entry, in slide-number order -- kept for the metadata array
    // consumers already read (`PptExtractionResult::speaker_notes`); the per-slide
    // attachment below is what fixes the misattribution (#1640).
    let speaker_notes: Vec<String> = notes_by_slide.values().cloned().collect();
    for slide in &mut slides {
        slide.notes = notes_by_slide.remove(&slide.number);
    }

    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.
pub(super) struct ArtRecord {
    pub(super) rec_instance: u16,
    pub(super) rec_type: u16,
    pub(super) content_start: usize,
    pub(super) 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.
pub(super) 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.
pub(super) 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 `TextHeaderAtom` (MS-PPT 2.13.33) declaring the `TextTypeEnum` value the
    /// text atom that follows is typed as.
    fn text_header_atom(text_type: u32) -> Vec<u8> {
        let mut buf = record_header(0x0000, RT_TEXT_HEADER_ATOM, 4);
        buf.extend_from_slice(&text_type.to_le_bytes());
        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> {
        slide_persist_atom_with_slide_id(persist_id, 0)
    }

    /// Build a `SlidePersistAtom` naming both `persist_id` (which resolves the `Slide`
    /// container's stream offset) and `slide_id` (what `NotesAtom.slideIdRef` names the
    /// slide by -- #1640). Layout per MS-PPT 2.4.14: `persistIdRef` (4), `flags` (4),
    /// `numberTexts` (4), `slideId` (4), `reserved2` (4).
    fn slide_persist_atom_with_slide_id(persist_id: u32, slide_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; 4]); // flags
        buf.extend_from_slice(&[0u8; 4]); // numberTexts
        buf.extend_from_slice(&slide_id.to_le_bytes());
        buf.extend_from_slice(&[0u8; 4]); // reserved2
        buf
    }

    /// Build a `NotesAtom` (MS-PPT 2.5.7): `slideIdRef` (4 bytes), then `slideFlags` (2)
    /// and `unused` (2) -- neither read here.
    fn notes_atom(slide_id_ref: u32) -> Vec<u8> {
        let mut buf = record_header(0x0000, RT_NOTES_ATOM, 8);
        buf.extend_from_slice(&slide_id_ref.to_le_bytes());
        buf.extend_from_slice(&[0u8; 4]);
        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. `doc_persist_id_ref`
    /// is the persist id of this save's live `DocumentContainer` (#1639).
    fn user_edit_atom(offset_last_edit: u32, offset_persist_directory: u32, doc_persist_id_ref: 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(&doc_persist_id_ref.to_le_bytes());
        buf.extend_from_slice(&[0u8; 8]); // 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(),
        );
        let document = container(RT_DOCUMENT, &slide_list);
        let document_offset = data.len() as u32;
        data.extend_from_slice(&document);

        // Older save: persist id 1 pointed at the stale copy. Newer save: it points at the
        // live one, and adds id 2. Persist id 20 is the `DocumentContainer` itself, named by
        // both saves' `UserEditAtom.docPersistIdRef` (#1639).
        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),
            (20, document_offset),
        ]));

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

        let live =
            live_slide_offsets(&data, &current_user_stream(new_edit_offset)).expect("the persist chain must resolve");
        assert_eq!(
            live.offsets,
            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(),
        );
        let document = container(RT_DOCUMENT, &slide_list);
        let document_offset = data.len() as u32;
        data.extend_from_slice(&document);

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

        let live =
            live_slide_offsets(&data, &current_user_stream(edit_offset)).expect("the persist chain must resolve");
        assert_eq!(live.offsets, 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"
        );
    }

    /// xberg-io/xberg#1639: a `.ppt` stream is append-only, so a deck saved more than once
    /// carries one `SlideListWithText` per save. The first one in the stream is the
    /// **oldest** save's; the live save's list -- reached via `docPersistIdRef` on the
    /// current `UserEditAtom` -- is the presentation's. Reproduces the issue's own example:
    /// a second save adds a slide, and the first save's list must not be read instead.
    #[test]
    fn the_live_document_slide_list_is_read_not_the_first_one_in_the_stream() {
        let slide_a = container(RT_SLIDE, &text_chars_atom("Slide A"));
        let mut data = Vec::new();
        let slide_a_offset = data.len() as u32;
        data.extend_from_slice(&slide_a);

        let old_slide_list = container(RT_SLIDE_LIST_WITH_TEXT, &slide_persist_atom(4));
        let old_document = container(RT_DOCUMENT, &old_slide_list);
        let old_document_offset = data.len() as u32;
        data.extend_from_slice(&old_document);

        let old_dir_offset = data.len() as u32;
        data.extend_from_slice(&persist_directory(&[(4, slide_a_offset), (1, old_document_offset)]));
        let old_edit_offset = data.len() as u32;
        data.extend_from_slice(&user_edit_atom(0, old_dir_offset, 1));

        let slide_b = container(RT_SLIDE, &text_chars_atom("Slide B"));
        let slide_b_offset = data.len() as u32;
        data.extend_from_slice(&slide_b);

        let new_slide_list = container(
            RT_SLIDE_LIST_WITH_TEXT,
            &[slide_persist_atom(4), slide_persist_atom(5)].concat(),
        );
        let new_document = container(RT_DOCUMENT, &new_slide_list);
        let new_document_offset = data.len() as u32;
        data.extend_from_slice(&new_document);

        let new_dir_offset = data.len() as u32;
        data.extend_from_slice(&persist_directory(&[(5, slide_b_offset), (1, new_document_offset)]));
        let new_edit_offset = data.len() as u32;
        data.extend_from_slice(&user_edit_atom(old_edit_offset, new_dir_offset, 1));

        let live =
            live_slide_offsets(&data, &current_user_stream(new_edit_offset)).expect("the persist chain must resolve");
        assert_eq!(
            live.offsets,
            vec![slide_a_offset as usize, slide_b_offset as usize],
            "the live document's slide list names both persist ids 4 and 5, not just the first save's 4"
        );

        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, "the deck added a slide in its second save");
        assert_eq!(slides[0].text, "Slide A");
        assert_eq!(slides[1].text, "Slide B");
    }

    /// xberg-io/xberg#1639, the outline half: the outline-text harvest has the same
    /// first-in-stream defect as the slide list -- every `SlideListWithText` met while
    /// walking the whole stream contributed outline text, so a stale save's wording of a
    /// slide's title could appear beside the live one. Only the live document's own list
    /// may be harvested.
    #[test]
    fn outline_text_is_harvested_only_from_the_live_slide_list() {
        let slide1 = container(RT_SLIDE, &text_chars_atom("body text"));
        let mut data = Vec::new();
        let slide1_offset = data.len() as u32;
        data.extend_from_slice(&slide1);

        let mut old_outline = Vec::new();
        old_outline.extend_from_slice(&slide_persist_atom(1));
        old_outline.extend_from_slice(&text_chars_atom("Old Title"));
        let old_slide_list = container(RT_SLIDE_LIST_WITH_TEXT, &old_outline);
        let old_document = container(RT_DOCUMENT, &old_slide_list);
        let old_document_offset = data.len() as u32;
        data.extend_from_slice(&old_document);

        let old_dir_offset = data.len() as u32;
        data.extend_from_slice(&persist_directory(&[(1, slide1_offset), (2, old_document_offset)]));
        let old_edit_offset = data.len() as u32;
        data.extend_from_slice(&user_edit_atom(0, old_dir_offset, 2));

        let mut new_outline = Vec::new();
        new_outline.extend_from_slice(&slide_persist_atom(1));
        new_outline.extend_from_slice(&text_chars_atom("New Title"));
        let new_slide_list = container(RT_SLIDE_LIST_WITH_TEXT, &new_outline);
        let new_document = container(RT_DOCUMENT, &new_slide_list);
        let new_document_offset = data.len() as u32;
        data.extend_from_slice(&new_document);

        let new_dir_offset = data.len() as u32;
        data.extend_from_slice(&persist_directory(&[(1, slide1_offset), (2, new_document_offset)]));
        let new_edit_offset = data.len() as u32;
        data.extend_from_slice(&user_edit_atom(old_edit_offset, new_dir_offset, 2));

        let live =
            live_slide_offsets(&data, &current_user_stream(new_edit_offset)).expect("the persist chain must resolve");

        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(), 1);
        assert_eq!(
            slides[0].text, "New Title\nbody text",
            "only the live save's outline title is recovered"
        );
        assert!(
            !slides[0].text.contains("Old Title"),
            "a stale save's outline text must not reach the output"
        );
    }

    /// 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");
    }

    /// xberg-io/xberg#1635: the outline's own `TextHeaderAtom` says which run is the slide's
    /// title (`Title` = 0) -- not the first line of whatever text ends up on the slide. A
    /// body-typed atom (`Body` = 1) in the same outline entry must not be mistaken for one.
    #[test]
    fn test_extract_texts_reads_the_outline_title_type_not_the_first_line() {
        let mut outline = Vec::new();
        outline.extend_from_slice(&record_header(0x0000, RT_SLIDE_PERSIST_ATOM, 0));
        outline.extend_from_slice(&text_header_atom(TEXT_TYPE_TITLE));
        outline.extend_from_slice(&text_chars_atom("Search strategy development"));
        outline.extend_from_slice(&text_header_atom(1)); // Body
        outline.extend_from_slice(&text_chars_atom("a body bullet, not the title"));
        let slwt = container(RT_SLIDE_LIST_WITH_TEXT, &outline);

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

        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].title.as_deref(),
            Some("Search strategy development"),
            "the Title-typed atom is the title, not the body bullet or the drawing's first line"
        );
    }

    /// xberg-io/xberg#1635, negative control: `CenterTitle` is `6`, not `5` -- `5` is
    /// `CenterBody`, ordinary body text. Reading the wrong value would silently promote a
    /// slide's body to its title. ~keep
    #[test]
    fn test_extract_texts_treats_center_title_as_six_not_five() {
        let mut center_title = Vec::new();
        center_title.extend_from_slice(&record_header(0x0000, RT_SLIDE_PERSIST_ATOM, 0));
        center_title.extend_from_slice(&text_header_atom(TEXT_TYPE_CENTER_TITLE));
        center_title.extend_from_slice(&text_chars_atom("Refworks"));
        let mut data = Vec::new();
        data.extend_from_slice(&container(RT_SLIDE_LIST_WITH_TEXT, &center_title));
        data.extend_from_slice(&container(RT_SLIDE, &text_chars_atom("some body")));

        let mut warnings = Vec::new();
        let (slides, _, _) =
            extract_texts_from_records(&data, false, None, &mut warnings).expect("record parsing should succeed");
        assert_eq!(
            slides[0].title.as_deref(),
            Some("Refworks"),
            "textType 6 (CenterTitle) is the centred-title placeholder"
        );

        let mut center_body = Vec::new();
        center_body.extend_from_slice(&record_header(0x0000, RT_SLIDE_PERSIST_ATOM, 0));
        center_body.extend_from_slice(&text_header_atom(5));
        center_body.extend_from_slice(&text_chars_atom("body, not a title"));
        let mut data5 = Vec::new();
        data5.extend_from_slice(&container(RT_SLIDE_LIST_WITH_TEXT, &center_body));
        data5.extend_from_slice(&container(RT_SLIDE, &text_chars_atom("drawn body")));

        let mut warnings5 = Vec::new();
        let (slides5, _, _) =
            extract_texts_from_records(&data5, false, None, &mut warnings5).expect("record parsing should succeed");
        assert_eq!(
            slides5[0].title, None,
            "textType 5 is CenterBody, not CenterTitle -- must not become the title"
        );
    }

    /// xberg-io/xberg#1640: the notes master is also an `RT_NOTES` container --
    /// `NotesAtom.slideIdRef == 0x80000000` -- and carries the notes page's layout
    /// placeholder text, not a slide's speaker notes. It must never reach
    /// `speaker_notes` or attach to any slide.
    #[test]
    fn should_not_treat_the_notes_master_placeholder_as_a_speaker_note() {
        let mut notes_master = Vec::new();
        notes_master.extend_from_slice(&notes_atom(NOTES_MASTER_SLIDE_ID_REF));
        notes_master.extend_from_slice(&text_chars_atom("Click to edit Master text styles"));
        let notes_master_container = container(RT_NOTES, &notes_master);

        let mut data = Vec::new();
        data.extend_from_slice(&notes_master_container);
        data.extend_from_slice(&container(RT_SLIDE, &text_chars_atom("Slide One")));

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

        assert!(
            speaker_notes.is_empty(),
            "the notes master's placeholder text must not become a speaker note: {speaker_notes:?}"
        );
        assert_eq!(slides.len(), 1);
        assert_eq!(
            slides[0].notes, None,
            "the master placeholder must not attach to slide 1 either"
        );
    }

    /// xberg-io/xberg#1640: notes must attach to the slide `NotesAtom.slideIdRef` names,
    /// resolved through the live `SlidePersistAtom.slideId` -- not to the slide at the same
    /// position among the deck's non-empty notes pages. Slide 1 has no notes; slide 2's
    /// note must land on slide 2, not shift onto slide 1.
    #[test]
    fn should_attach_notes_to_the_slide_named_by_slide_id_ref_not_position() {
        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();
        let slide1_offset = data.len() as u32;
        data.extend_from_slice(&slide1);
        let slide2_offset = data.len() as u32;
        data.extend_from_slice(&slide2);

        let mut notes2 = Vec::new();
        notes2.extend_from_slice(&notes_atom(101));
        notes2.extend_from_slice(&text_chars_atom("Notes for slide two"));
        data.extend_from_slice(&container(RT_NOTES, &notes2));

        let slide_list = container(
            RT_SLIDE_LIST_WITH_TEXT,
            &[
                slide_persist_atom_with_slide_id(10, 100),
                slide_persist_atom_with_slide_id(11, 101),
            ]
            .concat(),
        );
        let document = container(RT_DOCUMENT, &slide_list);
        let document_offset = data.len() as u32;
        data.extend_from_slice(&document);

        let dir_offset = data.len() as u32;
        data.extend_from_slice(&persist_directory(&[
            (10, slide1_offset),
            (11, slide2_offset),
            (99, document_offset),
        ]));
        let edit_offset = data.len() as u32;
        data.extend_from_slice(&user_edit_atom(0, dir_offset, 99));

        let live =
            live_slide_offsets(&data, &current_user_stream(edit_offset)).expect("the persist chain must resolve");

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

        assert_eq!(slides.len(), 2);
        assert_eq!(
            slides[0].notes, None,
            "slide 1 has no notes and must not inherit slide 2's by position"
        );
        assert_eq!(slides[1].notes.as_deref(), Some("Notes for slide two"));
        assert_eq!(speaker_notes, vec!["Notes for slide two".to_string()]);
    }

    /// 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"
        );
    }

    /// REV-CB regression for GH#1687 (shares the GH#1662/GH#1686 fix): an OCR-only
    /// `ExtractionConfig` (no `images.extract_images`, no captioning, no QR codes) must
    /// still read a `.ppt` OLE container's embedded image out of its `Pictures` stream,
    /// not skip it. `needs_image_data` gained the OCR disjunct that makes this true
    /// (#1662); PPT shares that predicate with DOCX, HTML and PPTX through
    /// `PptExtractor::extract_content`'s `config.needs_image_data()` call (see
    /// `extractors::ppt`), but until now nothing exercised that call site directly.
    /// Before the fix, `extract_images` stayed `false` for an OCR-only config, so
    /// `extract_ppt_text_with_options` never read `/Pictures` at all and
    /// `InternalDocument::images` stayed empty, silently, with no warning -- the same
    /// shape `should_return_no_images_when_extract_images_is_false` above proves at the
    /// lower `extract_ppt_text_with_options(bool)` layer. This test lives here rather
    /// than in `extractors::ppt`'s own test module because it reuses `build_test_ppt_ole`
    /// and the blip/record builders already proven above, instead of a second hand-rolled
    /// OLE/CFB writer for the same container shape.
    #[tokio::test]
    async fn should_read_real_embedded_image_bytes_for_ocr_only_config_at_extract_content() {
        use crate::core::config::{ExtractionConfig, OcrConfig};
        use crate::core::mime::LEGACY_POWERPOINT_MIME_TYPE;
        use crate::extractors::ppt::PptExtractor;
        use crate::plugins::InternalDocumentExtractor;

        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 config = ExtractionConfig {
            ocr: Some(OcrConfig::default()),
            ..Default::default()
        };

        let extractor = PptExtractor::new();
        let internal_doc = extractor
            .extract_content(&content, LEGACY_POWERPOINT_MIME_TYPE, &config)
            .await
            .expect("synthetic OLE container must extract");

        assert_eq!(internal_doc.images.len(), 1, "the single blip must yield one image");
        assert_eq!(
            internal_doc.images[0].data.as_ref(),
            &picture[..],
            "an OCR-only config must still read the real embedded-image bytes, not skip the Pictures stream"
        );
    }

    #[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` is 1-based: 1 -> the blip at offset 0, 2 -> the blip after it. ~keep
        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);
    }
}