flpdf 0.6.0

A pure-Rust PDF toolkit modeled on qpdf — read, rewrite, linearize, and inspect PDFs.
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
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
//! Layout writer — orchestrates the full linearized PDF output.
//!
//! qpdf correspondence: QPDFWriter.cc linearized write path split from the standard writer.
//!
//! This module assembles the six-part Annex F layout in correct order and
//! tracks qpdf's pass-1 and final-pass byte coordinates. The canonical writer
//! streams the final pass through its configured sink; the test/inspection
//! helper may additionally return the finished bytes.
//!
//! # Part ordering (Annex F)
//!
//! ```text
//! Annex F Part | Contents in this impl
//! -------------|-------------------------------------------------------------------
//! Part 1       | header + linearization param dict (`renumber.param_dict_ref()`)
//!              | with placeholders + Part 1 xref subsection (param-dict obj only)
//!              | + trailer
//! Part 2       | hint stream object (filtered according to stream-data policy)
//! Part 3       | first-page body — Plan.part2_objects with renumbered refs
//! Part 4       | shared/catalog/info — Plan.part3_objects with renumbered refs
//! Part 5       | remaining body — `Plan.part4_objects()` (derived view of
//!              | `part4_other_pages_private` + `_shared` + `_rest`) with
//!              | renumbered refs
//! Part 6       | cross-reference table for all objects + trailer
//! ```
//!
//! **Terminology note**: the `LinearizationPlan` field names (`part2_objects`,
//! `part3_objects`, `part4_objects`) do **not** correspond to the Annex F "Part"
//! numbers above.  Mapping:
//!
//! - `Plan.part2_objects` → Annex F Part 3 (first-page body)
//! - `Plan.part3_objects` → Annex F Part 4 (shared/catalog/info)
//! - `Plan.part4_objects()` → Annex F Part 5 (remaining body)
//!
//! The param-dict and hint-stream object numbers are **dynamic** — the
//! renumber map decides which slots they occupy. Use
//! [`RenumberMap::param_dict_ref`] and [`RenumberMap::hint_stream_slot`]
//! to query their actual positions; the writer reads both fields from
//! the renumber map rather than assuming `1` and `renumber.len() + 1`.
//! /Size in the trailer is `renumber.len() as u32 + 1` (the `total_count`
//! local), which already accounts for both reserved slots.
//!
//! # 2-pass algorithm
//!
//! qpdf writes the hint object once between two layout passes:
//!
//! 1. **Pass 1**: omit the reserved hint object and collect the virtual offsets
//!    and byte lengths for the rest of the file.
//! 2. **Build the hint object**: fill all hint tables from those pass-1 values,
//!    encode the payload, and frame/encrypt the complete indirect object once.
//! 3. **Pass 2**: write the final file and splice that exact hint-object buffer
//!    into the reserved slot. Fixed-width Part 1 padding keeps the downstream
//!    offsets aligned with the values encoded in the hint tables.
//!
//! # Scope
//!
//! The canonical sink route derives the final parameter dictionary and xref
//! coordinates before final emission. `LinearizedOffsets` remains available to
//! the in-memory inspection helper and its compatibility back-patch API.

use std::collections::{BTreeMap, BTreeSet};
use std::io::{Read, Seek, Write};
use std::path::Path;

use crate::linearization::hint_page::{bits_needed, PageOffsetHintTable};
use crate::linearization::hint_shared::SharedObjectHintTable;
use crate::linearization::hint_stream::{
    encode_hint_stream_selected, HintStreamMode, OutlineHintTable,
};
use crate::linearization::part1::{Part1Bytes, Part1Placeholders};
use crate::linearization::plan::{
    part9_category_order_key, ContainerPart, LinearizationPlan, RoutedObjStmBatch,
};
use crate::linearization::renumber::{ObjStmRelocation, RenumberMap, SecondHalfContainerAnchor};
use crate::pipeline::stdio_file::StdioBuffer;
use crate::qpdf_obj_gen::QpdfObjGen;
use crate::writer::encrypted_strings::EncryptedStringEmitter;
use crate::writer::object_streams::{
    emit_objstm_body_from_handles_with_writer, planner_config_from_options,
    wrap_objstm_body_as_handle,
};
use crate::writer::{
    decrement_progress_event, effective_pdf_version_and_ext, effective_stream_policy,
    output::{OutputSink, OutputTarget},
    report_progress_event,
    serialize::xref_stream,
    CompressStreams, NewlineBeforeEndstream, ObjectWriterEmission, WriterOptions, WriterResult,
};
use crate::{ObjectHandle, ObjectRef, Pdf, Result};

const EBADF_ERRNO: i32 = 9;

/// Forward-only destination for qpdf's linearization pass 1.
///
/// qpdf selects either `pushDiscardFilter` or a buffered `Pl_StdioFile` for
/// this pass (`QPDFWriter.cc:2656-2676`). Keeping the destination separate from
/// [`OutputSink`] lets the sink count and digest accepted bytes without owning a
/// second document-sized buffer.
enum Pass1Destination {
    Discard,
    File {
        path: std::path::PathBuf,
        writer: std::io::BufWriter<std::fs::File>,
    },
}

struct Pass1OutputTarget {
    destination: Pass1Destination,
}

impl Pass1OutputTarget {
    #[cfg(test)]
    fn discard() -> Self {
        Self {
            destination: Pass1Destination::Discard,
        }
    }

    fn new(path: Option<&Path>) -> Result<Self> {
        let destination = match path {
            Some(path) => {
                let file = std::fs::File::create(path)
                    .map_err(|source| crate::Error::file_io("open", path, source))?;
                Pass1Destination::File {
                    path: path.to_path_buf(),
                    writer: std::io::BufWriter::new(file),
                }
            }
            None => Pass1Destination::Discard,
        };
        Ok(Self { destination })
    }

    fn write_debug_comments(&mut self, comments: &[u8]) {
        if let Pass1Destination::File { writer, .. } = &mut self.destination {
            write_pass1_debug_comments(writer, comments);
        }
    }
}

impl OutputTarget for Pass1OutputTarget {
    fn write_chunk(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
        match &mut self.destination {
            Pass1Destination::Discard => Ok(bytes.len()),
            Pass1Destination::File { path, writer } => writer
                .write_all(bytes)
                .map(|()| bytes.len())
                .map_err(|source| {
                    std::io::Error::new(
                        source.kind(),
                        format!("write {}: {source}", path.display()),
                    )
                }),
        }
    }

    fn finish_segment(&mut self) -> Result<()> {
        Ok(())
    }

    fn finish_document(&mut self) -> Result<()> {
        match &mut self.destination {
            Pass1Destination::Discard => Ok(()),
            Pass1Destination::File { writer, .. } => match writer.flush() {
                // cov:ignore-start: safe Rust cannot manufacture a BufWriter
                // around a closed descriptor; qpdf's Pl_StdioFile keeps this
                // EBADF guard for externally closed FILE handles.
                Err(source) if source.raw_os_error() == Some(EBADF_ERRNO) => {
                    Err(crate::Error::Internal(
                        "linearization pass1: Pl_StdioFile::finish: stream already closed"
                            .to_string(),
                    ))
                }
                // cov:ignore-end
                Ok(()) | Err(_) => Ok(()),
            },
        }
    }
}

// ---------------------------------------------------------------------------
// ObjStm layout
// ---------------------------------------------------------------------------

/// A single ObjStm container scheduled for the linearized output.
///
/// `members` carries the **renumbered** member refs in batch order (the
/// pair-table order inside the container).  `container_new_num` is the fresh
/// object number assigned to the container itself — always above every
/// `RenumberMap` slot so it never collides with a planned object, the param
/// dict, or the hint stream.
#[derive(Debug, Clone)]
struct ObjStmContainer {
    /// Fresh object number for the container indirect object.
    container_new_num: u32,
    /// `(original_ref, new_ref)` pairs in batch order.
    members: Vec<(ObjectRef, ObjectRef)>,
}

/// Resolved ObjStm layout for a linearized write.
///
/// Built once, before the two layout passes, from the Part-tagged
/// [`crate::linearization::plan::ObjStmBatchPlan`].  The contained-object set
/// and per-container membership are **stable across the two passes** (only the
/// surrounding byte offsets shift), which keeps both passes on the same layout.
#[derive(Debug, Clone, Default)]
struct ObjStmLayout {
    /// Containers emitted in the open-document region (qpdf part4) — physically
    /// right after the Catalog and before the primary hint stream, so they are
    /// the first compressed objects of the first half.
    open_document: Vec<ObjStmContainer>,
    /// Containers emitted inside the first-page section (Annex F Part 3,
    /// before `/E`).
    part3: Vec<ObjStmContainer>,
    /// Containers emitted in the remaining body (Annex F Part 5, after `/E`).
    part4: Vec<ObjStmContainer>,
    /// `original_ref → (container_new_num, index_within_container)` for every
    /// object that lives inside an ObjStm.  Drives type-2 xref entries and
    /// the skip-from-plain-emission decision.
    member_to_container: BTreeMap<ObjectRef, (u32, u32)>,
    /// Source ObjStm container identities represented by the reconstructed
    /// containers. Preserve plan identities must not be emitted as plain body
    /// objects a second time.
    source_container_numbers: BTreeSet<u32>,
}

impl ObjStmLayout {
    /// `true` when no ObjStm containers are scheduled — the writer then keeps
    /// its classic-xref-table path verbatim (no regression).
    fn is_empty(&self) -> bool {
        self.open_document.is_empty() && self.part3.is_empty() && self.part4.is_empty()
    }

    /// Resolve the Part-tagged, writer-filtered ObjStm batch plan.
    ///
    /// This is the single source of truth for *which* objects are ObjStm
    /// members and *in what order* — consumed both by
    /// [`RenumberMap::place_objstm_members_per_half`] (slot allocation) and by
    /// [`ObjStmLayout::build_from_batches`] (container construction), so the
    /// two never disagree about membership or pair-table order.
    fn resolve_batches<R: Read + Seek>(
        plan: &LinearizationPlan,
        pdf: &mut Pdf<R>,
        options: &WriterOptions,
    ) -> Result<crate::linearization::plan::ObjStmBatchPlan> {
        let config = planner_config_from_options(options);
        let batch_plan = plan.objstm_batches(pdf, &config)?;

        // Writer-level invariant (qpdf linearization rule): a page DICTIONARY may
        // never be compressed — the linearization layout addresses pages by file
        // offset. qpdf compresses page-*private* non-dictionary objects (fonts,
        // etc.) normally, so only the page dictionaries themselves are excluded.
        // The Generate membership already erases them (QPDFWriter.cc:2141), so
        // this is a no-op there; it guards a Preserve source whose ObjStm somehow
        // carried a page dict.
        let page_dicts: std::collections::BTreeSet<ObjectRef> =
            crate::pages::page_refs(pdf)?.into_iter().collect();
        let filter_batches = |batches: Vec<RoutedObjStmBatch>| -> Vec<RoutedObjStmBatch> {
            batches
                .into_iter()
                .filter_map(|batch| {
                    let members: Vec<ObjectRef> = batch
                        .members
                        .into_iter()
                        .filter(|r| !page_dicts.contains(r))
                        .collect();
                    (!members.is_empty()).then_some(RoutedObjStmBatch {
                        members,
                        route: batch.route,
                        source_container_number: batch.source_container_number,
                    })
                })
                .collect()
        };
        Ok(crate::linearization::plan::ObjStmBatchPlan {
            open_document_batches: filter_batches(batch_plan.open_document_batches),
            part3_batches: filter_batches(batch_plan.part3_batches),
            part4_batches: filter_batches(batch_plan.part4_batches),
        })
    }

    /// Build the layout from an already-resolved batch plan, mapping every
    /// member + container through the **placed** `renumber` map.
    ///
    /// `container_numbers` are the per-batch container object numbers returned
    /// by [`RenumberMap::place_objstm_members_per_half`] (open-document batches
    /// first, then Part-3, then Part-4), so the layout never re-derives numbers
    /// independently. Every member ref is mapped through `renumber`; a missing
    /// entry is a planner / renumber inconsistency and is surfaced loudly.
    fn build_from_batches(
        batch_plan: &crate::linearization::plan::ObjStmBatchPlan,
        container_numbers: &[u32],
        renumber: &RenumberMap,
    ) -> Result<Self> {
        if batch_plan.open_document_batches.is_empty()
            && batch_plan.part3_batches.is_empty()
            && batch_plan.part4_batches.is_empty()
        {
            return Ok(Self::default());
        }

        let mut member_to_container = BTreeMap::new();
        let source_container_numbers: BTreeSet<u32> = batch_plan
            .open_document_batches
            .iter()
            .chain(&batch_plan.part3_batches)
            .chain(&batch_plan.part4_batches)
            .filter_map(|batch| batch.source_container_number)
            .collect();

        let take = |batches: &[RoutedObjStmBatch],
                    out: &mut Vec<ObjStmContainer>,
                    map: &mut BTreeMap<ObjectRef, (u32, u32)>,
                    container_iter: &mut std::vec::IntoIter<u32>|
         -> Result<()> {
            for batch in batches {
                if batch.members.is_empty() {
                    continue;
                }
                let container_new_num = container_iter.next().ok_or_else(|| {
                    crate::Error::Unsupported(
                        "linearization writer: ObjStm container-number stream exhausted \
                         (renumber relocation / batch-plan inconsistency)"
                            .to_string(),
                    )
                })?;
                let mut members = Vec::with_capacity(batch.members.len());
                for (idx, &orig) in batch.members.iter().enumerate() {
                    let new_ref = renumber.new_for_original(orig).ok_or_else(|| {
                        crate::Error::Unsupported(format!(
                            "linearization writer: ObjStm member {orig} has no renumber \
                             entry (planner / renumber inconsistency)"
                        ))
                    })?;
                    map.insert(orig, (container_new_num, idx as u32));
                    members.push((orig, new_ref));
                }
                out.push(ObjStmContainer {
                    container_new_num,
                    members,
                });
            }
            Ok(())
        };

        let container_numbers_vec: Vec<u32> = container_numbers.to_vec();
        let mut container_iter = container_numbers_vec.into_iter();
        let mut open_document = Vec::new();
        let mut part3 = Vec::new();
        let mut part4 = Vec::new();
        // Consumption order MUST match `place_objstm_members_per_half`'s
        // `container_numbers` order: open-document, then Part-3, then Part-4.
        take(
            &batch_plan.open_document_batches,
            &mut open_document,
            &mut member_to_container,
            &mut container_iter,
        )?;
        take(
            &batch_plan.part3_batches,
            &mut part3,
            &mut member_to_container,
            &mut container_iter,
        )?;
        take(
            &batch_plan.part4_batches,
            &mut part4,
            &mut member_to_container,
            &mut container_iter,
        )?;
        let _ = container_iter;

        Ok(Self {
            open_document,
            part3,
            part4,
            member_to_container,
            source_container_numbers,
        })
    }
}

/// Build the ObjStm container stream object for one scheduled container from
/// the live member handles and apply qpdf's global structural-stream
/// compression policy.
fn append_objstm_container_object<R: Read + Seek>(
    out: &mut OutputSink<'_>,
    container: &ObjStmContainer,
    renumber: &RenumberMap,
    pdf: &mut Pdf<R>,
    removed_refs: &BTreeSet<QpdfObjGen>,
    options: &WriterOptions,
    encrypt_ctx: Option<&crate::writer::EncryptionContext>,
) -> Result<usize> {
    let filtered = matches!(effective_stream_policy(options), Some(CompressStreams::Yes));
    let map = |object_gen| {
        renumber.new_for_raw(object_gen).ok_or_else(|| {
            // cov:ignore-start: the planner and ObjStm member map are built together, so a missing member identity is an internal invariant failure
            crate::Error::Unsupported(format!(
                "linearization writer: ObjStm member raw reference {} {} has no renumber entry",
                object_gen.get_obj(),
                object_gen.get_gen()
            ))
        })
        // cov:ignore-end
    };
    let mut members: Vec<(ObjectRef, ObjectHandle)> = Vec::with_capacity(container.members.len());
    for &(orig, new_ref) in &container.members {
        let handle = pdf.get_object_handle(orig);
        handle.try_dereference()?;
        // qpdf warns and writes null when a malformed source stream is routed
        // into an object stream (`QPDFWriter.cc:1714-1721`). Keep that edge at
        // the canonical handle boundary rather than materializing a legacy
        // stream value that cannot be a valid ObjStm member.
        let handle = if handle.as_stream_dict().is_some() {
            ObjectHandle::null()
        } else {
            handle
        };
        members.push((new_ref, handle));
    }
    let body = emit_objstm_body_from_handles_with_writer(
        &members,
        &mut |out, _member_index, _object_ref, handle| {
            crate::writer::output::with_buffer_sink(out, |out| {
                handle.write_object_with_qpdf_obj_gen_map_and_removed(out, &map, removed_refs)
            })
        },
    )?;
    let compress = if filtered {
        CompressStreams::Yes
    } else {
        CompressStreams::No
    };
    let (stream_handle, data) = wrap_objstm_body_as_handle(&body, compress, None)?;
    let stream_dict = stream_handle.as_stream_dict().ok_or_else(|| {
        // cov:ignore-start: wrap_objstm_body_as_handle always returns a stream handle.
        crate::Error::Internal("linearization ObjStm wrapper produced a non-stream handle".into())
        // cov:ignore-end
    })?; // cov:ignore: wrap_objstm_body_as_handle always returns a stream handle.
    let object_ref = ObjectRef::new(container.container_new_num, 0);
    // PDF encryption applies to the ObjStm container stream as one stream
    // object. The member objects remain plaintext inside that encrypted
    // payload; encrypting them individually would not match qpdf or the PDF
    // object-stream encryption rules (`QPDFWriter.cc:1782-1800`).
    if let Some(ctx) = encrypt_ctx {
        let mut payload_length = data.len();
        crate::writer::adjust_aes_stream_length(&mut payload_length, ctx, true)?;
        stream_dict.replace_key(
            b"/Length",
            ObjectHandle::integer(i64::try_from(payload_length).unwrap_or(i64::MAX)),
        )?;
    }

    // qpdf writes ObjStm keys in the fixed order Type/Length/Filter/N/First.
    // The values themselves are emitted by the canonical handle serializer;
    // only the surrounding order and object-stream framing remain raw layout.
    // Its newline-before-endstream setting applies to this container exactly
    // as it does to ordinary body streams (QPDFWriter.cc:1752-1755).
    let offset = out.position_usize()?;
    out.write_bytes(format!("{} 0 obj\n", container.container_new_num).as_bytes())?;
    out.write_bytes(b"<< /Type ")?;
    stream_dict.try_get_key(b"/Type")?.write_object(out)?;
    out.write_bytes(b" /Length ")?;
    stream_dict.try_get_key(b"/Length")?.write_object(out)?;
    if filtered {
        out.write_bytes(b" /Filter ")?;
        stream_dict.try_get_key(b"/Filter")?.write_object(out)?;
    }
    out.write_bytes(b" /N ")?;
    stream_dict.try_get_key(b"/N")?.write_object(out)?;
    out.write_bytes(b" /First ")?;
    stream_dict.try_get_key(b"/First")?.write_object(out)?;
    out.write_bytes(b" >>")?;
    if let Some(ctx) = encrypt_ctx {
        crate::writer::write_stream_payload_with_pipeline(
            out,
            &data,
            options.newline_before_endstream,
            object_ref,
            ctx,
            true,
            None,
        )?; // cov:ignore: encrypted ObjStm payload failure is a defensive pipeline continuation
    } else {
        crate::writer::serialize::write_stream_payload(
            out,
            &data,
            options.newline_before_endstream,
        )?; // cov:ignore: plain ObjStm payload failure is a defensive pipeline continuation
    }
    out.write_bytes(b"\nendobj\n")?;
    Ok(offset)
}

// ---------------------------------------------------------------------------
// Public result types
// ---------------------------------------------------------------------------

/// Byte offsets and derived values for a linearized PDF.
///
/// All values are absolute byte positions within `LinearizedDocument::bytes`
/// unless stated otherwise. These values describe the byte layout used to
/// fill the Part 1 parameter dictionary.
#[derive(Debug, Clone)]
pub struct LinearizedOffsets {
    /// Total file length in bytes — corresponds to `/L` in the param dict.
    pub file_length: usize,

    /// Byte offset of the hint stream object (its `N 0 obj` header) —
    /// corresponds to `/H[0]` in the param dict.
    pub hint_stream_offset: usize,

    /// Full byte length of the hint stream indirect object — corresponds to
    /// `/H[1]` in the param dict.
    ///
    /// This spans the complete `N 0 obj … endobj` representation, including
    /// the object header, stream dictionary, encoded payload, stream framing,
    /// and `endobj`. It is distinct from the hint stream dictionary's
    /// `/Length`, which counts only the encoded payload.
    pub hint_stream_length: usize,

    /// New object number assigned to the first-page page object — corresponds
    /// to `/O` in the param dict.  Typically `2` (first Part-2 object).
    pub first_page_object_new_num: u32,

    /// Byte offset immediately after the last byte of Annex F Part 3 (the
    /// first-page body section, `Plan.part2_objects`).  Corresponds to `/E`.
    pub end_of_first_page_offset: usize,

    /// Byte offset of the Part 6 cross-reference table (`xref` keyword).
    pub last_xref_keyword_offset: usize,

    /// Byte offset of the first entry in the Part 6 cross-reference table
    /// (= position immediately after the `xref\n0 N\n` header line) —
    /// corresponds to `/T` in the param dict per qpdf's linearization convention.
    pub last_xref_offset: usize,

    /// Total number of pages — corresponds to `/N`.
    pub page_count: u32,

    /// Placeholder byte ranges inside the Part 1 bytes.  Pre-back-patch these
    /// are 10-wide zero slots; post-back-patch the back-patcher updates them
    /// to point at the rewritten variable-width decimal value bytes.
    pub part1_placeholders: Part1Placeholders,

    /// `new_object_number → byte_offset` map covering every object in the
    /// linearized file.  Used for structural verification.
    pub xref_offsets: BTreeMap<u32, usize>,

    /// Byte range of the `/Prev` value placeholder in the Part 1 (first)
    /// trailer.  The value is written as a left-justified decimal integer
    /// padded on the right with spaces to exactly `PREV_PLACEHOLDER_WIDTH`
    /// bytes.  The back-patcher overwrites this range with the actual
    /// `last_xref_keyword_offset` value.
    pub first_trailer_prev_range: std::ops::Range<usize>,

    /// Absolute byte range spanning the rewritable param-dict region:
    /// `<<` through the end of the trailing pad (inclusive of `\nendobj\n`).
    /// The back-patcher splices a variable-width dict body + space-pad into
    /// this region in one operation.
    pub dict_writable_region: std::ops::Range<usize>,
}

/// The finished linearized PDF together with the offset metadata.
#[derive(Debug)]
pub struct LinearizedDocument {
    /// Raw bytes of the complete linearized PDF file.
    pub bytes: Vec<u8>,
    /// Offset metadata for back-patching.
    pub offsets: LinearizedOffsets,
}

/// Result shared by the memory-backed inspection helper and the canonical
/// sink-backed writer route. The latter deliberately does not retain a
/// document-sized byte vector after it has reached the configured sink.
struct LinearizedWriteResult {
    #[allow(dead_code)]
    document: Option<LinearizedDocument>,
    writer_result: WriterResult,
}

// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------

/// Width of the `/Prev` value field in the Part 1 (first) trailer.
///
/// The value is written as a left-justified decimal integer with space-padding
/// on the right, matching qpdf's convention.  22 bytes is sufficient for any
/// PDF file offset up to 10^22 - 1 (qpdf uses the same width).
pub(crate) const PREV_PLACEHOLDER_WIDTH: usize = 22;

// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------

/// Append `N G obj\n<object>\nendobj\n` to `bytes` and return the offset of the
/// `N G obj` header (i.e. the start of the object).
///
/// When `encrypted_string_emitter` is `Some`, strings are encrypted from the
/// writer's per-object emission state without mutating `object`. The
/// `/Encrypt` dictionary never reaches this helper: [`do_write_pass`] emits it
/// directly through
/// [`write_encryption_dictionary_handle`](crate::writer::encrypted_strings::write_encryption_dictionary_handle)
/// so it remains plaintext.
fn append_object(
    out: &mut OutputSink<'_>,
    new_ref: ObjectRef,
    object: &ObjectHandle,
    map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
    removed_refs: &BTreeSet<QpdfObjGen>,
    encrypted_string_emitter: Option<&mut EncryptedStringEmitter>,
) -> Result<usize> {
    let offset = out.position_usize()?;
    out.write_bytes(format!("{} {} obj\n", new_ref.number, new_ref.generation).as_bytes())?;
    if let Some(emitter) = encrypted_string_emitter {
        emitter.write_handle_object_with_qpdf_obj_gen_map_and_mode(
            out,
            new_ref,
            None,
            object,
            false,
            map,
            removed_refs,
        )?; // cov:ignore: canonical handle emission only errors for an invalid source graph.
    } else {
        object.write_object_with_qpdf_obj_gen_map_and_removed(out, map, removed_refs)?;
    }
    out.write_bytes(b"\nendobj\n")?;
    Ok(offset)
}

/// Append one live-handle body object in output-number space.
#[allow(clippy::too_many_arguments)]
fn append_body_object_with_raw_identity(
    out: &mut OutputSink<'_>,
    new_ref: ObjectRef,
    original_ref: QpdfObjGen,
    object: &ObjectHandle,
    options: &WriterOptions,
    encrypt_ctx: Option<&crate::writer::EncryptionContext>,
    encrypted_string_emitter: Option<&mut EncryptedStringEmitter>,
    renumber: &RenumberMap,
    removed_refs: &BTreeSet<QpdfObjGen>,
    content_normalize_refs: &BTreeSet<QpdfObjGen>,
) -> Result<usize> {
    object.try_dereference()?;
    let map = |object_gen| {
        renumber.new_for_raw(object_gen).ok_or_else(|| {
            // cov:ignore-start: every serialized body identity comes from the same raw RenumberMap that assigned its slot
            crate::Error::Unsupported(format!(
                "linearization writer: raw reference {} {} has no renumber entry",
                object_gen.get_obj(),
                object_gen.get_gen()
            ))
        })
        // cov:ignore-end
    };

    if object.as_stream_dict().is_none() {
        return append_object(
            out,
            new_ref,
            object,
            &map,
            removed_refs,
            encrypted_string_emitter,
        );
    }

    let (dict, data, dictionary_options) =
        crate::writer::plain::body::canonical_stream_output_for_linearization(
            object,
            options,
            options.content_normalization && content_normalize_refs.contains(&original_ref),
        )?; // cov:ignore: LLVM maps this covered stream-output call terminator to a zero-count continuation region
    let mut entries = dict.try_as_dictionary()?.unwrap_or_default();
    let payload_ctx = encrypt_ctx.filter(|ctx| new_ref != ctx.encrypt_ref);
    let is_metadata_stream = dict.try_is_dictionary_of_type(b"Metadata", b"")?;
    let cleartext_metadata =
        payload_ctx.is_some_and(|ctx| !ctx.encrypt_metadata && is_metadata_stream);
    // qpdf clears the active data key for cleartext metadata and leaves the
    // stream dictionary's ordinary filter policy to `unparseObject`; it does
    // not inject a synthetic `/Crypt /Identity` stage here
    // (`QPDFWriter.cc:1539-1546`).

    let mut payload_length = data.len();
    if let Some(ctx) = payload_ctx.filter(|_| !cleartext_metadata) {
        crate::writer::adjust_aes_stream_length(&mut payload_length, ctx, true)?;
    }
    entries.insert(
        b"/Length".to_vec(),
        ObjectHandle::integer(i64::try_from(payload_length).unwrap_or(i64::MAX)),
    );
    let dict = ObjectHandle::dictionary(entries.into_iter().collect());

    let offset = out.position_usize()?;
    out.write_bytes(format!("{} {} obj\n", new_ref.number, new_ref.generation).as_bytes())?;
    if let Some(emitter) = encrypted_string_emitter {
        emitter.write_handle_stream_dict_with_qpdf_obj_gen_map(
            out,
            new_ref,
            None,
            &dict,
            crate::writer::encrypted_strings::StreamDictOptions::new(
                false,
                dictionary_options,
                true,
            ),
            &map,
            removed_refs,
            None,
        )?; // cov:ignore: canonical stream-dictionary emission only errors for an invalid source graph.
    } else {
        dict.write_stream_body_with_qpdf_obj_gen_map_and_removed_with_options(
            out,
            dictionary_options,
            &map,
            removed_refs,
        )?; // cov:ignore: the unencrypted linearized route normally uses the shared string emitter; this direct owner call is validated by the compact writer tests
    }

    if let Some(ctx) = payload_ctx.filter(|_| !cleartext_metadata) {
        crate::writer::write_stream_payload_with_pipeline(
            out,
            &data,
            options.newline_before_endstream,
            new_ref,
            ctx,
            true,
            None,
        )?; // cov:ignore: stream payload encryption is a validated in-memory writer boundary.
    } else {
        crate::writer::serialize::write_stream_payload(
            out,
            &data,
            options.newline_before_endstream,
        )?; // cov:ignore: plain linearized stream payload failure is a defensive pipeline continuation
    }
    out.write_bytes(b"\nendobj\n")?;
    Ok(offset)
}

#[allow(clippy::too_many_arguments)]
fn append_body_object_for_ref<R: Read + Seek>(
    out: &mut OutputSink<'_>,
    pdf: &mut Pdf<R>,
    new_ref: ObjectRef,
    original_ref: ObjectRef,
    options: &WriterOptions,
    encrypt_ctx: Option<&crate::writer::EncryptionContext>,
    encrypted_string_emitter: Option<&mut EncryptedStringEmitter>,
    renumber: &RenumberMap,
    removed_refs: &BTreeSet<QpdfObjGen>,
    content_normalize_refs: &BTreeSet<QpdfObjGen>,
) -> Result<usize> {
    let object = pdf.get_object_handle(original_ref);
    append_body_object_with_raw_identity(
        out,
        new_ref,
        QpdfObjGen::try_from_object_ref(original_ref)?,
        &object,
        options,
        encrypt_ctx,
        encrypted_string_emitter,
        renumber,
        removed_refs,
        content_normalize_refs,
    )
}

/// Compatibility adapter for the test-only helper surface and callers that
/// already own a checked `ObjectRef`. The linearization production path uses
/// [`append_body_object_with_raw_identity`] so its removed set is prepared at
/// the writer boundary rather than rebuilt for each object.
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
fn append_body_object(
    out: &mut OutputSink<'_>,
    new_ref: ObjectRef,
    original_ref: ObjectRef,
    object: &ObjectHandle,
    options: &WriterOptions,
    encrypt_ctx: Option<&crate::writer::EncryptionContext>,
    encrypted_string_emitter: Option<&mut EncryptedStringEmitter>,
    renumber: &RenumberMap,
    removed_refs: &BTreeSet<ObjectRef>,
    content_normalize_refs: &BTreeSet<ObjectRef>,
) -> Result<usize> {
    let raw_removed_refs =
        crate::writer::object::qpdf_obj_gen_set_from_object_ref_set(removed_refs)?;
    let raw_content_normalize_refs = content_normalize_refs
        .iter()
        .filter_map(|object_ref| QpdfObjGen::try_from_object_ref(*object_ref).ok())
        .collect();
    append_body_object_with_raw_identity(
        out,
        new_ref,
        QpdfObjGen::try_from_object_ref(original_ref)?,
        object,
        options,
        encrypt_ctx,
        encrypted_string_emitter,
        renumber,
        &raw_removed_refs,
        &raw_content_normalize_refs,
    )
}

#[allow(clippy::too_many_arguments)]
fn append_body_object_for_raw<R: Read + Seek>(
    out: &mut OutputSink<'_>,
    pdf: &mut Pdf<R>,
    new_ref: ObjectRef,
    original_gen: QpdfObjGen,
    options: &WriterOptions,
    encrypt_ctx: Option<&crate::writer::EncryptionContext>,
    encrypted_string_emitter: Option<&mut EncryptedStringEmitter>,
    renumber: &RenumberMap,
    removed_refs: &BTreeSet<QpdfObjGen>,
    content_normalize_refs: &BTreeSet<QpdfObjGen>,
) -> Result<usize> {
    let object =
        pdf.get_object_handle_by_raw_identity(original_gen.get_obj(), original_gen.get_gen());
    append_body_object_with_raw_identity(
        out,
        new_ref,
        original_gen,
        &object,
        options,
        encrypt_ctx,
        encrypted_string_emitter,
        renumber,
        removed_refs,
        content_normalize_refs,
    )
}

/// Write repeated padding through the counted output boundary without creating
/// a document-sized temporary Vec. The final linearization target is Vec-backed
/// and may later patch this fixed-width region; pass 1 uses the same forward
/// bytes for qpdf's discard/file pipeline.
fn write_repeated_bytes(out: &mut OutputSink<'_>, byte: u8, mut count: usize) -> Result<()> {
    const CHUNK_SIZE: usize = 4096;
    let chunk = [byte; CHUNK_SIZE];
    while count >= CHUNK_SIZE {
        out.write_bytes(&chunk)?;
        count -= CHUNK_SIZE;
    }
    if count != 0 {
        out.write_bytes(&chunk[..count])?;
    } // cov:ignore: LLVM attributes this covered partial-padding branch to the write line
    Ok(())
}

/// Byte width of a single classic cross-reference entry:
/// `NNNNNNNNNN GGGGG n \n` = 10 + 1 + 5 + 1 + 1 + 1 + 1 = 20 bytes.  Kept in
/// one place so the first-page placeholder block length and the back-patch
/// entry encoder agree.
const CLASSIC_XREF_ENTRY_WIDTH: usize = 20;

/// Byte range (inside the writer's `bytes` buffer) and object-number range that
/// the classic first-page cross-reference subsection reserves for in-place
/// back-patching once every covered object offset is known.
///
/// The classic (stream-free) analogue of [`FirstPageXrefPatch`].  qpdf's
/// linearized first-page `xref` covers the whole first-page section (objects
/// `param_slot..total`), whose offsets are forward references not yet known
/// when the subsection is emitted, so the entries are written as a fixed-width
/// placeholder block and overwritten by [`patch_part1_xref`] after the final
/// pass collects every object offset.
struct Part1XrefPatch {
    /// First object number the subsection covers (`= param_slot`).
    start_num: u32,
    /// Number of entries the subsection covers (`= total − param_slot`).
    count: u32,
    /// Absolute byte range of the fixed-width entry block (overwritten with the
    /// real 20-byte classic entries once offsets are final).
    data_range: std::ops::Range<usize>,
}

/// Write a Part 1 xref subsection covering the whole first-page section plus a
/// first-page trailer, then return `(xref_keyword_offset, prev_value_range,
/// patch)`.
///
/// The Part 1 xref is required by the linearized PDF spec so a viewer can
/// resolve the first page (and the linearization parameter dict) from the
/// leading bytes without parsing the whole file.  Matching qpdf's classic
/// (stream-free) layout, the subsection header is `xref {param_slot}
/// {total − param_slot}` and it covers the high-numbered first-page objects
/// (param dict, catalog, hint stream, first page, and page-1 private objects).
/// The low-numbered "rest" objects (other pages, the Pages tree, Info) are
/// recorded by the main (Part 6) xref instead.
///
/// Only the param-dict object's offset is known when this runs; the rest are
/// forward references.  The entry block is therefore emitted as a fixed-width
/// placeholder (`count × `[`CLASSIC_XREF_ENTRY_WIDTH`]) and back-patched in
/// place by [`patch_part1_xref`] once the final pass has every offset. Because
/// the block byte length is invariant, no downstream offset shifts when the
/// complete hint object is spliced between the two passes.
///
/// The first-page trailer includes `/Info` (when present), `/Root`, `/Size`,
/// `/Prev`, and `/ID` — matching qpdf's key order and content for linearized
/// PDFs.  The `/Prev` value is written as a left-justified decimal integer
/// padded on the right with spaces to [`PREV_PLACEHOLDER_WIDTH`] bytes so it
/// can be back-patched in-place once the Part 6 xref offset is known.  When
/// `encrypt_ctx` is `Some`, `/Encrypt {N} 0 R` is written immediately after
/// `/ID` — qpdf's `writeTrailer` writes `/ID` first, then, for every trailer
/// form except `t_lin_second` (the main/second-half trailer),
/// ` /Encrypt {objid} 0 R` (QPDFWriter.cc:1224-1231). Verified empirically against qpdf
/// 11.9.0 (`qpdf --linearize --static-id --static-aes-iv --encrypt "" "" 128
/// --use-aes=y`), whose first-page trailer ends `... /ID [<...><...>]
/// /Encrypt 4 0 R >>`.
///
/// Returns `(xref_keyword_offset, prev_value_byte_range, patch)`.
#[allow(clippy::too_many_arguments)]
fn write_part1_xref_and_trailer(
    out: &mut OutputSink<'_>,
    param_dict_obj_number: u32,
    total_object_count: u32,
    first_page_count: u32,
    catalog_new_ref: ObjectRef,
    info_new_ref: Option<ObjectRef>,
    source_trailer: &ObjectHandle,
    canonical_entries: &[(Vec<u8>, Vec<u8>)],
    map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
    removed_refs: &BTreeSet<QpdfObjGen>,
    id_writer: Option<crate::pdf_syntax::ReborrowableIdWriter>,
    encrypt_ctx: Option<&crate::writer::EncryptionContext>,
    pass1: bool,
    final_xref_offsets: Option<&BTreeMap<u32, usize>>,
    final_prev: Option<usize>,
) -> Result<(usize, std::ops::Range<usize>, Option<Part1XrefPatch>)> {
    // The param-dict object's trailing pad (reserved by `Part1Bytes::build`)
    // ends with spaces; qpdf starts the first-page `xref` on a fresh line, so
    // emit the line-break separator here.  This lands the `xref` keyword at
    // qpdf's fixed offset (216 for the 15-byte header) once the pad width is
    // taken into account.
    if out.last_byte() != Some(b'\n') {
        out.write_bytes(b"\n")?;
    }
    let xref_offset = out.position_usize()?;

    // Subsection: the whole first-page section (objects param_slot..total).
    out.write_bytes(format!("xref\n{param_dict_obj_number} {first_page_count}\n").as_bytes())?;
    // Fixed-width placeholder block: `first_page_count` classic entries, each
    // CLASSIC_XREF_ENTRY_WIDTH bytes.  The offsets are forward references, so
    // patch_part1_xref overwrites this block in place once they are known.
    // Its byte length is invariant (it never depends on the offsets it carries),
    // so no downstream byte shifts.
    let patch = if pass1 {
        for _ in 0..first_page_count {
            out.write_bytes(b"0000000000 00000 n \n")?;
        }
        None
    } else if let Some(xref_offsets) = final_xref_offsets {
        // cov:ignore-start: validated final layout contains every first-page object offset
        for number in param_dict_obj_number..param_dict_obj_number + first_page_count {
            let offset = xref_offsets.get(&number).copied().ok_or_else(|| {
                crate::Error::Unsupported(format!(
                    "Part-1 xref: covered object {number} has no final offset"
                ))
            })?;
            out.write_bytes(format!("{offset:010} 00000 n \n").as_bytes())?;
        }
        // cov:ignore-end
        None
    } else {
        let data_start = out.position_usize()?;
        let data_len = (first_page_count as usize)
            .checked_mul(CLASSIC_XREF_ENTRY_WIDTH)
            .ok_or_else(|| {
                // cov:ignore-start: first_page_count is a u32 and supported
                // targets have enough usize capacity for these fixed entries;
                // this is defensive overflow handling.
                crate::Error::Unsupported(
                    "Part-1 xref placeholder length exceeds usize range".to_string(),
                )
            })?; // cov:ignore-end
        write_repeated_bytes(out, b' ', data_len)?;
        Some(Part1XrefPatch {
            start_num: param_dict_obj_number,
            count: first_page_count,
            data_range: data_start..data_start + data_len,
        })
    };

    // First-page trailer for Part 1. qpdf emits the live trimmed trailer keys
    // in decoded-name order, inserts `/Prev` immediately after `/Size`, and
    // appends `/ID` and `/Encrypt` after the ordinary keys. The values in
    // `canonical_entries` came from the live ObjectHandle graph; raw bytes are
    // limited to this fixed linearization framing and its back-patch field.
    out.write_bytes(b"trailer << ")?;

    let mut entries = canonical_entries.to_vec();
    if let Some(info_ref) = info_new_ref {
        entries.push((
            b"/Info".to_vec(),
            format!("{} {} R", info_ref.number, info_ref.generation).into_bytes(),
        ));
    }
    entries.push((
        b"/Root".to_vec(),
        format!(
            "{} {} R",
            catalog_new_ref.number, catalog_new_ref.generation
        )
        .into_bytes(),
    ));
    entries.push((
        b"/Size".to_vec(),
        total_object_count.to_string().into_bytes(),
    ));
    entries.sort_by(|left, right| left.0.cmp(&right.0));

    let mut prev_value_range = None;
    for (key, value) in entries {
        out.write_bytes(b"/")?;
        crate::pdf_syntax::write_name_escaped(out, key.strip_prefix(b"/").unwrap_or(&key))?;
        out.write_bytes(b" ")?;
        out.write_bytes(&value)?;
        if key == b"/Size" {
            // `/Prev` is known from qpdf's pass-1 second-xref coordinate in
            // the forward final pass. The placeholder remains only for the
            // in-memory compatibility path that still exercises the legacy
            // back-patcher directly.
            out.write_bytes(b" /Prev ")?;
            let prev_value_start = out.position_usize()?;
            let placeholder = format!("{:<PREV_PLACEHOLDER_WIDTH$}", final_prev.unwrap_or(0));
            out.write_bytes(placeholder.as_bytes())?;
            if final_prev.is_none() {
                prev_value_range = Some(prev_value_start..out.position_usize()?);
            }
        } else {
            out.write_bytes(b" ")?;
        }
    }

    // No separator space before `/ID`: the fixed-width `/Prev` placeholder's
    // trailing pad already separates the value, exactly as qpdf writes it.
    out.write_bytes(b"/ID ")?;
    let id_value = source_trailer.try_get_key(b"/ID")?;
    match id_writer {
        Some(write_id) => write_id(out),
        None => id_value.write_id_value_with_qpdf_obj_gen_map(out, map, removed_refs),
    }?; // cov:ignore: direct trailer ID serialization is validated by canonical handle tests

    // /Encrypt — reference to the `/Encrypt` dictionary object, written right
    // after `/ID` (qpdf `writeTrailer` writes `/ID` first, then — for every
    // trailer form except `t_lin_second`, the main/second-half trailer —
    // ` /Encrypt {objid} 0 R`, QPDFWriter.cc:1224-1231). The main (Part-6)
    // trailer is produced by `write_main_xref_and_trailer`, a separate
    // function that never receives `encrypt_ctx`, so that omission is
    // structural rather than a runtime branch here.
    if let Some(ctx) = encrypt_ctx {
        out.write_bytes(
            format!(
                " /Encrypt {} {} R",
                ctx.encrypt_ref.number, ctx.encrypt_ref.generation
            )
            .as_bytes(),
        )?; // cov:ignore: encrypted linearization trailer framing errors are defensive output failures
    }

    out.write_bytes(b" >>")?;
    // Per linearized PDF convention (ISO 32000-1 Annex F and qpdf practice),
    // the Part 1 first trailer's startxref value is always 0.  The main xref
    // at the end of the file (Part 6) carries the real byte offset in its own
    // trailing startxref, so readers that follow the tail-startxref path are
    // unaffected.  qpdf uses 0 here to signal "this is the first trailer of a
    // linearized file"; we adopt the same convention for byte-identical output.
    out.write_bytes(b"\nstartxref\n0\n%%EOF\n")?;

    let prev_value_range = match (prev_value_range, final_prev) {
        (Some(range), _) => range,
        (None, Some(_)) => 0..0,
        (None, None) => {
            // cov:ignore-start: /Size is inserted unconditionally above.
            return Err(crate::Error::Unsupported(
                "linearization first trailer has no /Size entry for /Prev patch".to_string(),
            ));
            // cov:ignore-end
        }
    };
    Ok((xref_offset, prev_value_range, patch))
}

/// Overwrite the classic first-page xref subsection's placeholder entry block
/// in place, now that every covered object offset is known.
///
/// The subsection covers objects `[start_num, start_num + count)` — the whole
/// first-page section — all of which are plain indirects on the classic path,
/// so the encoder needs only the final `xref_offsets` map.  Because the block
/// was emitted at its final byte length, this is a pure in-place patch: no
/// offset shifts occur when the complete hint object is spliced.
///
/// # Errors
///
/// Returns [`crate::Error::Unsupported`] if a covered object number has no
/// entry in `xref_offsets` (a planner / writer inconsistency that would
/// otherwise emit a free entry for a live object), or if the patch range lies
/// outside `bytes`.
fn patch_part1_xref(
    out: &mut OutputSink<'_>,
    patch: &Part1XrefPatch,
    xref_offsets: &BTreeMap<u32, usize>,
) -> Result<()> {
    if patch.data_range.end > out.position_usize()? {
        return Err(crate::Error::Unsupported(
            "Part-1 xref patch range out of bounds".to_string(),
        ));
    }
    let mut data = Vec::with_capacity(patch.count as usize * CLASSIC_XREF_ENTRY_WIDTH);
    for number in patch.start_num..patch.start_num + patch.count {
        let offset = xref_offsets.get(&number).copied().ok_or_else(|| {
            crate::Error::Unsupported(format!(
                "Part-1 xref: covered object {number} has no offset (planner / writer \
                 inconsistency — would emit a free entry for a live first-page object)"
            ))
        })?;
        data.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
    }
    if data.len() != patch.data_range.len() {
        return Err(crate::Error::Unsupported(format!(
            "Part-1 xref payload length drift: encoded {} bytes, reserved {}",
            data.len(),
            patch.data_range.len()
        )));
    }
    out.patch_bytes(patch.data_range.clone(), &data)
}

/// Write the main (Part 6) cross-reference table — covering only the
/// low-numbered "rest" objects `[0, param_slot)` — followed by the main
/// trailer and the file's trailing `startxref`/`%%EOF`.
///
/// Matching qpdf's classic linearized layout, the main xref records object 0
/// (the free head) and objects `1..param_slot` (the other pages, the Pages
/// tree, and Info — the objects physically after `/E`).  The high-numbered
/// first-page objects `[param_slot, total)` are recorded by the Part-1
/// first-page xref instead.
///
/// The main trailer is `<< /Size {param_slot} /ID .. >>`: no `/Root` and no
/// `/Info` (qpdf omits both here — the first-page trailer carries them).  `/ID`
/// is still emitted: a file identifier is file-scoped, so the trailer a reader
/// resolves via the trailing `startxref` must advertise the same identifier the
/// first-page trailer carries.  The keys are written as raw bytes (not via
/// `Dictionary::write_pdf`, which alphabetizes) to preserve qpdf's key order
/// `/Size /ID`.
///
/// The trailing `startxref` points at `first_page_xref_offset` — the first-page
/// `xref` keyword near the top of the file — not at the main xref.  qpdf chains
/// a linearized reader: trailing `startxref` → first-page xref → its `/Prev` →
/// main xref.
///
/// Returns `(xref_keyword_offset, xref_first_entry_offset)` where:
/// - `xref_keyword_offset` is the byte offset of the `xref` keyword
/// - `xref_first_entry_offset` is the byte offset of the first xref entry
///   (after the `xref\n0 N\n` header), which is the correct `/T` value per
///   qpdf's linearization checker.
#[allow(clippy::too_many_arguments)]
fn write_main_xref_and_trailer(
    out: &mut OutputSink<'_>,
    xref_offsets: &BTreeMap<u32, usize>,
    param_slot: u32, // /Size of the main subsection — covers objects [0, param_slot)
    first_page_xref_offset: usize,
    source_trailer: &ObjectHandle,
    map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
    removed_refs: &BTreeSet<QpdfObjGen>,
    id_writer: Option<crate::pdf_syntax::ReborrowableIdWriter>,
) -> Result<(usize, usize)> {
    let xref_start = out.position_usize()?;

    // Dense table: objects 0 .. param_slot (the low-numbered "rest" objects).
    let xref_header = format!("xref\n0 {}\n", param_slot);
    out.write_bytes(xref_header.as_bytes())?;
    let xref_first_entry_offset = out.position_usize()?;
    // Object 0 — free head.
    out.write_bytes(b"0000000000 65535 f \n")?;
    for number in 1..param_slot {
        match xref_offsets.get(&number) {
            Some(offset) => out.write_bytes(format!("{:010} 00000 n \n", offset).as_bytes())?,
            None => out.write_bytes(b"0000000000 65535 f \n")?,
        }
    }

    // Main trailer.  Written as raw bytes (not Dictionary::write_pdf, which
    // alphabetizes) to keep qpdf's key order /Size /ID.  No /Root or /Info —
    // qpdf omits both from the main trailer of a classic linearized file.
    out.write_bytes(b"trailer << ")?;
    out.write_bytes(format!("/Size {} ", param_slot).as_bytes())?;
    // /ID — emit the file-scoped identifier verbatim (the same value the
    // Part-1 trailer carries), so the trailer a reader resolves via the
    // trailing `startxref` advertises the identifier.
    out.write_bytes(b"/ID ")?;
    let id_value = source_trailer.try_get_key(b"/ID")?;
    match id_writer {
        Some(write_id) => write_id(out),
        None => id_value.write_id_value_with_qpdf_obj_gen_map(out, map, removed_refs),
    }?; // cov:ignore: direct trailer ID serialization is validated by canonical handle tests
    out.write_bytes(b" >>")?;
    out.write_bytes(format!("\nstartxref\n{}\n%%EOF\n", first_page_xref_offset).as_bytes())?;

    Ok((xref_start, xref_first_entry_offset))
}

/// Byte ranges (inside the writer's `bytes` buffer) the first-page xref stream
/// reserves for in-place back-patching once every downstream object offset and
/// the main (Part-6) xref offset are known.
struct FirstPageXrefPatch {
    /// Object number the first-page xref stream itself was assigned.
    first_xref_num: u32,
    /// First object number the stream's `/Index` covers (= the second-half
    /// object count, the half-split point).
    index_start: u32,
    /// Number of dense-table entries the stream covers: the first half,
    /// `[index_start, index_start + index_count)`.
    index_count: u32,
    /// Fixed byte region reserved for the object (qpdf's pass-1 sizing). The
    /// object header sits at `region.start` — the value the main xref's `/Prev`
    /// and the file's trailing `startxref` point at. [`patch_first_page_xref`]
    /// overwrites the whole region with the real encoded object plus trailing
    /// space padding, so the next object's offset is independent of the payload
    /// length and the later hint-object splice is unaffected.
    region: std::ops::Range<usize>,
    /// `/Root` reference for the rebuilt dict.
    catalog_new_ref: ObjectRef,
    /// `/Info` reference, when the source trailer carries one.
    info_new_ref: Option<ObjectRef>,
    /// `/Size` value (highest object number + 1).
    size: u32,
    /// Trailer `/ID` placeholder bytes `(id0, id1)`, written into the rebuilt
    /// dict so the deterministic-`/ID` back-patch finds them afterwards.
    id: Option<(Vec<u8>, Vec<u8>)>,
    /// Live trailer entries serialized through the canonical ObjectHandle
    /// graph. Writer-owned keys are added separately by the xref serializer.
    canonical_entries: Vec<(Vec<u8>, Vec<u8>)>,
    /// Trailer `/Encrypt` reference on the first-page xref stream. The main
    /// linearization xref stream intentionally omits this (`t_lin_second`).
    encrypt: Option<ObjectRef>,
    /// Highest object number (sizes field 2 alongside the max offset).
    max_id: u32,
    /// Largest object-stream member index (sizes field 3 of `/W`).
    max_ostream_index: u64,
    /// Whether the generated xref stream uses predictor + Flate filtering.
    filtered: bool,
}

struct FinalFirstPageXref<'a> {
    member_new: &'a BTreeMap<u32, (u32, u32)>,
    main_xref_offset: usize,
}

/// Return the live trailer entries that the linearization xref dictionary may
/// carry in addition to its writer-owned structural fields.
///
/// qpdf's `getTrimmedTrailer` walks the live trailer handle, while the
/// linearization writer supplies `/Info`, `/Root`, `/Size`, `/Prev`, `/ID`, and
/// `/Encrypt` at the xref/trailer boundary. Keep those generated keys out of
/// this list so they cannot be duplicated. Values are serialized through the
/// canonical handle graph and mapped into output-number space; only the xref
/// dictionary's fixed framing and key order remain raw layout.
///
/// A value that is itself an indirect handle is never dereferenced here: qpdf's
/// `writeTrailer` unparses each surviving key through `unparseChild`
/// (`QPDFWriter.cc:1143-1155`), which branches solely on `child.isIndirect()`
/// and, when true, writes the renumbered `"N 0 R"` token without ever
/// inspecting what that reference resolves to -- an indirect stream target is
/// no exception, so this mirrors that check before falling back to the
/// generic handle-graph unparse used for direct values. Same split as the
/// plain writer's sibling `canonical_trailer_entries`
/// (`crates/flpdf/src/writer/plain/plan.rs`).
fn canonical_linearization_trailer_entries(
    trailer: &ObjectHandle,
    map: &dyn Fn(QpdfObjGen) -> Result<ObjectRef>,
    removed_refs: &BTreeSet<QpdfObjGen>,
) -> Result<Vec<(Vec<u8>, Vec<u8>)>> {
    let entries = trailer.try_as_dictionary()?.unwrap_or_default();
    let mut serialized = Vec::with_capacity(entries.len());
    for (key, value) in entries {
        if matches!(
            key.as_slice(),
            b"/ID"
                | b"/Encrypt"
                | b"/Info"
                | b"/Prev"
                | b"/Root"
                | b"/Size"
                | b"/Type"
                | b"/W"
                | b"/Index"
                | b"/Length"
                | b"/Filter"
                | b"/DecodeParms"
                | b"/XRefStm"
        ) {
            continue;
        }
        let removed = value.qpdf_obj_gen().is_some_and(|object_gen| {
            !object_gen.is_indirect() || removed_refs.contains(&object_gen)
        });
        if removed || value.try_is_null()? {
            continue;
        }
        let mut value_bytes = Vec::new();
        if let Some(object_gen) = value.qpdf_obj_gen() {
            let mapped = map(object_gen)?;
            value_bytes.extend_from_slice(mapped.to_string().as_bytes());
        } else {
            crate::writer::output::with_buffer_sink(&mut value_bytes, |out| {
                value.write_object_with_qpdf_obj_gen_map_and_removed(out, map, removed_refs)
            })?;
        }
        serialized.push((key, value_bytes));
    }
    Ok(serialized)
}

/// Return the first-page xref subsection length for a linearization layout.
///
/// The subtraction is normally guaranteed by the contiguous slot allocation,
/// but malformed hand-built layouts must fail before any xref bytes are emitted.
pub(crate) fn first_page_xref_object_count(
    total_count: u32,
    param_dict_obj_number: u32,
) -> Result<u32> {
    total_count
        .checked_sub(param_dict_obj_number)
        .ok_or_else(|| {
            crate::Error::Unsupported(format!(
                "linearization writer: param-dict object number ({param_dict_obj_number}) \
             exceeds /Size ({total_count}) — cannot size the first-page xref subsection"
            ))
        })
}

/// Compute the linearized output's `/ID` **once per save**.
///
/// A PDF file identifier is file-scoped: every trailer / xref-stream dict in
/// one linearized output must carry the *same* `/ID`.  `write_linearized`
/// calls this exactly once and stores the result on the working
/// `source_trailer` so the Part-1 trailer and all split xref/trailers emit an
/// identical identifier (previously each site regenerated a fresh random /ID,
/// producing inconsistent identifiers within a single file).
///
/// Policy mirrors `crate::writer`:
///   - `--deterministic-id` without `--static-id`: a fixed-width all-zero placeholder
///     `[<0×32><0×32>]` installed here so pass 1 (which only measures object
///     byte lengths) emits a fixed-width `/ID`. The real two-level
///     identifier cannot be known until the bytes exist, so it is computed from
///     a digest over a reconstruction of qpdf's first write pass. The classic
///     (stream-free) path then **direct-writes** that identifier at every `/ID`
///     site in the final pass (qpdf's 2-pass scheme), so the placeholder never
///     reaches the finished output. The ObjStm / xref-stream path also emits
///     the computed identifier directly from the final trailer view. The
///     identifier has the same width as the placeholder, so every later byte
///     offset (`startxref`, hint stream, xref offsets) is unchanged.
///   - `--static-id`: `[source_id0_or_π, π_const]`, with an empty source
///     `/ID[0]` falling back to the same pi value
///     (when both flags are set, this static form takes precedence)
///   - default: a fresh changing identifier; a non-empty source `/ID[0]` is
///     preserved, otherwise the same fresh value is used for both elements
///     (ISO 32000-1 §14.4).
fn finalize_linearized_id(
    options: &WriterOptions,
    source_id0: Option<&[u8]>,
    det_id_source_id0: Option<&[u8]>,
    copy_encryption: Option<&crate::encryption::CopyEncryptionSource>,
) -> ObjectHandle {
    if crate::writer::uses_deterministic_id(options) {
        // Size the all-zero permanent-identifier placeholder to the source
        // `/ID[0]` length so the serialized `/ID` array reaches its FINAL width
        // here, before the two layout passes. qpdf preserves `/ID[0]` verbatim
        // regardless of length; both the pass-1 digest buffer and the probe
        // passes that measure `/L`, `/H`, the hint stream, and the xref offsets
        // serialize this placeholder, so any width other than the final one
        // would shift every downstream offset. The length is taken from the
        // already-captured source `/ID[0]` (`None` -> 16, the fallback changing
        // identifier's width), which matches what the writer emits.
        let len0 = det_id_source_id0.map(<[u8]>::len).unwrap_or(16);
        ObjectHandle::array(vec![
            ObjectHandle::string(vec![0u8; len0]),
            ObjectHandle::string(vec![0u8; 16]),
        ])
    } else if let Some(source) = copy_encryption {
        let generated = crate::writer::generate_id_handle(None, options.static_id);
        let id1 = generated
            .as_array()
            .and_then(|values| values.get(1).and_then(ObjectHandle::as_string))
            .unwrap_or_else(|| source.id0.clone());
        ObjectHandle::array(vec![
            ObjectHandle::string(source.id0.clone()),
            ObjectHandle::string(id1),
        ])
    } else {
        crate::writer::generate_id_handle(source_id0, options.static_id)
    }
}

/// Build qpdf's pass-1 `/ID` placeholder from the original trailer.
///
/// `QPDFWriter::writeTrailer` (qpdf 11.9.0, lines 1197-1213) ignores the
/// selected final-ID policy during linearization pass 1. It writes an all-zero
/// first string with the same byte width as the original `/ID[0]` (falling
/// back to 16 bytes when there is no non-empty original identifier), followed
/// by a 16-byte all-zero changing identifier.
fn linearization_pass1_id(source_id0: Option<&[u8]>) -> ObjectHandle {
    let first_len = source_id0.map(|id| id.len()).unwrap_or(16);
    ObjectHandle::array(vec![
        ObjectHandle::string(vec![0u8; first_len]),
        ObjectHandle::string(vec![0u8; 16]),
    ])
}

/// Reserve the **first-page (Part-1) cross-reference stream**'s fixed byte
/// region at its proper position — physically inside the first-page region,
/// *before* `/E`, in the slot where the classic Part-1 mini-xref + first trailer
/// would otherwise go (a linearized reader resolves page 1 from the leading
/// bytes, so emitting this only at EOF would defeat linearization).
///
/// The region size is qpdf's pass-1 sizing ([`xref_stream::first_pass_region_len`]):
/// the byte length of an uncompressed, wide-field xref object plus
/// [`xref_stream::calculate_xref_stream_padding`]. Because the wide field is
/// forced (`1 << 25`), the region is independent of the hint length, so it stays
/// constant across both layout passes. A space placeholder of exactly that
/// length is written here;
/// [`patch_first_page_xref`] overwrites it with the real encoded object (qpdf
/// `/W [1 2 1]`, with `/Predictor 12` when filtered) plus trailing space padding once every
/// downstream offset (and the main xref offset for `/Prev`) is known — the region
/// length never changes, so no later byte shifts.
///
/// This stream is the **target of the file's trailing `startxref`** and holds
/// `/Prev → main xref` (qpdf's first-half → main chain direction); the main
/// (Part-6) xref at EOF carries no `/Prev`, so the chain is acyclic. Its
/// `/Index [second_half_count, first_half_count)` covers the FIRST-half objects.
//
// qpdf's `writeTrailer` emits `/Encrypt` immediately after `/ID` for every
// linearization trailer except `t_lin_second` (QPDFWriter.cc:1160-1231).
// `XrefStreamDict::encrypt` is an opt-in field because the same serializer is
// also used by the plain writer, whose xref-stream trailer has no such entry.
#[allow(clippy::too_many_arguments)]
fn write_first_page_xref_stream(
    out: &mut OutputSink<'_>,
    xref_offsets: &mut BTreeMap<u32, usize>,
    relocation: &ObjStmRelocation,
    total_count: u32, // /Size (relocated renumber.len() + 1) — already final
    catalog_new_ref: ObjectRef,
    info_new_ref: Option<ObjectRef>,
    source_trailer: &ObjectHandle,
    canonical_entries: &[(Vec<u8>, Vec<u8>)],
    max_ostream_index: u64,
    filtered: bool,
    encrypt: Option<ObjectRef>,
    pass1: bool,
    final_layout: Option<FinalFirstPageXref<'_>>,
) -> Result<FirstPageXrefPatch> {
    let final_size = total_count;
    let first_xref_num = relocation.first_xref_slot;
    // First-half range: objects `[second_half_count, /Size)`.
    let index_start = relocation.second_half_count;
    // cov:ignore-start: unreachable invariant — `second_half_count`
    // (index_start) is the count of second-half objects and `total_count`
    // (final_size) is the full /Size, so index_start <= final_size always holds;
    // the guard is defence-in-depth against a renumber/relocation inconsistency.
    let index_count = final_size.checked_sub(index_start).ok_or_else(|| {
        crate::Error::Unsupported(
            "first-page xref /Index underflow (second-half count exceeds /Size)".to_string(),
        )
    })?;
    // cov:ignore-end
    let max_id = final_size.saturating_sub(1);
    let id = xref_id_bytes(source_trailer)?;
    let obj_ref = ObjectRef::new(first_xref_num, 0);

    // Reserve the fixed pass-1 region (qpdf's writePad length-stabilisation):
    // the forced wide field-2 (`1 << 25`) makes the region independent of the
    // hint length, so it is constant across both layout passes. The real
    // compressed object plus
    // trailing padding is written into the region by `patch_first_page_xref`
    // once every downstream offset (and the main xref offset for `/Prev`) is
    // known — so the region's byte length never changes and no later offset
    // shifts.
    let region_len = {
        let dict = xref_stream::XrefStreamDict {
            filtered,
            widths: xref_stream::first_pass_widths(max_id, max_ostream_index, 0),
            index: Some((index_start, index_count)),
            info: info_new_ref,
            root: Some(catalog_new_ref),
            root_value: None,
            live_root_value: None,
            size: final_size,
            prev: Some(0),
            canonical_entries: Some(canonical_entries),
            live_trailer: None,
            live_map: None,
            live_removed_refs: None,
            id: id.as_ref().map(|(a, b)| (a.as_slice(), b.as_slice())),
            encrypt,
        };
        xref_stream::first_pass_region_len(obj_ref, &dict, index_count as usize)
    };

    // The param-dict object's trailing pad (reserved by `Part1Bytes::build`) ends
    // with spaces; qpdf starts the first-page xref stream on a fresh line, so emit
    // the line-break separator here (the classic path's analogue is in
    // `write_part1_xref_and_trailer`). This lands the object at qpdf's offset.
    if out.last_byte() != Some(b'\n') {
        out.write_bytes(b"\n")?;
    }
    let obj_offset = out.position_usize()?;
    let patch = FirstPageXrefPatch {
        first_xref_num,
        index_start,
        index_count,
        region: obj_offset..obj_offset + region_len,
        catalog_new_ref,
        info_new_ref,
        size: final_size,
        id,
        canonical_entries: canonical_entries.to_vec(),
        encrypt,
        max_id,
        max_ostream_index,
        filtered,
    };
    xref_offsets.insert(first_xref_num, obj_offset);
    if pass1 {
        let (region, _) =
            build_first_page_xref_region(&patch, xref_offsets, &BTreeMap::new(), 0, 0, true)?;
        out.write_bytes(&region)?;
    } else if let Some(final_layout) = final_layout {
        // The final xref coordinates are known from pass 1 plus the framed
        // hint length. Emit the qpdf-shaped region directly; a non-seekable
        // Writer/Pipeline must never receive a later in-place repair.
        let (region, _) = build_first_page_xref_region(
            &patch,
            xref_offsets,
            final_layout.member_new,
            final_layout.main_xref_offset,
            0,
            false,
        )?; // cov:ignore: pass-1 sizing guarantees the final region fits
        out.write_bytes(&region)?;
    } else {
        // Space placeholder of exactly the region length, then the trailing
        // newline (outside the region, mirroring qpdf). The placeholder is
        // overwritten after the downstream offsets are known.
        write_repeated_bytes(out, b' ', region_len)?;
    }
    out.write_bytes(b"\n")?;

    Ok(patch)
}

/// Extract the trailer `/ID`'s two byte strings — the deterministic-`/ID`
/// all-zero placeholder while writing — for the rebuilt xref-stream dicts. The
/// final-pass trailer view supplies the real identifier directly.
fn xref_id_bytes(source_trailer: &ObjectHandle) -> Result<Option<(Vec<u8>, Vec<u8>)>> {
    let id = source_trailer.try_get_key(b"/ID")?;
    let Some(values) = id.try_as_array()? else {
        return Ok(None);
    };
    if values.len() != 2 {
        return Ok(None);
    }
    let (first, second) = (&values[0], &values[1]);
    Ok(match (first.as_string(), second.as_string()) {
        (Some(first), Some(second)) => Some((first, second)),
        _ => None,
    })
}

/// Overwrite the first-page xref stream's reserved region with the real encoded
/// object once every downstream offset (and the main xref offset for `/Prev`)
/// is known.
///
/// The object is rebuilt from scratch — entries from `xref_offsets` /
/// `member_new`, qpdf-matching `/W` widths, and policy-selected raw or
/// PNG-`/Predictor 12` + Flate payload,
/// `/Prev → main xref` — then space-padded to the region's fixed byte length
/// ([`xref_stream::write_padded_region`]). Because the region length is fixed
/// (qpdf's pass-1 sizing), this shifts no later offset while the hint object is
/// spliced. The final-pass trailer view carries the final `/ID` bytes directly.
///
/// Returns the absolute byte range (within `bytes`) of the emitted `/ID`
/// array token, translated from [`xref_stream::write_padded_region`]'s
/// region-relative range by `patch.region.start`. The caller records this
/// exact span in `id_ranges` instead of the whole region — the region also
/// carries this object's stream payload and, via `patch.canonical_entries`,
/// arbitrary custom trailer entries without scanning their serialized bytes.
fn build_first_page_xref_region(
    patch: &FirstPageXrefPatch,
    xref_offsets: &mut BTreeMap<u32, usize>,
    member_new: &BTreeMap<u32, (u32, u32)>,
    main_xref_offset: usize,
    _hint_length: usize,
    pass1: bool,
) -> Result<(Vec<u8>, Option<std::ops::Range<usize>>)> {
    // The first-page xref object's own offset is the region start.
    xref_offsets.insert(patch.first_xref_num, patch.region.start);

    let (stream_layout, prev) = if pass1 {
        // qpdf's pass-1 first-half xref: UNCOMPRESSED, the forced-wide field
        // (`1 << 25` ⇒ `/W [1 4 1]`), `/Prev 0`, and entries only for the objects
        // written BEFORE it (the param dict + the xref object itself); every
        // forward reference is a type-0 zero record, since pass 1 does not
        // back-patch.
        let mut pass1_offs: BTreeMap<u32, usize> = xref_offsets
            .iter()
            .filter(|(_, &off)| off <= patch.region.start)
            .map(|(&n, &off)| (n, off))
            .collect();
        // Pass 1 does not back-patch forward references: every object after the
        // xref — including ObjStm members — is a type-0 zero record, so the
        // member map is empty here (members are not yet "resolved" in pass 1).
        let stream_layout = xref_stream::prepare_xref_stream(
            &mut pass1_offs,
            &BTreeMap::new(),
            patch.index_start,
            patch.index_count,
            patch.first_xref_num,
            patch.region.start,
            0,
            patch.max_id,
            patch.max_ostream_index,
            0,
            None,
            patch.filtered,
            true,
            true,
        )?; // cov:ignore: pass-1 layout errors are defensive pipeline failures.
        (stream_layout, 0u64)
    } else {
        // qpdf's second pass keeps one physical xref map and applies the hint
        // correction while encoding first-half rows. The serializer derives
        // virtual row values in its bounded entry payload; the writer-owned
        // map remains physical and is not cloned.
        let stream_layout = xref_stream::prepare_xref_stream_from_physical_offsets(
            xref_offsets,
            member_new,
            patch.index_start,
            patch.index_count,
            patch.first_xref_num,
            patch.region.start,
            patch.max_id,
            patch.max_ostream_index,
            patch.filtered,
        )?; // cov:ignore: pass-2 layout errors are defensive pipeline failures.
        (stream_layout, main_xref_offset as u64)
    };
    let dict = xref_stream::XrefStreamDict {
        filtered: patch.filtered,
        widths: stream_layout.widths,
        index: Some((patch.index_start, patch.index_count)),
        info: patch.info_new_ref,
        root: Some(patch.catalog_new_ref),
        root_value: None,
        live_root_value: None,
        size: patch.size,
        prev: Some(prev),
        canonical_entries: Some(&patch.canonical_entries),
        live_trailer: None,
        live_map: None,
        live_removed_refs: None,
        id: patch.id.as_ref().map(|(a, b)| (a.as_slice(), b.as_slice())),
        encrypt: patch.encrypt,
    };
    // cov:ignore: the `?` below never fires — write_padded_region errors only if
    // the object exceeds its pass-1-sized region. Filtered final payloads fit
    // inside the wider predicted region; raw payloads retain the same size.
    let (region, region_id_range) = xref_stream::write_padded_region(
        ObjectRef::new(patch.first_xref_num, 0),
        &dict,
        &stream_layout,
        patch.region.len(),
    )?; // cov:ignore: see above — unreachable region-overflow error arm.
    Ok((
        region,
        region_id_range.map(|r| patch.region.start + r.start..patch.region.start + r.end),
    ))
}

/// Patch the final pass's fixed-size first-page xref region through the
/// Vec-backed output target.
fn patch_first_page_xref(
    out: &mut OutputSink<'_>,
    patch: &FirstPageXrefPatch,
    xref_offsets: &mut BTreeMap<u32, usize>,
    member_new: &BTreeMap<u32, (u32, u32)>,
    main_xref_offset: usize,
    hint_length: usize,
) -> Result<Option<std::ops::Range<usize>>> {
    let (region, id_range) = build_first_page_xref_region(
        patch,
        xref_offsets,
        member_new,
        main_xref_offset,
        hint_length,
        false,
    )?; // cov:ignore: the final xref region is validated by qpdf differential tests
    if patch.region.end > out.position_usize()? {
        // cov:ignore-start: unreachable invariant — the region was reserved
        // inside this same output before any later bytes were emitted.
        return Err(crate::Error::Unsupported(
            "first-page xref patch range out of bounds".to_string(),
        ));
        // cov:ignore-end
    }
    out.patch_bytes(patch.region.clone(), &region)?;
    Ok(id_range)
}

/// Emit the **main (second-half) cross-reference stream** at end-of-body,
/// followed by the trailing `startxref`/`%%EOF`.
///
/// `/Index [0, second_half_count]`: the SECOND-half object range
/// `0 ..< second_half_count`, type-0 (the free object 0) then type-1 (the
/// second-half uncompressed objects, the main xref object itself, and the
/// ObjStm container) then type-2 (all ObjStm members) — a single contiguous
/// range with no type-1-after-type-2 interleave under the per-half
/// compressed-last layout.
///
/// The main xref carries **no** `/Prev`: it is the end of qpdf's first-half →
/// main chain (the first-page stream's own `/Prev` points forward here).  The
/// file's trailing `startxref` targets the **first-page** xref (the chain leaf
/// a linearized reader consults first), not this main xref.  Returns
/// `(main_xref_offset, main_xref_offset, id_range)`: the caller computes `/T =
/// main_xref_offset − 1` (via `saturating_sub(1)`), matching qpdf's
/// `xref_zero_offset` (the byte just before the main xref stream object).
/// `id_range` is the absolute byte range (within `bytes`) of the emitted
/// `/ID` array token — see [`patch_first_page_xref`]'s doc for why the caller
/// records this exact span rather than the whole object.
#[allow(clippy::too_many_arguments)]
fn write_main_xref_stream_and_trailer(
    out: &mut OutputSink<'_>,
    xref_offsets: &mut BTreeMap<u32, usize>,
    member_new: &BTreeMap<u32, (u32, u32)>,
    relocation: &ObjStmRelocation,
    total_count: u32, // /Size (placed renumber.len() + 1) — already final
    source_trailer: &ObjectHandle,
    first_page_obj_offset: usize,
    max_ostream_index: u64,
    pass1: bool,
    filtered: bool,
) -> Result<(usize, usize, Option<std::ops::Range<usize>>, usize)> {
    let final_size = total_count;
    let first_xref_num = relocation.first_xref_slot;
    let main_xref_num = relocation.main_xref_slot;
    let max_id = final_size.saturating_sub(1);
    let id = xref_id_bytes(source_trailer)?;

    // Second-half range: objects `[0, second_half_count)`.
    let main_count = relocation.second_half_count;
    let main_xref_offset = out.position_usize()?;
    xref_offsets.insert(first_xref_num, first_page_obj_offset);
    let stream_layout = xref_stream::prepare_xref_stream(
        xref_offsets,
        member_new,
        0,
        main_count,
        main_xref_num,
        main_xref_offset,
        main_xref_offset as u64,
        max_id,
        max_ostream_index,
        0,
        None,
        filtered,
        pass1,
        false,
    )?; // cov:ignore: xref payload setup is a validated in-memory writer boundary.

    // Main (second-half) xref: no `/Index`, `/Info`, `/Root`, or `/Prev` — it is
    // the chain terminal, reached only via the first-page stream's `/Prev`. Its
    // `/Size` is the second-half object COUNT (not the file's total /Size), so
    // the omitted `/Index` defaults to `[0, main_count)` — exactly the objects
    // this stream covers (qpdf's `second_trailer_size`).
    let dict = xref_stream::XrefStreamDict {
        filtered,
        widths: stream_layout.widths,
        index: None,
        info: None,
        root: None,
        root_value: None,
        live_root_value: None,
        size: main_count,
        prev: None,
        canonical_entries: None,
        live_trailer: None,
        live_map: None,
        live_removed_refs: None,
        id: id.as_ref().map(|(a, b)| (a.as_slice(), b.as_slice())),
        encrypt: None,
    };

    // Pad the object to its fixed pass-1 region (qpdf's writePad), then a newline
    // before `startxref`, so the file length is independent of the compressed
    // length. Unlike the first-page stream, the main xref's pass-1 `max_offset`
    // is its OWN offset (`second_xref_offset`) — already known — so qpdf does NOT
    // force the wide 4-byte field here; the region uses the real `/W` widths.
    let main_obj_ref = ObjectRef::new(main_xref_num, 0);
    let region_len = {
        let p1_dict = xref_stream::XrefStreamDict {
            filtered,
            widths: stream_layout.widths,
            index: None,
            info: None,
            root: None,
            root_value: None,
            live_root_value: None,
            size: main_count,
            prev: None,
            canonical_entries: None,
            live_trailer: None,
            live_map: None,
            live_removed_refs: None,
            id: id.as_ref().map(|(a, b)| (a.as_slice(), b.as_slice())),
            encrypt: None,
        };
        xref_stream::first_pass_region_len(main_obj_ref, &p1_dict, main_count as usize)
    };
    let (region, region_id_range) =
        xref_stream::write_padded_region(main_obj_ref, &dict, &stream_layout, region_len)?;
    let region_start = out.position_usize()?;
    out.write_bytes(&region)?;
    out.write_bytes(b"\n")?;
    let id_range = region_id_range.map(|r| region_start + r.start..region_start + r.end);

    // Trailing `startxref` → the **first-page** xref stream (qpdf's chain leaf).
    let second_xref_end = out.position_usize()?;
    out.write_bytes(format!("startxref\n{first_page_obj_offset}\n%%EOF\n").as_bytes())?;

    // `/T` rule for the split linearized file is the byte just before the
    // **main** cross-reference stream (qpdf's `xref_zero_offset`). The caller
    // computes `/T = second_return.saturating_sub(1)`, so return
    // `main_xref_offset` as the second element. The first element is also the
    // main xref offset (used for layout diagnostics / `last_xref`).
    Ok((
        main_xref_offset,
        main_xref_offset,
        id_range,
        second_xref_end,
    ))
}

/// Serialize the hint-stream object dictionary + `stream\n` opener exactly as
/// qpdf 11.9.0 orders it: an optional `/Filter /FlateDecode`, followed by
/// `/S {s}[ /O {o}] /Length {len}`.
/// qpdf emits `/O` between `/S` and `/Length`, and only when the document has
/// outlines (`if (O)`, QPDFWriter.cc:2307); `/S` carries the shared-object
/// section offset, `/O` the outlines section offset (both within the
/// uncompressed hint stream).
///
/// Used by [`append_hint_stream_object`] so the hand-written dictionary keeps
/// qpdf's key order. Stream framing is emitted by the canonical writer
/// pipeline immediately after this prefix.
fn hint_stream_dict_prefix(
    shared_section_offset: usize,
    outline_section_offset: Option<usize>,
    payload_len: usize,
    filtered: bool,
) -> String {
    let filter_key = if filtered {
        "/Filter /FlateDecode "
    } else {
        ""
    };
    let outline_key = match outline_section_offset {
        Some(o) => format!(" /O {o}"),
        None => String::new(),
    };
    format!("<< {filter_key}/S {shared_section_offset}{outline_key} /Length {payload_len} >>")
}

#[cfg(test)]
thread_local! {
    /// Test-only IV queue used to model a probe/final re-encryption regression
    /// without exposing an IV-injection option in the production API. The
    /// queue is thread-local because Rust unit tests run in parallel.
    static TEST_HINT_STREAM_AES_IVS:
        std::cell::RefCell<std::collections::VecDeque<[u8; 16]>> =
        const { std::cell::RefCell::new(std::collections::VecDeque::new()) };
}

#[cfg(test)]
fn next_test_hint_stream_aes_iv(default: [u8; 16]) -> [u8; 16] {
    TEST_HINT_STREAM_AES_IVS.with(|ivs| ivs.borrow_mut().pop_front().unwrap_or(default))
}

/// Emit the primary hint-stream object and return its start byte offset.
///
/// qpdf 11.9.0 serializes the hint-stream object dict in the key order
/// optional `/Filter`, then `/S`, `/O` when present, and `/Length` (observed
/// against its `--check-linearization` golden output), which the generic
/// `BTreeMap`-ordered stream serializer cannot reproduce. This
/// emitter writes the dict literal by hand (via [`hint_stream_dict_prefix`]) to
/// match that order; the surrounding framing (`N G obj\n` … `\nstream\n` …
/// `\nendstream\nendobj\n`) is byte-identical to [`append_object`]. The newline
/// before `endstream` is written only when the payload does not already end in
/// one (qpdf, QPDFWriter.cc:2327). This deliberately does not use the global
/// `newline_before_endstream` option: qpdf's hint-stream helper has this
/// separate conditional framing rule.
///
/// The hint stream IS encrypted when `encrypt_ctx` is `Some` — unlike the
/// `/Encrypt` dict and the xref table/stream, it carries no exemption in
/// qpdf: `writeHintStream` calls `setDataKey(hint_id)` before writing the
/// dict/payload (QPDFWriter.cc:2297), so the emitted `/Length` reflects the
/// *encrypted* byte count. `new_ref` (the hint stream's own reserved object
/// number) is always distinct from `ctx.encrypt_ref` — the `/Encrypt` dict's
/// slot is reserved by inserting immediately before the (then-current) hint
/// slot and shifting the latter by one (`RenumberMap::reserve_encrypt_dict_slot`)
/// — so no self-skip check is needed here, unlike [`append_object`] and
/// [`append_body_object_with_raw_identity`].
///
/// `hint_stream_aes_iv` is used only while constructing this one complete
/// buffer. qpdf encrypts the hint stream once and replays the exact framed
/// bytes on its second layout pass (`QPDFWriter.cc:2860-2884`); the caller
/// follows the same boundary by passing the resulting buffer to
/// [`do_write_pass`] unchanged. It is unused when `encrypt_ctx` is `None` or
/// the cipher is RC4 (no IV concept).
#[allow(clippy::too_many_arguments)]
fn append_hint_stream_object(
    bytes: &mut Vec<u8>,
    new_ref: ObjectRef,
    payload: &[u8],
    shared_section_offset: usize,
    outline_section_offset: Option<usize>,
    filtered: bool,
    encrypt_ctx: Option<&crate::writer::EncryptionContext>,
    hint_stream_aes_iv: [u8; 16],
) -> Result<usize> {
    #[cfg(test)]
    let hint_stream_aes_iv = next_test_hint_stream_aes_iv(hint_stream_aes_iv);

    // qpdf calls `adjustAESStreamLength` after selecting the hint object's data
    // key and before writing its dictionary (`QPDFWriter.cc:2296-2314`). The
    // canonical writer pipeline emits the IV and ciphertext later, but this
    // fixed-width length is needed now for the hand-ordered dictionary.
    let mut payload_len = payload.len();
    if let Some(ctx) = encrypt_ctx {
        crate::writer::adjust_aes_stream_length(&mut payload_len, ctx, true)?;
    }

    let offset = bytes.len();
    bytes.extend_from_slice(format!("{} {} obj\n", new_ref.number, new_ref.generation).as_bytes());
    bytes.extend_from_slice(
        hint_stream_dict_prefix(
            shared_section_offset,
            outline_section_offset,
            payload_len,
            filtered,
        )
        .as_bytes(),
    );
    if let Some(ctx) = encrypt_ctx {
        // qpdf's `writeHintStream` selects the hint object's data key and
        // writes the payload through the encryption pipeline exactly once.
        // Pass 2 receives this complete framed object unchanged, so the
        // explicit IV preserves the same ciphertext across both passes.
        crate::writer::output::with_buffer_sink(bytes, |out| {
            crate::writer::write_stream_payload_with_pipeline_qdf(
                out,
                payload,
                NewlineBeforeEndstream::Never,
                true,
                new_ref,
                ctx,
                true,
                Some(hint_stream_aes_iv),
            )
        })?;
    } else {
        crate::writer::output::with_buffer_sink(bytes, |out| {
            crate::writer::serialize::write_stream_payload_with_qdf(
                out,
                payload,
                NewlineBeforeEndstream::Never,
                true,
            )
        })?;
    }
    bytes.extend_from_slice(b"\nendobj\n");
    Ok(offset)
}

/// Loop-invariant inputs for the Outlines Hint Table (qpdf's `c_outline_data`).
///
/// `first_object` and `nobjects` depend only on membership + renumbering; the
/// pass-1 offset/length are filled in to build the [`OutlineHintTable`].
struct OutlineHintInfo {
    /// Renumbered number of the first outline output unit (the ObjStm container —
    /// or plain object — holding the `/Outlines` dictionary).
    first_object: u32,
    /// Number of distinct outline output units (qpdf's `cho.nobjects`).
    nobjects: u32,
}

/// Compute the loop-invariant Outlines Hint Table inputs, or `None` when the
/// document has no outlines (qpdf then omits the table and the `/O` key).
///
/// Mirrors qpdf's `pushOutlinesToPart` + `calculateHOutline`: the first unit is
/// the object/container holding the `/Outlines` dict, and `nobjects` is the count
/// of distinct output units the outline objects fold into. An outline object
/// that is an ObjStm member folds to its container's new number
/// ([`getUncompressedObject`](https://qpdf.readthedocs.io)); a plain one keeps
/// its own renumbered number.
///
/// # Errors
///
/// Propagates reader errors from catalog resolution.
fn compute_outline_hint_info<R: Read + Seek>(
    outlines: &std::collections::BTreeSet<QpdfObjGen>,
    pdf: &mut Pdf<R>,
    renumber: &RenumberMap,
    objstm_layout: &ObjStmLayout,
) -> Result<Option<OutlineHintInfo>> {
    if outlines.is_empty() {
        return Ok(None);
    }
    // The /Outlines dictionary reference (the first outline unit qpdf places).
    // This helper runs only when the retained outline set is non-empty
    // (therefore a /Outlines key exists),
    // so the catalog is always a resolvable dictionary here.
    let outlines_ref = if let Some(root_ref) = pdf.root_ref() {
        let root = pdf.get_object_handle(root_ref);
        if !root.try_is_dictionary()? {
            None // cov:ignore: catalog is always a dict when outlines exist
        } else {
            let outlines = root.try_get_key(b"/Outlines")?;
            outlines
                .qpdf_obj_gen()
                .filter(|object_gen| object_gen.is_indirect())
        }
    } else {
        None // cov:ignore: a non-empty retained outline set has a Catalog root
    };
    let Some(outlines_ref) = outlines_ref else {
        // Defensive: a non-empty outline closure implies a /Outlines ref, so this
        // is unreachable for a well-formed catalog.
        return Ok(None); // cov:ignore: retained outline set non-empty implies catalog /Outlines ref present
    };
    // Map an outline object to its output unit: its ObjStm container's new number
    // when compressed, else its own renumbered number. The objstm corpus
    // compresses all outline objects, so the plain branch (uncompressed outline,
    // i.e. the deferred plain --linearize path) is not exercised here.
    let unit_of = |object_gen: QpdfObjGen| -> Option<u32> {
        if let Some(object_ref) = object_gen.to_object_ref() {
            if let Some(&(container_num, _)) = objstm_layout.member_to_container.get(&object_ref) {
                return Some(container_num);
            }
        }
        renumber
            .new_for_raw(object_gen)
            .map(|new_ref| new_ref.number)
    };
    let units: std::collections::BTreeSet<u32> = outlines
        .iter()
        .filter_map(|&object_gen| unit_of(object_gen))
        .collect();
    let Some(first_object) = unit_of(outlines_ref) else {
        // Defensive: the /Outlines dict is part of the closure and the plan, so it
        // always has a unit.
        return Ok(None); // cov:ignore: /Outlines dict always has a renumber/container entry
    };
    Ok(Some(OutlineHintInfo {
        first_object,
        nobjects: units.len() as u32,
    }))
}

/// Build the Outlines Hint Table from qpdf's pass-1 measurements
/// (`calculateHOutline`).
///
/// `first_object_offset` is already the pass-1 virtual offset: pass 1 omits
/// the reserved hint object, so qpdf's final `adjusted_offset` adds the exact
/// saved hint-object length back when validating pass 2. `group_length` is the
/// summed byte length of the `nobjects` consecutive output units starting at
/// `first_object` (qpdf's `outputLengthNextN`).
///
/// # Errors
///
/// Returns [`crate::Error::Unsupported`] if the first outline unit has no
/// offset in `xref_offsets` or if the virtual offset exceeds the fixed
/// 32-bit hint-table field.
fn build_outline_hint_table(
    info: &OutlineHintInfo,
    xref_offsets: &BTreeMap<u32, usize>,
    byte_lengths: &BTreeMap<u32, usize>,
) -> Result<OutlineHintTable> {
    let first_off = xref_offsets
        .get(&info.first_object)
        .copied()
        .ok_or_else(|| {
            crate::Error::Unsupported(format!(
                "outline hint: first outline unit (#{}) has no probed offset",
                info.first_object
            ))
        })?;
    // The HGeneric `first_object_offset` is a fixed 32-bit field (qpdf
    // writeHGeneric). Reject (rather than silently truncate) an offset past
    // 4 GiB, matching how the other fixed-width hint fields fail via
    // `write_bits_checked`.
    let first_object_offset = u32::try_from(first_off).map_err(|_| {
        crate::Error::Unsupported(format!(
            "outline hint: pass-1 first unit offset ({first_off}) exceeds the \
             32-bit Outlines Hint Table field"
        ))
    })?;
    // `u64` range bound prevents a `u32` overflow panic on a pathological
    // (>4-billion-object) layout; for any realistic document the values fit in
    // `u32`, so `n as u32` and the sum are byte-identical to the direct
    // computation.
    let group_length: u64 = (info.first_object as u64
        ..info.first_object as u64 + info.nobjects as u64)
        .map(|n| byte_lengths.get(&(n as u32)).copied().unwrap_or(0) as u64)
        .sum();
    Ok(OutlineHintTable {
        first_object: info.first_object,
        first_object_offset,
        nobjects: info.nobjects,
        group_length: group_length as u32,
    })
}

/// Build the pass-1 (digest) variant of an already-built [`Part1Bytes`].
///
/// qpdf's first write pass emits the linearization parameter dict **empty**
/// (`<< >>`) instead of the full `/Linearized 1 /L .. /H [ .. ] /O .. >>` body,
/// but pads the object region to the *same* size so the first-page `xref`
/// keyword still lands at its fixed offset.  We reproduce that by cloning the
/// finalized Part-1 bytes and overwriting the rewritable dict region (`<<`
/// through the trailing pad) in place with `<< >>\nendobj\n` followed by ASCII
/// spaces to refill the region.  The region length is invariant, so `obj1_offset`
/// and every later offset are unchanged.
///
/// The placeholders / writable-region metadata are irrelevant for the digest
/// buffer (it is never back-patched), so they are left as-is on the clone.
fn build_pass1_part1(part1: &Part1Bytes) -> Part1Bytes {
    // Empty-dict object body exactly as qpdf's pass 1 writes it.
    const EMPTY_DICT: &[u8] = b"<< >>\nendobj\n";
    let mut pass1 = part1.clone();
    let region = part1.dict_writable_region.clone();
    // The region always holds the full `<< .. >>\nendobj\n` + pad, which is far
    // wider than the empty-dict body; assert so the `resize` below can only ever
    // grow (refill with spaces), never truncate the empty dict.
    debug_assert!(region.len() >= EMPTY_DICT.len());
    let mut replacement = Vec::with_capacity(region.len());
    replacement.extend_from_slice(EMPTY_DICT);
    // Refill to the exact region length with ASCII spaces (qpdf's pad), keeping
    // the region length invariant so no downstream offset shifts.
    replacement.resize(region.len(), b' ');
    pass1.bytes[region].copy_from_slice(&replacement);
    pass1
}

/// Result of one complete linearized layout pass.
///
/// Pass 1 omits the reserved hint object, so its offsets are qpdf's virtual
/// coordinates. The final pass contains the exact hint-object buffer generated
/// from this result.
struct LinearizedPassOutput {
    xref_offsets: BTreeMap<u32, usize>,
    first_page_xref_offset: Option<usize>,
    hint_stream_offset: usize,
    hint_stream_obj_total_len: usize,
    end_of_first_page_offset: usize,
    last_xref_offset: usize,
    last_xref_first_entry_offset: usize,
    second_xref_end: usize,
    first_trailer_prev_range: std::ops::Range<usize>,
    id_ranges: Vec<std::ops::Range<usize>>,
}

/// Final-pass coordinates derived from qpdf's pass-1 measurements.
///
/// qpdf keeps the xref map from the first pass and applies the framed hint
/// object's length when it writes the second pass. Keeping that same map here
/// lets the final pass write its first-page xref and parameter dictionary
/// forward, without reserving a region that must be repaired after the body
/// has already reached a non-seekable sink.
struct FinalLinearizedLayout<'a> {
    xref_offsets: &'a mut BTreeMap<u32, usize>,
    main_xref_offset: usize,
}

/// Perform a complete single-pass write of the linearized PDF body.
///
/// `hint_stream_object` is the complete qpdf-shaped indirect hint object. `None`
/// is qpdf pass 1: the reserved slot is omitted and all objects after it use
/// virtual offsets. `Some` splices the already-encrypted/framed object without
/// re-encoding it. `structural_streams_filtered` controls ObjStm and xref
/// stream filters and payload encodings.
///
/// When `pass1_digest` is set, the buffer reproduces qpdf's *first* write pass —
/// the throwaway buffer qpdf MD5-hashes to seed a linearized `--deterministic-id`
/// (`QPDFWriter::writeLinearized` → `computeDeterministicIDData`, qpdf 11.9.0).
/// That pass differs from the final (second) pass only in length-preserving ways
/// the classic stream-free path can reproduce: the linearization parameter dict
/// is emitted empty (`<< >>` padded to the same region size, supplied via the
/// `part1` argument), the primary hint stream object is **absent** (every object
/// physically after it shifts down by the hint length), and the first-page xref
/// subsection carries formatted zero-offset entries (qpdf never back-patches it
/// in pass 1). `/Prev` and `/ID` are left at their placeholders (`0` and the
/// all-zero array), which is exactly what qpdf's pass-1 buffer contains. The
/// classic body uses the flag for its zeroed first-page xref, while the ObjStm
/// path uses it for qpdf's pass-1 xref-stream representation.
///
/// `encrypt_ctx`, when `Some`, is emitted as a plaintext `/Encrypt` indirect
/// object right after the catalog/open-document-plain objects, in every pass
/// (qpdf writes it unconditionally on `m->encrypted`, independent of pass
/// number — see the call site's doc for the qpdf source reference).
#[allow(clippy::too_many_arguments, clippy::type_complexity)]
fn do_write_pass<R: Read + Seek>(
    plan: &LinearizationPlan,
    renumber: &RenumberMap,
    raw_removed_refs: &BTreeSet<QpdfObjGen>,
    raw_content_normalize_refs: &BTreeSet<QpdfObjGen>,
    pdf: &mut Pdf<R>,
    output: &mut OutputSink<'_>,
    part1: &Part1Bytes,
    catalog_new_ref: ObjectRef,
    hint_stream_new_num: u32,
    total_count: u32,
    info_new_ref: Option<ObjectRef>,
    _first_page_object_new_num: u32,
    hint_stream_object: Option<&[u8]>,
    structural_streams_filtered: bool,
    source_trailer: &ObjectHandle,
    objstm_layout: &ObjStmLayout,
    relocation: &ObjStmRelocation,
    options: &WriterOptions,
    pass1_digest: bool,
    mut id_writer: Option<crate::pdf_syntax::ReborrowableIdWriter>,
    encrypt_ctx: Option<&crate::writer::EncryptionContext>,
    mut encrypted_string_emitter: Option<&mut EncryptedStringEmitter>,
    final_pdf_version: &str,
    final_extension_level: i64,
    final_layout: Option<FinalLinearizedLayout<'_>>,
) -> Result<LinearizedPassOutput> {
    let is_final = final_layout.is_some();
    let final_main_xref_offset = final_layout.as_ref().map(|layout| layout.main_xref_offset);
    let mut local_xref_offsets = BTreeMap::new();
    let xref_offsets: &mut BTreeMap<u32, usize> = match final_layout {
        Some(layout) => layout.xref_offsets,
        None => &mut local_xref_offsets,
    };

    // The classic path emits `/ID` at two sites (Part-1 and main trailers).
    // A `&mut dyn FnMut` cannot be moved into both calls, so reborrow it for the
    // first (`as_deref_mut()`) and move it into the last. Only the classic
    // deterministic-`/ID` final pass supplies `Some`; the ObjStm path leaves it
    // `None` and emits the placeholder for the still-patch-based xref-stream
    // trailers.

    // Part 1
    let param_dict_obj_number = renumber.param_dict_ref().number;
    let param_dict_absolute_offset = part1.obj1_offset;
    output.write_bytes(&part1.bytes)?;
    // qpdf deliberately writes extra header text after the linearization
    // parameter dictionary, rather than in `writeHeader`, so the dictionary
    // remains within the first 1024 bytes (QPDFWriter.cc:2718-2720). The
    // qpdf writes a separator newline after the padded parameter dictionary
    // before the extra header (`QPDFWriter.cc:2714-2720`). The setting has
    // already been normalized with a trailing newline by PdfWriter, matching
    // qpdf's `setExtraHeaderText` contract.
    if !options.extra_header_text.is_empty() {
        output.write_bytes(b"\n")?;
    }
    output.write_bytes(options.extra_header_text.as_bytes())?;
    xref_offsets.insert(param_dict_obj_number, param_dict_absolute_offset);

    // member new-number → (container new-number, index) for the type-2 xref
    // entries.  Built once: the first-page xref stream (emitted just below,
    // before /E) and the main xref stream (emitted at EOF) both consume it.
    let mut member_new: BTreeMap<u32, (u32, u32)> = BTreeMap::new();
    for container in objstm_layout
        .open_document
        .iter()
        .chain(&objstm_layout.part3)
        .chain(&objstm_layout.part4)
    {
        for (idx, &(_orig, new_ref)) in container.members.iter().enumerate() {
            member_new.insert(new_ref.number, (container.container_new_num, idx as u32));
        }
    }
    // Largest object-stream member index across all containers — sizes field 3
    // of the cross-reference streams' `/W` (qpdf's `max_ostream_index`).
    let max_ostream_index: u64 = member_new
        .values()
        .map(|&(_, idx)| u64::from(idx))
        .max()
        .unwrap_or(0);

    let trailer_map = |object_gen| {
        // cov:ignore-start: planner reachability and renumber placement cover every live trailer reference.
        renumber.new_for_raw(object_gen).ok_or_else(|| {
            crate::Error::Unsupported(format!(
                "linearization writer: trailer raw reference {} {} has no renumber entry",
                object_gen.get_obj(),
                object_gen.get_gen()
            ))
        })
        // cov:ignore-end
    }; // cov:ignore: planner-produced trailer map is complete by construction.
    let canonical_entries =
        canonical_linearization_trailer_entries(source_trailer, &trailer_map, raw_removed_refs)?;

    // The classic Part-1 mini-xref + first trailer is only emitted on the
    // non-ObjStm path.  For ObjStm-bearing output the first-page (Part-1)
    // *xref stream* takes its place, and it MUST
    // sit physically here (inside the first-page region, before /E) so a
    // reader can resolve page 1 from the leading bytes.  It is written with a
    // deterministic byte length (uncompressed payload + fixed-width /Prev) and
    // back-patched in place once the downstream offsets and the main (Part-6)
    // xref offset are known (see `patch_first_page_xref` below) — so this shifts
    // no bytes between the two layout passes. Returning an empty
    // `/Prev` range tells the back-patcher there is no classic Part-1 trailer
    // `/Prev` to patch.
    let mut first_page_xref_patch: Option<FirstPageXrefPatch> = None;
    // Classic-path first-page xref: its keyword offset (threaded to the main
    // trailer's `startxref`) and the placeholder block to back-patch once every
    // first-page object offset is known.  qpdf's classic linearized layout
    // makes the file's trailing `startxref` point at this first-page xref, and
    // the first-page xref covers the whole first-page section.
    let mut part1_classic_xref_offset: usize = 0;
    let mut part1_xref_patch: Option<Part1XrefPatch> = None;
    // Absolute byte spans of every section that carries a `/ID`.  The
    // deterministic-`/ID` back-patch scans *only* inside these spans so it can
    // never overwrite a body byte sequence that happens to equal the all-zero
    // `/ID` token. Each span is
    // captured as `start..bytes.len()` around the call that emits its `/ID`.
    let mut id_ranges: Vec<std::ops::Range<usize>> = Vec::new();
    let first_trailer_prev_range = if objstm_layout.is_empty() {
        // First-page xref covers objects [param_slot, total): the param dict
        // plus every other first-page object (catalog, hint, first page, page-1
        // private).  total_count = /Size (highest object number + 1), so the
        // count is `total_count − param_slot`. The helper validates the
        // subtraction before any first-page xref bytes are emitted.
        let first_page_count = first_page_xref_object_count(total_count, param_dict_obj_number)?;
        let section_start = output.position_usize()?;
        let (p1_xref_offset, range, patch) = write_part1_xref_and_trailer(
            output,
            param_dict_obj_number,
            total_count,
            first_page_count,
            catalog_new_ref,
            info_new_ref,
            source_trailer,
            &canonical_entries,
            &trailer_map,
            raw_removed_refs,
            id_writer.as_deref_mut(),
            encrypt_ctx,
            pass1_digest,
            is_final.then_some(&*xref_offsets),
            final_main_xref_offset,
        )?; // cov:ignore: the validated linearization plan makes this serializer error path defensive.
        part1_classic_xref_offset = p1_xref_offset;
        part1_xref_patch = patch;
        // Part-1 first-page trailer `/ID` site.  The main (Part-6) trailer
        // emitted at EOF carries the same `/ID` (its span is captured at
        // the `write_main_xref_and_trailer` call below), so the classic
        // table path has two `/ID` sites — both back-patched together.
        id_ranges.push(section_start..output.position_usize()?);
        range
    } else {
        let final_first_page_layout = if is_final {
            Some(FinalFirstPageXref {
                member_new: &member_new,
                main_xref_offset: final_main_xref_offset.ok_or_else(|| {
                    // cov:ignore-start: final layout always supplies the main xref coordinate
                    crate::Error::Unsupported(
                        "final linearization layout has no main xref offset".to_string(),
                    )
                    // cov:ignore-end
                })?, // cov:ignore: final layout always supplies the main xref coordinate
            })
        } else {
            None
        };
        let patch = write_first_page_xref_stream(
            output,
            xref_offsets,
            relocation,
            total_count,
            catalog_new_ref,
            info_new_ref,
            source_trailer,
            &canonical_entries,
            max_ostream_index,
            structural_streams_filtered,
            encrypt_ctx.map(|ctx| ctx.encrypt_ref),
            pass1_digest,
            final_first_page_layout,
        )?;
        // First-page xref stream object carries one `/ID` (the main xref
        // stream below carries the second). This call only reserves the
        // region as blank padding — the object's real bytes, including its
        // `/ID` token and canonical (custom) trailer entries, are written
        // later by `patch_first_page_xref`, which is the one that reports the
        // token's exact span for `id_ranges` (see that function's doc for why
        // the whole region is not used: it also carries this object's stream
        // payload and, via `canonical_entries`, arbitrary custom trailer
        // entries whose serialized bytes could coincidentally contain the
        // deterministic-`/ID` placeholder's fixed byte pattern).
        first_page_xref_patch = Some(patch);
        0..0
    };

    // Catalog (qpdf `lc_root`).  qpdf emits the document catalog at the very
    // start of the first-page section — physically before the primary hint
    // stream and the page objects — so the first-page region is numbered in
    // ascending order (Catalog, Hint, Page, Resources, ...).  qpdf keeps the
    // catalog uncompressed (a standalone indirect object) in every mode, and
    // the planner enforces this by excluding `/Catalog` from every ObjStm
    // container (see `objstm_batches`).  So the catalog is always a first-half
    // standalone object whose bytes must land in the first-page section before
    // /E to match its first-half object number.
    let mut catalog_emitted_early = false;
    if let Some(catalog_orig) = plan.root_ref {
        debug_assert!(
            !objstm_layout
                .member_to_container
                .contains_key(&catalog_orig),
            "planner invariant: /Catalog is never an ObjStm member"
        );
        // QPDFWriter::writeObject reports progress before unparseObject
        // mutates shared Extensions (QPDFWriter.cc:1773,1794).
        report_progress_event(options)?;
        let catalog = pdf
            .get_object_handle(catalog_orig)
            .output_root_copy_with_adbe(final_pdf_version, final_extension_level, true)?;
        let offset = append_body_object_with_raw_identity(
            output,
            catalog_new_ref,
            QpdfObjGen::try_from_object_ref(catalog_orig)?,
            &catalog,
            options,
            encrypt_ctx,
            encrypted_string_emitter.as_deref_mut(),
            renumber,
            raw_removed_refs,
            raw_content_normalize_refs,
        )?; // cov:ignore: planner-produced Catalog references are valid by construction.
        xref_offsets.insert(catalog_new_ref.number, offset);
        catalog_emitted_early = true;
    }

    // Open-document plain objects and ObjStm containers (qpdf part4). qpdf's
    // enqueueObject emits the object or its source container at the point its
    // assigned object number is encountered (QPDFWriter.cc:1097-1132). That
    // matters for Preserve: a source container can have a lower object number
    // than an ineligible plain stream in the same open-document region. Merge
    // both output kinds and emit by assigned number so the physical order and
    // the hint/xref offsets follow qpdf. Generate containers have no source
    // number and are assigned after the plain objects, so the same ordering
    // also preserves that route.
    enum OpenDocumentEmit<'a> {
        Plain {
            original: ObjectRef,
            new_ref: ObjectRef,
        },
        Raw {
            original: QpdfObjGen,
            new_ref: ObjectRef,
        },
        Container(&'a ObjStmContainer),
    }
    let mut open_document_emits: Vec<(u32, OpenDocumentEmit<'_>)> = Vec::new();
    for original_ref in &plan.part4_open_document_plain {
        // Preserve mode starts from qpdf's source member-to-container map. The
        // linearization plan is built before the resolved ObjStm layout, so an
        // object that is later retained in a source container can still appear
        // in this broad open-document list. qpdf's enqueueObject routes that
        // member through its container and never writes a second plain copy
        // (QPDFWriter.cc:1097-1105); apply the same ownership decision at the
        // final emission boundary. Generate-mode members are not in this list
        // because its planner already separates eligible members from streams.
        if objstm_layout.member_to_container.contains_key(original_ref)
            || objstm_layout
                .source_container_numbers
                .contains(&original_ref.number)
        {
            continue;
        }
        if catalog_emitted_early && plan.root_ref == Some(*original_ref) {
            continue;
        }
        // cov:ignore-start: unreachable invariant — renumber.rs step-6b inserts
        // every part4_open_document_plain ref, so new_for_original is always Some.
        let Some(new_ref) = renumber.new_for_original(*original_ref) else {
            return Err(crate::Error::Unsupported(
                "part4_open_document_plain ref missing from renumber map".into(),
            ));
        };
        // cov:ignore-end
        open_document_emits.push((
            new_ref.number,
            OpenDocumentEmit::Plain {
                original: *original_ref,
                new_ref,
            },
        ));
    }
    for &original_gen in &plan.raw.part4_open_document_plain {
        if original_gen.to_object_ref().is_some() {
            continue;
        }
        let Some(new_ref) = renumber.new_for_raw(original_gen) else {
            // cov:ignore-start: raw plan construction and RenumberMap::from_plan share this vector; absence is an internal invariant failure
            return Err(crate::Error::Unsupported(format!(
                "raw open-document identity {} {} has no renumber entry",
                original_gen.get_obj(),
                original_gen.get_gen()
            )));
        };
        // cov:ignore-end
        open_document_emits.push((
            new_ref.number,
            OpenDocumentEmit::Raw {
                original: original_gen,
                new_ref,
            },
        ));
    }
    for container in &objstm_layout.open_document {
        open_document_emits.push((
            container.container_new_num,
            OpenDocumentEmit::Container(container),
        ));
    }
    open_document_emits.sort_by_key(|(number, _)| *number);
    for (_, emit) in open_document_emits {
        match emit {
            OpenDocumentEmit::Plain { original, new_ref } => {
                let offset = append_body_object_for_ref(
                    output,
                    pdf,
                    new_ref,
                    original,
                    options,
                    encrypt_ctx,
                    encrypted_string_emitter.as_deref_mut(),
                    renumber,
                    raw_removed_refs,
                    raw_content_normalize_refs,
                )?; // cov:ignore: planner-produced open-document references are valid by construction.
                xref_offsets.insert(new_ref.number, offset);
                report_progress_event(options)?;
            }
            OpenDocumentEmit::Raw { original, new_ref } => {
                let offset = append_body_object_for_raw(
                    output,
                    pdf,
                    new_ref,
                    original,
                    options,
                    encrypt_ctx,
                    encrypted_string_emitter.as_deref_mut(),
                    renumber,
                    raw_removed_refs,
                    raw_content_normalize_refs,
                )?; // cov:ignore: planner-produced raw open-document identities are valid by construction.
                xref_offsets.insert(new_ref.number, offset);
                report_progress_event(options)?;
            }
            OpenDocumentEmit::Container(container) => {
                let offset = append_objstm_container_object(
                    output,
                    container,
                    renumber,
                    pdf,
                    raw_removed_refs,
                    options,
                    encrypt_ctx,
                )?; // cov:ignore: error requires an internal planner/renumber inconsistency.
                xref_offsets.insert(container.container_new_num, offset);
                for _ in &container.members {
                    if pass1_digest {
                        decrement_progress_event(options)?;
                    }
                    report_progress_event(options)?;
                    if pass1_digest {
                        // qpdf's writeObjectStream performs an offset-measuring pass
                        // followed by the payload pass inside each outer linearization
                        // pass. The first outer pass therefore reports each member
                        // twice after the decrement, while the final pass's net effect
                        // is one event (QPDFWriter.cc:1639-1707).
                        report_progress_event(options)?;
                    }
                }
            }
        }
    }

    // `/Encrypt` dictionary object (qpdf `writeEncryptionDictionary`, called
    // from `writeLinearized` right after `part4_end_marker` —
    // QPDFWriter.cc:2793-2796). Emitted right after the Part-4
    // (open-document) objects — plain and ObjStm-container — and before the
    // hint stream, matching qpdf's insertion point. qpdf calls
    // `writeEncryptionDictionary` unconditionally on `m->encrypted`, on
    // every pass, so this is not gated on `pass1_digest`. The dict itself is
    // never encrypted (PDF 1.7 §7.6.1 — a reader must parse it before it can
    // derive the file key needed to decrypt anything else). Its five binary
    // security-handler strings use the dedicated compact hexadecimal form.
    if let Some(ctx) = encrypt_ctx {
        let offset = output.position_usize()?;
        output.write_bytes(
            format!(
                "{} {} obj\n",
                ctx.encrypt_ref.number, ctx.encrypt_ref.generation
            )
            .as_bytes(),
        )?; // cov:ignore: encrypted linearization dictionary framing errors are defensive output failures
        crate::writer::encrypted_strings::write_encryption_dictionary_handle(
            output,
            &ctx.encrypt_dict,
        )?; // cov:ignore: LLVM maps this covered encrypted-dictionary continuation to cleanup
        output.write_bytes(b"\nendobj\n")?;
        xref_offsets.insert(ctx.encrypt_ref.number, offset);
    }

    // Hint stream object.
    //
    // In pass-1-digest mode the hint stream is absent (qpdf reserves its xref
    // slot but writes no bytes during pass 1), so every object physically after
    // it shifts down by the hint length.  Skipping the emission here reproduces
    // that shift incrementally — no offset arithmetic.  The slot is also kept
    // out of `xref_offsets`: the first-page xref that covers it is written as
    // formatted zero-offset entries below, so the slot needs no real offset.
    let hint_stream_offset = output.position_usize()?;
    if let Some(hint_stream_object) = hint_stream_object {
        output.write_bytes(hint_stream_object)?;
        xref_offsets.insert(hint_stream_new_num, hint_stream_offset);
    }
    let hint_stream_obj_total_len = output
        .position_usize()?
        .checked_sub(hint_stream_offset)
        .ok_or_else(|| {
            // cov:ignore-start: OutputSink positions are monotonic by
            // construction, so this underflow is a defensive invariant guard.
            crate::Error::Unsupported(
                "linearization hint stream offset moved backwards".to_string(),
            )
        })?; // cov:ignore-end

    // qpdf orders every first-page plain object and Part-3 ObjStm container by
    // the object number assigned during its linearization setup. In particular,
    // an optimization-minted inherited attribute can follow a container that
    // was allocated before optimization. Build one emission list so physical
    // order agrees with RenumberMap and the hint table.
    enum FirstPageEmit<'a> {
        Plain(ObjectRef),
        Raw(QpdfObjGen),
        Container(&'a ObjStmContainer),
    }
    let mut first_page_emits: Vec<(u32, FirstPageEmit<'_>)> = Vec::new();
    for original_ref in plan
        .part2_objects
        .iter()
        .chain(&plan.part3_objects)
        .chain(&plan.part6_outline_objects)
    {
        if objstm_layout.member_to_container.contains_key(original_ref)
            || objstm_layout
                .source_container_numbers
                .contains(&original_ref.number)
            || (catalog_emitted_early && plan.root_ref == Some(*original_ref))
        {
            continue;
        }
        // cov:ignore-start: planner/renumber inconsistency -- impossible by construction, since part2/part3/part6_outline_objects derive from the same renumber plan.
        let Some(new_ref) = renumber.new_for_original(*original_ref) else {
            return Err(crate::Error::Unsupported(format!(
                "first-page object {} has no renumber entry",
                original_ref
            )));
        };
        // cov:ignore-end
        first_page_emits.push((new_ref.number, FirstPageEmit::Plain(*original_ref)));
    }
    for original_gen in plan
        .raw
        .part2_objects
        .iter()
        .chain(&plan.raw.part3_objects)
        .chain(&plan.raw.part6_outline_objects)
        .copied()
        .filter(|object_gen| object_gen.to_object_ref().is_none())
    {
        let Some(new_ref) = renumber.new_for_raw(original_gen) else {
            // cov:ignore-start: raw plan construction and RenumberMap::from_plan share this vector; absence is an internal invariant failure
            return Err(crate::Error::Unsupported(format!(
                "raw first-page identity {} {} has no renumber entry",
                original_gen.get_obj(),
                original_gen.get_gen()
            )));
        };
        // cov:ignore-end
        first_page_emits.push((new_ref.number, FirstPageEmit::Raw(original_gen)));
    }
    for container in &objstm_layout.part3 {
        first_page_emits.push((
            container.container_new_num,
            FirstPageEmit::Container(container),
        ));
    }
    first_page_emits.sort_by_key(|(number, _)| *number);

    for (_, emit) in first_page_emits {
        match emit {
            FirstPageEmit::Plain(original_ref) => {
                let new_ref = renumber
                    .new_for_original(original_ref)
                    .expect("first-page plain object renumber entry checked above");
                let offset = append_body_object_for_ref(
                    output,
                    pdf,
                    new_ref,
                    original_ref,
                    options,
                    encrypt_ctx,
                    encrypted_string_emitter.as_deref_mut(),
                    renumber,
                    raw_removed_refs,
                    raw_content_normalize_refs,
                )?; // cov:ignore: planner-produced first-page references are valid by construction.
                xref_offsets.insert(new_ref.number, offset);
                report_progress_event(options)?;
            }
            FirstPageEmit::Raw(original_gen) => {
                let new_ref = renumber
                    .new_for_raw(original_gen)
                    .expect("raw first-page object renumber entry checked above");
                let offset = append_body_object_for_raw(
                    output,
                    pdf,
                    new_ref,
                    original_gen,
                    options,
                    encrypt_ctx,
                    encrypted_string_emitter.as_deref_mut(),
                    renumber,
                    raw_removed_refs,
                    raw_content_normalize_refs,
                )?; // cov:ignore: planner-produced raw first-page identities are valid by construction.
                xref_offsets.insert(new_ref.number, offset);
                report_progress_event(options)?;
            }
            FirstPageEmit::Container(container) => {
                let offset = append_objstm_container_object(
                    output,
                    container,
                    renumber,
                    pdf,
                    raw_removed_refs,
                    options,
                    encrypt_ctx,
                )?; // cov:ignore: error requires an internal planner/renumber inconsistency.
                xref_offsets.insert(container.container_new_num, offset);
                for _ in &container.members {
                    if pass1_digest {
                        decrement_progress_event(options)?;
                    }
                    report_progress_event(options)?;
                    if pass1_digest {
                        report_progress_event(options)?;
                    }
                }
            }
        }
    }

    // /E: end of first-page section, AFTER Part-2, Part-3, the Part-3
    // ObjStm containers, and Part-6 outline objects (when UseOutlines).
    let end_of_first_page_offset = output.position_usize()?;

    // Part 5 (Annex F): remaining body.  qpdf emits the objects that follow
    // /E (the Pages tree, Info, and any other tail objects) in ascending
    // new-number order.  On the classic path we therefore sort the Part-4
    // refs by their renumbered object number; part7/part8 are already in
    // number order, so this only reorders `part4_rest`.  The catalog, when it
    // was emitted early in the first-page section above, is skipped here so it
    // is not written twice.  ObjStm members are skipped and emitted via their
    // Part-4 container below.  The ObjStm path retains the writer-emission
    // order of `part4_objects()` (its split-xref tail relocation depends on it).
    // Emit the second-half (Annex F Part 5) objects in NEW-NUMBER order, with
    // each Part-4 ObjStm container interleaved at its object-number position
    // among the plain objects — qpdf numbers the second-half uncompressed objects
    // (plain + containers) in part order and writes them in that same order, so a
    // part7 container sits in its owning page's group, NOT after every plain
    // object. (mixed/threepage have a single second-half container that is the
    // last second-half object, so this is identical to the old plain-then-
    // containers emission; disc's part7 container falls in the middle.) Members
    // are written inside their container; the early-written catalog is skipped.
    enum Part4Emit<'a> {
        Plain(ObjectRef),
        Raw(QpdfObjGen),
        Container(&'a ObjStmContainer),
    }
    let mut part4_emits: Vec<(u32, Part4Emit)> = Vec::new();
    for original_ref in plan.part4_objects() {
        if objstm_layout
            .member_to_container
            .contains_key(&original_ref)
            || objstm_layout
                .source_container_numbers
                .contains(&original_ref.number)
        {
            continue;
        }
        if catalog_emitted_early && plan.root_ref == Some(original_ref) {
            continue;
        }
        let Some(new_ref) = renumber.new_for_original(original_ref) else {
            // cov:ignore-start: every part4 plain object is in the RenumberMap by
            // construction (the plan and renumber derive from the same part vectors);
            // this guards a planner/renumber inconsistency that cannot occur here.
            return Err(crate::Error::Unsupported(format!(
                "part4 object {original_ref} has no renumber entry"
            )));
            // cov:ignore-end
        };
        part4_emits.push((new_ref.number, Part4Emit::Plain(original_ref)));
    }
    for original_gen in plan
        .raw
        .part4_other_pages_private
        .iter()
        .chain(&plan.raw.part4_other_pages_shared)
        .chain(&plan.raw.part4_rest)
        .chain(&plan.raw.part9_outline_objects)
        .copied()
        .filter(|object_gen| object_gen.to_object_ref().is_none())
    {
        let Some(new_ref) = renumber.new_for_raw(original_gen) else {
            // cov:ignore-start: raw plan construction and RenumberMap::from_plan share this vector; absence is an internal invariant failure
            return Err(crate::Error::Unsupported(format!(
                "raw Part-4 identity {} {} has no renumber entry",
                original_gen.get_obj(),
                original_gen.get_gen()
            )));
        };
        // cov:ignore-end
        part4_emits.push((new_ref.number, Part4Emit::Raw(original_gen)));
    }
    for container in &objstm_layout.part4 {
        part4_emits.push((container.container_new_num, Part4Emit::Container(container)));
    }
    part4_emits.sort_by_key(|(number, _)| *number);
    for (_, emit) in &part4_emits {
        match emit {
            Part4Emit::Plain(original_ref) => {
                let new_ref = renumber
                    .new_for_original(*original_ref)
                    .expect("part4 plain object renumber entry checked above");
                let offset = append_body_object_for_ref(
                    output,
                    pdf,
                    new_ref,
                    *original_ref,
                    options,
                    encrypt_ctx,
                    encrypted_string_emitter.as_deref_mut(),
                    renumber,
                    raw_removed_refs,
                    raw_content_normalize_refs,
                )?; // cov:ignore: planner-produced Part-4 references are valid by construction.
                xref_offsets.insert(new_ref.number, offset);
                report_progress_event(options)?;
            }
            Part4Emit::Raw(original_gen) => {
                let new_ref = renumber
                    .new_for_raw(*original_gen)
                    .expect("raw Part-4 object renumber entry checked above");
                let offset = append_body_object_for_raw(
                    output,
                    pdf,
                    new_ref,
                    *original_gen,
                    options,
                    encrypt_ctx,
                    encrypted_string_emitter.as_deref_mut(),
                    renumber,
                    raw_removed_refs,
                    raw_content_normalize_refs,
                )?; // cov:ignore: planner-produced raw Part-4 identities are valid by construction.
                xref_offsets.insert(new_ref.number, offset);
                report_progress_event(options)?;
            }
            Part4Emit::Container(container) => {
                let offset = append_objstm_container_object(
                    output,
                    container,
                    renumber,
                    pdf,
                    raw_removed_refs,
                    options,
                    encrypt_ctx,
                )?; // cov:ignore: error requires an internal planner/renumber inconsistency.
                xref_offsets.insert(container.container_new_num, offset);
                for _ in &container.members {
                    if pass1_digest {
                        decrement_progress_event(options)?;
                    }
                    report_progress_event(options)?;
                    if pass1_digest {
                        report_progress_event(options)?;
                    }
                }
            }
        }
    }

    if let Some(expected) = final_main_xref_offset {
        let actual = output.position_usize()?;
        if actual != expected {
            // cov:ignore-start: final offsets are derived from the same pass-1 layout
            return Err(crate::Error::Unsupported(format!(
                "linearization final main xref offset drifted: expected {}, got {}",
                expected, actual
            )));
            // cov:ignore-end
        }
    }

    // Part 6: main cross-reference + trailer.
    //
    // When ObjStm containers are present the body holds compressed (type-2)
    // members which a classic xref table cannot represent, so Part 6 becomes
    // an xref stream.  With an empty layout the classic table path is kept
    // verbatim — no behavioural change for Disable / no-ObjStm inputs.
    let (last_xref_offset, last_xref_first_entry_offset, second_xref_end) = if objstm_layout
        .is_empty()
    {
        // The main (Part-6) xref covers only the low-numbered "rest" objects
        // [0, param_slot); the first-page section [param_slot, total) was
        // recorded by the Part-1 first-page xref above.  qpdf's classic layout
        // makes the file's trailing `startxref` point back at that first-page
        // xref (near the top of the file), so thread its keyword offset in.
        //
        // The main trailer carries the same `/ID` as the Part-1 first-page
        // trailer; capture its span so the deterministic-`/ID` back-patch
        // rewrites the placeholder there too (the push is unconditional,
        // matching the Part-1 site — `id_ranges` is consulted only when
        // `deterministic_id` is set).
        let main_section_start = output.position_usize()?;
        let result = write_main_xref_and_trailer(
            output,
            &*xref_offsets,
            param_dict_obj_number,
            part1_classic_xref_offset,
            source_trailer,
            &trailer_map,
            raw_removed_refs,
            // Last use of `id_writer` — move it (no reborrow needed).
            id_writer,
        )?; // cov:ignore: the validated linearization plan makes this serializer error path defensive.
        id_ranges.push(main_section_start..output.position_usize()?);

        // Final output patches the fixed-width first-page xref after every
        // object offset is known. Pass 1 already emitted qpdf's zero records
        // directly before the body and therefore has no in-place operation.
        if !pass1_digest && !is_final {
            let patch = part1_xref_patch
                .as_ref()
                // cov:ignore-start: final classic output always reserves this patch.
                .ok_or_else(|| {
                    crate::Error::Unsupported(
                        "linearization writer: classic path produced no Part-1 xref patch \
                         (internal invariant violated)"
                            .to_string(),
                    )
                })?;
            // cov:ignore-end
            patch_part1_xref(output, patch, &*xref_offsets)?; // cov:ignore: legacy patch fallback is not used by the forward final route
        }

        (result.0, result.1, 0)
    } else {
        // The first-page xref stream was already emitted before /E; record
        // where it landed so the file's trailing `startxref` (qpdf's chain leaf)
        // can point at it and its `/Prev → main xref` can be back-patched.
        let patch = first_page_xref_patch.as_ref().ok_or_else(|| {
            crate::Error::Unsupported(
                "linearization writer: ObjStm path produced no first-page xref patch \
                 (internal invariant violated)"
                    .to_string(),
            )
        })?;
        let first_page_obj_offset = patch.region.start;

        // Boundary invariant: the first-page
        // cross-reference section must be physically inside the first-page
        // region, i.e. before /E.
        debug_assert!(
            first_page_obj_offset < end_of_first_page_offset,
            "first-page xref stream offset ({first_page_obj_offset}) must be before \
             /E ({end_of_first_page_offset}) — linearization boundary violated"
        );

        let result = write_main_xref_stream_and_trailer(
            output,
            xref_offsets,
            &member_new,
            relocation,
            total_count,
            source_trailer,
            first_page_obj_offset,
            max_ostream_index,
            pass1_digest,
            structural_streams_filtered,
        )?; // cov:ignore: the validated linearization plan makes xref-stream serialization errors defensive.
        let (main_xref_offset, main_first_entry_offset, main_id_range, second_xref_end) = result;
        // Main xref stream object is the second (and last) `/ID` site on the
        // ObjStm path.  Its span extends through the trailing
        // `startxref`/`%%EOF` and is never touched by `patch_first_page_xref`
        // below (which patches only the first-page region, before /E). Record
        // only the `/ID` array token's own span (not the whole object): this
        // dict carries no canonical (custom) trailer entries
        // (`write_main_xref_stream_and_trailer` always passes
        // `canonical_entries: None`), but its stream payload is arbitrary
        // binary xref data, so the tight span still avoids scanning bytes
        // this function does not own. See `patch_first_page_xref`'s doc for
        // the full rationale (that first-page sibling *does* carry custom
        // trailer entries, which is what makes the tight span load-bearing
        // there).
        if let Some(id_range) = main_id_range {
            id_ranges.push(id_range);
        }

        // Every downstream object offset is now known, so rebuild the first-page
        // xref's reserved region with the real encoded object and `/Prev →
        // main xref`. The region's byte length is fixed (qpdf's pass-1 sizing),
        // so this shifts no bytes between the two layout passes.
        if !pass1_digest && !is_final {
            let first_page_id_range = patch_first_page_xref(
                output,
                patch,
                xref_offsets, // cov:ignore: legacy patch fallback is not used by the forward final route
                &member_new,
                main_xref_offset,
                hint_stream_obj_total_len,
            )?; // cov:ignore: propagates patch_first_page_xref's unreachable region-overflow error arm.
            if let Some(id_range) = first_page_id_range {
                id_ranges.push(id_range);
            }
        }

        (main_xref_offset, main_first_entry_offset, second_xref_end)
    };

    let pass_xref_offsets = if is_final {
        BTreeMap::new()
    } else {
        std::mem::take(xref_offsets)
    };
    Ok(LinearizedPassOutput {
        xref_offsets: pass_xref_offsets,
        first_page_xref_offset: first_page_xref_patch
            .as_ref()
            .map(|patch| patch.region.start),
        hint_stream_offset,
        hint_stream_obj_total_len,
        end_of_first_page_offset,
        last_xref_offset,
        last_xref_first_entry_offset,
        second_xref_end,
        first_trailer_prev_range,
        id_ranges,
    })
}

/// Compute per-object byte lengths from a written-out `xref_offsets` map.
///
/// Each object's byte length = offset of the next object (or end-of-xref-section)
/// minus this object's offset.
///
/// Returns `new_number → byte_length` map.
fn compute_byte_lengths(
    xref_offsets: &BTreeMap<u32, usize>,
    last_xref_offset: usize,
    hint_stream_new_num: u32,
    param_dict_new_num: u32,
) -> BTreeMap<u32, usize> {
    // Build a sorted list of (offset, new_number) pairs, plus a sentinel for
    // the last_xref_offset (= start of main xref, which terminates the body).
    let mut sorted: Vec<(usize, u32)> = xref_offsets
        .iter()
        // Exclude the param dict (Part 1, written before the hint stream).
        // The slot is dynamic because the renumber map may promote /Pages,
        // /Info, /Catalog ahead of it — hard-coding `1` here would skip the
        // wrong object whenever the param dict moves.
        .filter(|(&num, _)| num != param_dict_new_num)
        .map(|(&num, &off)| (off, num))
        .collect();
    sorted.sort_unstable();

    let mut lengths: BTreeMap<u32, usize> = BTreeMap::new();
    for (idx, &(off, num)) in sorted.iter().enumerate() {
        // Skip the hint stream — its "length" is used separately.
        if num == hint_stream_new_num {
            continue;
        }
        let next_off = if idx + 1 < sorted.len() {
            sorted[idx + 1].0
        } else {
            last_xref_offset
        };
        lengths.insert(num, next_off.saturating_sub(off));
    }
    lengths
}

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

/// For each second-half ObjStm batch, return its insertion point among plain
/// objects so the container lands at its qpdf part/object-key position.
///
/// qpdf orders the second half as `part7 (page by page) → part8 → part9`.
/// Generate containers have fresh high object numbers and therefore sort at the
/// end of their group. Preserve containers retain their source ObjGen and may
/// precede a plain object in the same group.
fn part7_owner_for_plan(plan: &LinearizationPlan, member: ObjectRef) -> Option<usize> {
    if let Some(optimization) = plan.optimization.as_ref() {
        let owner = plan
            .preserve_source_membership()
            .and_then(|membership| membership.get(&member.number).copied())
            .map(|source| ObjectRef::new(source, 0))
            .unwrap_or(member);
        return optimization
            .other_page_private_owner(owner)
            .map(|page| page as usize);
    }
    // Manually constructed plans have no canonical object-user map. Keep
    // their bounded fallback without imposing this second ownership table
    // on the production qpdf route.
    plan.per_page_private_objects
        .iter()
        .enumerate()
        .skip(1)
        .find_map(|(page, members)| members.contains(&member).then_some(page))
}

fn qpdf_object_number(object_gen: QpdfObjGen) -> u32 {
    u32::try_from(object_gen.get_obj()).unwrap_or(u32::MAX)
}

type SecondHalfPlainRank = (u8, usize, u8, u32);
type SecondHalfPlainObject = (QpdfObjGen, SecondHalfPlainRank);

fn second_half_container_anchors(
    plan: &LinearizationPlan,
    part4_batches: &[RoutedObjStmBatch],
) -> Vec<SecondHalfContainerAnchor> {
    let member_set: BTreeSet<QpdfObjGen> = part4_batches
        .iter()
        .flat_map(|batch| batch.members.iter().copied())
        .filter_map(|object_ref| QpdfObjGen::try_from_object_ref(object_ref).ok())
        .collect();
    let source_container_set: BTreeSet<QpdfObjGen> = part4_batches
        .iter()
        .filter_map(|batch| batch.source_container_number)
        .map(|number| QpdfObjGen::new(number as i32, 0))
        .collect();

    // Generate containers are fresh objects with no source ObjGen. Preserve
    // containers retain one, and use the existing source-number anchor rules.
    // The two modes cannot be mixed in one resolved batch plan.
    let generate_batches = part4_batches
        .iter()
        .all(|batch| batch.source_container_number.is_none());
    let part9_pages: BTreeSet<ObjectRef> = plan
        .optimization
        .as_ref()
        .map(|optimization| {
            optimization
                .objects_for_root_key(b"Pages")
                .collect::<BTreeSet<ObjectRef>>()
        })
        .filter(|pages| !pages.is_empty())
        .unwrap_or_else(|| plan.pages_tree_ref.into_iter().collect());

    // Second-half plain (non-member) objects in qpdf part order, each tagged
    // with a qpdf ordering key. The identity in this list is deliberately
    // `QpdfObjGen`, not `ObjectRef`: a raw plain object can be the object that
    // separates a generated container from its previous peer.
    let mut plain_ranked: Vec<SecondHalfPlainObject> = Vec::new();
    let push_page_private = |plain_ranked: &mut Vec<SecondHalfPlainObject>,
                             page: usize,
                             page_head: Option<QpdfObjGen>,
                             objects: &[QpdfObjGen]| {
        for &object_gen in objects {
            if !member_set.contains(&object_gen) && !source_container_set.contains(&object_gen) {
                let page_head_rank = u8::from(Some(object_gen) != page_head);
                plain_ranked.push((
                    object_gen,
                    (0, page, page_head_rank, qpdf_object_number(object_gen)),
                ));
            }
        }
    };

    if plan.has_raw_projection_gap() {
        for (page, objects) in plan.raw.per_page_private_objects.iter().enumerate().skip(1) {
            let page_head = plan
                .page_hints
                .get(page)
                .and_then(|hint| QpdfObjGen::try_from_object_ref(hint.page_ref).ok());
            push_page_private(&mut plain_ranked, page, page_head, objects);
        }
        for &object_gen in &plan.raw.part4_other_pages_shared {
            if !member_set.contains(&object_gen) && !source_container_set.contains(&object_gen) {
                plain_ranked.push((object_gen, (1, 0, 0, qpdf_object_number(object_gen))));
            }
        }
        for &object_gen in &plan.raw.part4_rest {
            if !member_set.contains(&object_gen) && !source_container_set.contains(&object_gen) {
                let (category, page) = if generate_batches {
                    object_gen
                        .to_object_ref()
                        .zip(plan.optimization.as_ref())
                        .map(|(object_ref, optimization)| {
                            part9_category_order_key(optimization, &part9_pages, [&object_ref])
                        })
                        .unwrap_or((0, 0))
                } else {
                    (0, 0)
                };
                plain_ranked.push((
                    object_gen,
                    (
                        2 + category,
                        page as usize,
                        0,
                        qpdf_object_number(object_gen),
                    ),
                ));
            }
        }
    } else {
        for (i, privates) in plan.per_page_private_objects.iter().enumerate().skip(1) {
            let page_head = plan
                .page_hints
                .get(i)
                .and_then(|hint| QpdfObjGen::try_from_object_ref(hint.page_ref).ok());
            let objects: Vec<QpdfObjGen> = privates
                .iter()
                .filter_map(|object_ref| QpdfObjGen::try_from_object_ref(*object_ref).ok())
                .collect();
            push_page_private(&mut plain_ranked, i, page_head, &objects);
        }
        for &object_ref in &plan.part4_other_pages_shared {
            let object_gen = QpdfObjGen::try_from_object_ref(object_ref)
                .expect("checked Part-8 object must fit qpdf raw identity");
            if !member_set.contains(&object_gen) && !source_container_set.contains(&object_gen) {
                plain_ranked.push((object_gen, (1, 0, 0, qpdf_object_number(object_gen))));
            }
        }
        for &object_ref in &plan.part4_rest {
            let object_gen = QpdfObjGen::try_from_object_ref(object_ref)
                .expect("checked Part-9 object must fit qpdf raw identity");
            if !member_set.contains(&object_gen) && !source_container_set.contains(&object_gen) {
                if generate_batches {
                    let optimization = plan
                        .optimization
                        .as_ref()
                        .expect("generated ObjStm batches require optimization users");
                    let (category, page) =
                        part9_category_order_key(optimization, &part9_pages, [&object_ref]);
                    plain_ranked.push((
                        object_gen,
                        (
                            2 + category,
                            page as usize,
                            0,
                            qpdf_object_number(object_gen),
                        ),
                    ));
                } else {
                    plain_ranked.push((object_gen, (2, 0, 0, qpdf_object_number(object_gen))));
                }
            }
        }
    }

    let member_is_in_route = |member: ObjectRef, route: ContainerPart| -> bool {
        let object_gen = QpdfObjGen::try_from_object_ref(member)
            .expect("ObjStm members must fit qpdf raw identity");
        match route {
            ContainerPart::OtherPagePrivate => plan
                .raw
                .per_page_private_objects
                .iter()
                .skip(1)
                .any(|objects| objects.contains(&object_gen)),
            ContainerPart::OtherPageShared => {
                plan.raw.part4_other_pages_shared.contains(&object_gen)
            }
            ContainerPart::Rest => {
                plan.raw.part4_rest.contains(&object_gen)
                    || plan.raw.part9_outline_objects.contains(&object_gen)
            }
            _ => false, // cov:ignore: only second-half routes reach this raw membership helper
        }
    };

    let anchors: Vec<_> = part4_batches
        .iter()
        .map(|batch| {
            if batch.members.is_empty() {
                return SecondHalfContainerAnchor::AfterLast; // cov:ignore: resolved batches are non-empty
            }
            // A generated container is first encountered when qpdf enqueues
            // the first compressed member in this part. Its position is
            // therefore determined by that member's raw source order, not by
            // an invented maximum source number. Preserve mode keeps its
            // existing source-container ordering key because qpdf's preserved
            // container itself carries that source identity.
            let object_number = if let Some(source_container_number) = batch.source_container_number
            {
                source_container_number
            } else if plan.has_raw_projection_gap() {
                batch
                    .members
                    .iter()
                    .filter_map(|member| QpdfObjGen::try_from_object_ref(*member).ok())
                    .filter(|object_gen| {
                        batch.members.iter().any(|member| {
                            QpdfObjGen::try_from_object_ref(*member).ok() == Some(*object_gen)
                                && member_is_in_route(*member, batch.route)
                        })
                    })
                    .map(qpdf_object_number)
                    .min()
                    .expect("raw ObjStm batch must have a member in its second-half route")
            } else {
                u32::MAX
            };
            let batch_rank: (u8, usize, u8, u32) = match batch.route {
                ContainerPart::OtherPagePrivate => {
                    let owner = batch
                        .members
                        .iter()
                        .find_map(|member| part7_owner_for_plan(plan, *member))
                        .expect("Part-7 ObjStm route must have one non-first-page owner");
                    (0, owner, 1, object_number)
                }
                ContainerPart::OtherPageShared => (1, 0, 0, object_number),
                ContainerPart::Rest
                    if batch.source_container_number.is_some()
                        && (batch.source_container_number.is_some_and(|source| {
                            part9_pages.contains(&ObjectRef::new(source, 0))
                        }) || batch.members.iter().any(|m| part9_pages.contains(m))) =>
                {
                    // qpdf places the complete /Pages user set before the
                    // remaining lc_other set. If that user set is folded into
                    // a preserved ObjStm, the container inherits the same
                    // head position rather than sorting by its source object
                    // number (QPDF_linearization.cc:1286-1290).
                    (2, 0, 0, 0)
                }
                ContainerPart::Rest if generate_batches => {
                    let optimization = plan
                        .optimization
                        .as_ref()
                        .expect("generated ObjStm batches require optimization users");
                    let (category, page) =
                        part9_category_order_key(optimization, &part9_pages, batch.members.iter());
                    (2 + category, page as usize, 1, object_number)
                }
                ContainerPart::Rest => (2, 0, 0, object_number),
                // cov:ignore-start: first-half routes cannot enter resolved second-half batches
                ContainerPart::OpenDocument
                | ContainerPart::FirstPagePrivate
                | ContainerPart::FirstPageShared
                | ContainerPart::FirstPageOutlines => {
                    unreachable!("first-half route in second-half ObjStm batches")
                } // cov:ignore-end
            };
            let previous = plain_ranked
                .iter()
                .rfind(|(_, rank)| *rank <= batch_rank)
                .map(|(r, _)| *r);
            match previous {
                Some(r) => SecondHalfContainerAnchor::After(r),
                None if plain_ranked.is_empty() => SecondHalfContainerAnchor::AfterLast,
                None => SecondHalfContainerAnchor::BeforeFirst,
            }
        })
        .collect();
    anchors
}

fn preserved_source_container_number(
    container: &ObjStmContainer,
    source_container_by_member: &BTreeMap<ObjectRef, u32>,
) -> Result<u32> {
    let source_container_number = container
        .members
        .first()
        .and_then(|(original_ref, _)| source_container_by_member.get(original_ref).copied())
        .ok_or_else(|| {
            crate::Error::Unsupported(format!(
                "preserved ObjStm container {} has no source container",
                container.container_new_num
            ))
        })?;
    if container.members.iter().any(|(original_ref, _)| {
        source_container_by_member.get(original_ref).copied() != Some(source_container_number)
    }) {
        return Err(crate::Error::Unsupported(format!(
            "preserved ObjStm container {} combines multiple source containers",
            container.container_new_num
        )));
    }
    Ok(source_container_number)
}

/// Reject a standard (non-ObjStm-generating) linearization plan that still
/// contains multiple live objects sharing an object number with different
/// generations.
///
/// qpdf's own linearization renumbering pass hits this exact limitation for
/// files with a stale-generation reference alongside the object's real
/// generation (e.g. a `/Candidates [4 0 R 4 1 R]`-shaped array referencing
/// both a dangling `4 0 R` and the live `4 1 R`): `discard_lower_generations`
/// only removes duplicate rows from the *raw xref table* at load time, so it
/// does not resolve a reference to a generation that never had its own xref
/// row in the first place. Verified against a live qpdf 11.9.0 probe: both
/// `--object-streams=disable` and `--object-streams=preserve` reject
/// `null-visible-stale-generation.pdf` with this exact message (exit 2),
/// while `--object-streams=generate` succeeds because Generate's own
/// planning already collapses stale generations before this point.
fn reject_multiple_generations(plan: &LinearizationPlan) -> Result<()> {
    let mut previous_number = None;
    for object_gen in plan.renumber_assigned_raw() {
        let object_number = object_gen.get_obj();
        if previous_number == Some(object_number) {
            return Err(crate::Error::Unsupported(
                "QPDF cannot currently linearize files that contain multiple objects with the \
                 same object ID and different generations.  If you see this error message, \
                 please file a bug report and attach the file if possible.  As a workaround, \
                 first convert the file with qpdf without linearizing, and then linearize the \
                 result of that conversion."
                    .to_string(),
            ));
        }
        previous_number = Some(object_number);
    }
    Ok(())
}

/// Write a complete linearized PDF to an in-memory buffer.
///
/// Given a [`LinearizationPlan`] (which partitions all objects into the four
/// body parts) and a [`RenumberMap`] (which assigns the correct linearized
/// object numbers), this function:
///
/// 1. Emits Part 1: header + linearization param dict (whose object number is
///    `renumber.param_dict_ref().number` — typically 3 with the qpdf-aligned
///    slot allocation, never assumed to be 1) with placeholder numeric values,
///    followed by a one-object xref subsection and trailer.
/// 2. Emits the hint stream object at `renumber.hint_stream_slot()` (Annex F
///    Part 2). /Size in both trailers is `renumber.len() as u32 + 1`.
/// 3. Emits the first-page body objects (`Plan.part2_objects` — Annex F Part 3).
/// 4. Emits the shared/catalog/info objects (`Plan.part3_objects` — Annex F Part 4).
/// 5. Emits the remaining body objects (`Plan.part4_objects()` — Annex F Part 5).
/// 6. Emits the main cross-reference table and trailer (Annex F Part 6).
///
/// Uses qpdf's two-pass layout: pass 1 omits the hint object and supplies the
/// virtual offsets for one-shot hint-table generation; pass 2 splices the
/// complete framed hint object at the reserved slot.
///
/// Returns [`LinearizedDocument`] containing both the bytes and the
/// [`LinearizedOffsets`] needed for back-patching.
///
/// With [`WriterOptions::deterministic_id`] and without
/// [`WriterOptions::static_id`], the `/ID` is derived from an MD5 over the
/// assembled layout (the same digest feeds every trailer / xref-stream dict),
/// so the identifier is reproducible across runs for identical input. When
/// both flags are set, qpdf's static-ID precedence is used instead.
///
/// # Errors
///
/// Returns [`crate::Error::Internal`] when
/// [`WriterOptions::deterministic_id`] is combined with encrypted output
/// ([`WriterOptions::encrypt`] or [`WriterOptions::copy_encryption`]): qpdf
/// still enables its deterministic digest pipeline, but the encryption setup
/// generates an ID before that pipeline exists. This guard mirrors only that
/// specific restriction — qpdf itself accepts a *non*-deterministic-id `/ID`
/// alongside encryption (observed on qpdf
/// 11.9.0: `qpdf --linearize --encrypt "" "" 128 --use-aes=y -- in.pdf
/// out.pdf` succeeds, while adding `--deterministic-id` to that same command
/// fails with qpdf's own `QPDFWriter::generateID has no data for
/// deterministic ID` internal error), so linearize+encrypt on its own is not
/// rejected by this guard.
///
/// The production PdfWriter route prepares the Catalog extensions before
/// planning, so indirect /Extensions and /ADBE values are accepted and
/// directized according to qpdf's QPDFWriter::prepareFileForWrite. This
/// lower-level test-only entry point assumes its supplied plan was built
/// after that preparation and does not add a separate extension rejection.
///
/// Returns [`crate::Error::Unsupported`] when the plan and renumber map are
/// inconsistent or a layout value does not fit its slot — for example an
/// object (catalog, page, shared, or body object) has no entry in the
/// [`RenumberMap`], the plan has no page hints or a `per_page_private_objects`
/// length that disagrees with `page_hints`, `/Size` overflows `u32`, a shared
/// object lacks a pass-1 byte length, or a hint-table field cannot represent its
/// pass-1 value.
#[cfg(test)]
pub(crate) fn write_linearized<R: Read + Seek>(
    plan: &LinearizationPlan,
    renumber: &RenumberMap,
    pdf: &mut Pdf<R>,
    options: &WriterOptions,
) -> Result<LinearizedDocument> {
    let setup = crate::writer::build_writer_setup(pdf, options)?;
    let output = write_linearized_impl(plan, renumber.clone(), pdf, options, None, setup, None)?;
    // cov:ignore-start: the memory helper always selects the Vec-backed output mode
    output.document.ok_or_else(|| {
        crate::Error::Internal(
            "linearization memory helper returned no in-memory document".to_string(),
        )
    })
    // cov:ignore-end
}

/// Write linearized output through the canonical [`crate::PdfWriter`] route.
///
/// The public compatibility helpers above accept an already-built plan for
/// the inspection/fixture APIs.  A real writer must plan and emit the same
/// live `Pdf` after all writer settings and graph mutations have settled.  The
/// returned mapping is taken from the final local renumber map, including any
/// ObjStm relocation performed by the two-pass linearization emitter.
pub(crate) fn write_linearized_for_pdf_writer<R: Read + Seek>(
    pdf: &mut Pdf<R>,
    options: &WriterOptions,
    pass1_path: Option<&Path>,
    setup: crate::writer::WriterSetupState,
    output: &mut dyn OutputTarget,
) -> Result<WriterResult> {
    let plan_result = (|| {
        let mode = if crate::writer::force_version_below_1_5(options) {
            crate::writer::ObjectStreamMode::Disable
        } else {
            options.object_streams
        };

        let mut plan_options = options.clone();
        plan_options.object_streams = mode;
        let plan = LinearizationPlan::from_pdf_with_writer_options_and_source_membership(
            pdf,
            &plan_options,
            Some(&setup.source_object_stream_data),
            setup.generated_compressible.as_ref(),
        )?;
        // qpdf allocates generated ObjStm placeholders before it removes page
        // and Catalog members from the mapping (QPDFWriter.cc:1970-2005,
        // 2141-2161). Count those pre-filter containers for progress even
        // when a later filter leaves one empty and therefore absent from the
        // emitted layout.
        let generated_object_stream_count = if mode == crate::writer::ObjectStreamMode::Generate {
            match setup.generated_compressible.as_ref() {
                Some(compressible) => {
                    crate::writer::object_streams::even_split_into_streams(&compressible.eligible)
                        .len()
                }
                None => {
                    let compressible =
                        crate::writer::object_streams::compressible_objgens_qpdf_plan(pdf)?;
                    crate::writer::object_streams::even_split_into_streams(&compressible.eligible)
                        .len()
                }
            }
        } else {
            0
        };
        crate::writer::configure_progress_for_pdf(
            pdf,
            options,
            generated_object_stream_count,
            true,
        )?;
        let renumber = RenumberMap::from_plan(&plan);
        Ok((plan, renumber))
    })();

    plan_result.and_then(|(plan, renumber)| {
        let output = write_linearized_impl(
            &plan,
            renumber,
            pdf,
            options,
            pass1_path,
            setup,
            Some(output),
        )?;
        Ok(output.writer_result)
    })
}

/// Append qpdf's pass-1 debugging comments after the body pipeline has been
/// finished. `QPDFWriter.cc:2886-2900` uses unchecked `fprintf` calls followed
/// by an unchecked `fclose`, so comment write/close failures are intentionally
/// not promoted to the writer's public error channel.
fn write_pass1_debug_comments(writer: &mut dyn Write, comments: &[u8]) {
    debug_assert!(comments.len() < 4096);
    let mut buffered = StdioBuffer::new(writer);
    let _ = buffered.write(comments);
}

/// Reject manually-constructed plans whose per-page private-object lists do
/// not have one entry for every page hint. `from_pdf` always preserves this
/// alignment; keeping the check separate makes the hand-built-plan failure
/// observable without forcing a malformed plan through the full writer.
// qpdf-deviation-start: no qpdf counterpart validates a persisted plan's
// per_page_private_objects/page_hints vector-length agreement; qpdf computes
// both inline in one pass (QPDF_linearization.cc calculateLinearizationData)
// with no separate externally-constructible plan struct, and this Err arm is
// reachable only via flpdf's own #[cfg(test)] hand-built-plan entry points,
// never from parsing a real PDF.
fn validate_per_page_private_objects(plan: &LinearizationPlan) -> Result<()> {
    if plan.per_page_private_objects.len() != plan.page_hints.len() {
        return Err(crate::Error::Unsupported(format!(
            "linearization writer: per_page_private_objects length ({}) does not \
                 match page_hints length ({}) — plan invariant violated",
            plan.per_page_private_objects.len(),
            plan.page_hints.len()
        )));
    }
    Ok(())
}
// qpdf-deviation-end

#[inline(never)]
fn write_linearized_impl<R: Read + Seek>(
    plan: &LinearizationPlan,
    renumber: RenumberMap,
    pdf: &mut Pdf<R>,
    options: &WriterOptions,
    pass1_path: Option<&Path>,
    setup: crate::writer::WriterSetupState,
    final_output: Option<&mut dyn OutputTarget>,
) -> Result<LinearizedWriteResult> {
    let crate::writer::WriterSetupState {
        generated_id,
        encryption_parameters,
        source_object_stream_data,
        generated_compressible: _,
        generated_object_stream_sources: _,
    } = setup;
    let source_container_by_member: BTreeMap<ObjectRef, u32> = source_object_stream_data
        .into_iter()
        .map(|(member, stream)| (ObjectRef::new(member, 0), stream))
        .collect();
    let deterministic_id = crate::writer::uses_deterministic_id(options);

    // Finalize the file identifier exactly once here — before the plan/
    // renumber-map rebuild below, before `Optimization::prepare_for_linearized_write`,
    // and before the two layout passes — and store it back on the working
    // trailer. The Part-1 trailer and every split xref/trailer then read this
    // single value, so one linearized output carries one consistent /ID across
    // both passes.
    //
    // Computed this early (rather than just before the layout passes,
    // where this block used to sit) so `/ID[0]` is available before the
    // renumber map is consumed: the file encryption key derives from
    // `/ID[0]` (PDF 1.7 §7.6.3.3 Algorithm 2), and qpdf itself computes
    // `/ID` once, early, via `generateID()`'s idempotent guard
    // (`QPDFWriter::write` calls it before `unparseObject`-ing the trailer).
    // This computation depends only on `options` and the source trailer's
    // `/ID`/`/Info` — neither the plan/renumber rebuild nor
    // `Optimization::prepare_for_linearized_write` below ever mutates the
    // trailer, so moving it here does not change any output byte for an
    // existing (non-encrypting) caller.
    //
    // Capture qpdf's deterministic-`/ID` seed inputs from the ORIGINAL trailer
    // BEFORE the all-zero placeholder overwrites `/ID` below. `/ID[0]` is the
    // preserved permanent identifier and the `/Info`-derived suffix feeds the
    // seed; reading either after the placeholder is installed would mistake the
    // 16 zero bytes for a real source `/ID[0]` and corrupt the result.
    let source_trailer_handle = pdf.trailer().shallow_copy()?;
    let source_id0 = crate::writer::source_permanent_id_handle(&source_trailer_handle);
    let (det_id_source_id0, det_id_info_suffix): (Option<Vec<u8>>, Vec<u8>) = if deterministic_id {
        let suffix = crate::writer::deterministic_id_info_suffix(pdf);
        (source_id0.clone(), suffix)
    } else {
        (None, Vec::new())
    };
    let pass1_id = linearization_pass1_id(source_id0.as_deref());
    let finalized_id = generated_id.unwrap_or_else(|| {
        finalize_linearized_id(
            options,
            source_id0.as_deref(),
            det_id_source_id0.as_deref(),
            options.copy_encryption.as_ref(),
        )
    });
    source_trailer_handle.replace_key(b"/ID", finalized_id)?;
    let pass1_source_trailer = source_trailer_handle.shallow_copy()?;
    pass1_source_trailer.replace_key(b"/ID", pass1_id)?;

    // QPDFWriter::setEncryptionParameters and
    // QPDFWriter::copyEncryptionParameters call generateID() before the
    // linearized pass can produce deterministic ID data. Translate that
    // qpdf logic_error rather than treating the combination as an unsupported
    // feature (with a static ID, qpdf's pushMD5Pipeline fails instead).
    if options.deterministic_id && (options.encrypt.is_some() || options.copy_encryption.is_some())
    {
        return Err(crate::writer::deterministic_id_encryption_error(options));
    }

    // `plan`/`renumber` are built from a separate `Pdf` handle opened on the
    // same source bytes (every real caller — the CLI, and this module's own
    // `build_linearized()` test helper — re-opens the input for writing rather
    // than reusing the planning handle: "Re-open the PDF so write_linearized
    // can seek/read objects independently"). Run qpdf's complete optimization
    // preparation prefix here too, on THIS handle, so direct `/Outlines`,
    // page-tree repairs, and inherited-attribute minting happen in the same
    // order and allocate the same object numbers the plan assumed. Idempotent:
    // a no-op if `pdf` was already prepared (e.g. a caller that reuses one
    // handle for both steps). Runs after the option guards above so an invalid
    // option combination returns its error without mutating the caller's `Pdf`
    // first.
    crate::optimization::Optimization::prepare_for_linearized_write(pdf)?;

    // Reconcile the caller-built plan/renumber pair with the writer's effective
    // object-stream mode. The historical `from_pdf(bool)` API maps `false` to
    // Disable, while `WriterOptions::default()` is Preserve; source-ObjStm
    // Preserve has different stale-generation and container-routing rules, so
    // reusing the Disable partitions can reject or mis-layout the file. Rebuild
    // both structures together whenever their recorded planning mode differs.
    //
    // A forced sub-1.5 header also makes the effective mode Disable: object and
    // cross-reference streams are PDF 1.5 features and qpdf will not emit them
    // under a forced version it must not exceed (observed on qpdf 11.9.0:
    // `--linearize --object-streams=generate --force-version=1.4` yields no
    // `/ObjStm` and a classic xref table at header 1.4). In that case normalize
    // the write options too, so plan, renumbering, and physical output all use
    // the same classic layout.
    let effective_object_stream_mode = if crate::writer::force_version_below_1_5(options) {
        crate::writer::ObjectStreamMode::Disable
    } else {
        options.object_streams
    };
    let must_rebuild_plan = plan.object_stream_mode != effective_object_stream_mode;
    let rebuilt = if must_rebuild_plan {
        let rebuilt_plan =
            LinearizationPlan::from_pdf_with_object_stream_mode(pdf, effective_object_stream_mode)?;
        let rebuilt_renumber = RenumberMap::from_plan(&rebuilt_plan);
        Some((rebuilt_plan, rebuilt_renumber))
    } else {
        None
    };
    let must_normalize_options = options.object_streams != effective_object_stream_mode;
    let normalized_options = if must_normalize_options {
        Some(WriterOptions {
            object_streams: effective_object_stream_mode,
            ..options.clone()
        })
    } else {
        None
    };
    let (rebuilt_plan, renumber) = match rebuilt {
        Some((rebuilt_plan, rebuilt_renumber)) => (Some(rebuilt_plan), rebuilt_renumber),
        None => (None, renumber),
    };
    let plan = rebuilt_plan.as_ref().unwrap_or(plan);
    let options = normalized_options.as_ref().unwrap_or(options);

    // qpdf's linearization maps discard generations only after asserting that
    // every surviving object number is unique. Generate, and Preserve on an
    // ObjStm source, have already removed stale generations while planning;
    // standard Disable/Preserve retain them and must reject the file here.
    // discard_lower_generations (xref.rs) only removes duplicate rows from
    // the raw xref table at load time; it does not resolve a reference to a
    // generation that never had its own xref row (see
    // reject_multiple_generations's own doc).
    reject_multiple_generations(plan)?;

    // ------------------------------------------------------------------
    // Pre-compute values that do not change across the two layout passes.
    // ------------------------------------------------------------------
    // ------------------------------------------------------------------
    // ObjStm per-half compressed-last placement.
    //
    // qpdf's linearization checker forbids an uncompressed (type-1) xref
    // entry appearing after a compressed (type-2) one within a cross-
    // reference stream.  flpdf's classic slot allocation leaves ObjStm
    // members at their low Part-3 slots while containers sit above
    // `renumber.len()`, which interleaves type-1 and type-2 entries.
    //
    // Fix: resolve the writer-filtered batch plan ONCE, then place every
    // member + container so that, within each file half, the compressed
    // objects are numbered LAST (qpdf 11.9.0's per-half compressed-last
    // order) — see [`RenumberMap::place_objstm_members_per_half`].  The two
    // split xref streams then divide the object-number space by file half:
    // the main (second-half) xref covers `[0, second_half_count)` and the
    // first-page (first-half) xref covers `[second_half_count, /Size)`.  The
    // resulting `local_renumber` is used everywhere downstream; when there are
    // no ObjStm batches it is byte-identical to the input map (the placement
    // early-returns), so the Disable / non-ObjStm path is completely
    // unchanged.
    // ------------------------------------------------------------------
    let resolved_batch_plan = ObjStmLayout::resolve_batches(plan, pdf, options)?;

    // Whether this write schedules any ObjStm container/member relocation —
    // true for Generate (always builds fresh containers) or for Preserve on a
    // source that already carries object streams; always false for Disable
    // and for Preserve on an ObjStm-free source. Computed once here (and
    // reused below both by the encrypt guard and by the 1.5 version floor)
    // from the writer-filtered batch plan, so it reflects every path that can
    // make a batch non-empty, not just `ObjectStreamMode::Generate`.
    let emits_object_streams = !resolved_batch_plan.open_document_batches.is_empty()
        || !resolved_batch_plan.part3_batches.is_empty()
        || !resolved_batch_plan.part4_batches.is_empty();

    let mut local_renumber = renumber;
    // Per Part-4 batch, the second-half plain object after which its container is
    // emitted (its part-group's last plain object) so each second-half container
    // lands at its qpdf part position: a part7 container at the END of its owning
    // page's group, a part8 container after the last part8 plain object, etc.
    // `None` (no preceding plain) appends after all plain — equivalent when the
    // container's group is the last one (the single-second-half-container case).
    let second_half_anchors =
        second_half_container_anchors(plan, &resolved_batch_plan.part4_batches);
    let part4_members: Vec<Vec<ObjectRef>> = resolved_batch_plan
        .part4_batches
        .iter()
        .map(|batch| batch.members.clone())
        .collect();
    // Most Part-4 non-member objects (for example ineligible outline streams
    // and remaining lc_other objects) are placed AFTER the second-half ObjStm
    // containers. Plain streams that qpdf classifies as private/shared
    // thumbnails are emitted during the Part-9 thumbnail phase, before the
    // generated containers that follow; a thumbnail stream demoted to lc_other
    // remains in the post-container pass. Compute that exact set here.
    //
    // `part9_outline_objects` is included alongside `part4_rest`: its eligible
    // members ride in a second-half ObjStm batch (filtered out by
    // `part4_member_set`), but an ineligible outline stream (a stream
    // reachable from `/Outlines`, e.g. a shared /JS action stream) is emitted
    // plain and qpdf numbers it AFTER the outline container, not before.
    let part4_member_set: BTreeSet<ObjectRef> = part4_members.iter().flatten().copied().collect();
    // qpdf's root /Pages user can contain several nested Pages nodes (see
    // `LinearizationPlan::part4_objects`); every member remaining in
    // `part4_rest` is promoted ahead of the rest of part9, not only the
    // Catalog's direct /Pages object. Mirror that full set here so none of
    // those promoted nodes is swept into the post-container pass below.
    let part9_pages: BTreeSet<ObjectRef> = plan
        .optimization
        .as_ref()
        .map(|optimization| {
            optimization
                .objects_for_root_key(b"Pages")
                .collect::<BTreeSet<ObjectRef>>()
        })
        .filter(|pages| !pages.is_empty())
        .unwrap_or_else(|| plan.pages_tree_ref.into_iter().collect());
    let part9_thumbnail_objects: BTreeSet<ObjectRef> = plan
        .optimization
        .as_ref()
        .map(|optimization| {
            optimization
                .thumbnail_objects()
                .collect::<BTreeSet<ObjectRef>>()
        })
        .unwrap_or_default();
    let part9_thumbnail_pre_plain: BTreeSet<ObjectRef> =
        if options.object_streams == crate::writer::ObjectStreamMode::Generate {
            let optimization = plan
                .optimization
                .as_ref()
                .expect("Generate linearization requires optimization users");
            plan.part4_rest
                .iter()
                .copied()
                .filter(|object| {
                    part9_thumbnail_objects.contains(object)
                        && matches!(
                            part9_category_order_key(optimization, &part9_pages, [object]).0,
                            1 | 2
                        )
                })
                .collect()
        } else {
            BTreeSet::new()
        };
    let second_half_post_plain: BTreeSet<ObjectRef> =
        if options.object_streams == crate::writer::ObjectStreamMode::Preserve {
            // Preserve containers retain their source object numbers in qpdf's
            // part-7/8/9 sets. Plain objects therefore remain in the same ordered
            // stream as the containers and are placed by their source-number
            // anchors; deferring them would move an ordinary lc_other object past
            // a later source container.
            BTreeSet::new()
        } else {
            plan.part4_rest
                .iter()
                .chain(&plan.part9_outline_objects)
                .copied()
                .filter(|r| {
                    !part4_member_set.contains(r)
                        && !part9_pages.contains(r)
                        && !part9_thumbnail_pre_plain.contains(r)
                        && Some(*r) != plan.info_ref
                })
                .collect()
        };
    // First-half mirror of `second_half_post_plain`: under /PageMode /UseOutlines
    // the outline objects route to qpdf part6 (first half) via
    // `part6_outline_objects`. Eligible members ride in a first-half ObjStm batch
    // (open-document or Part-3); an ineligible outline stream (a stream
    // reachable from /Outlines, e.g. a shared /JS action stream) is emitted plain,
    // and qpdf numbers it AFTER the part6 container — so it must be placed in the
    // first-half post-container pass, not before the container.
    let first_half_member_set: BTreeSet<ObjectRef> = resolved_batch_plan
        .open_document_batches
        .iter()
        .chain(&resolved_batch_plan.part3_batches)
        .flat_map(|batch| batch.members.iter().copied())
        .collect();
    let mut first_half_post_plain: BTreeSet<ObjectRef> = plan
        .part6_outline_objects
        .iter()
        .copied()
        .filter(|object| !first_half_member_set.contains(object))
        .collect();
    // qpdf's pushOutlinesToPart always emits the plain `/Outlines` root first
    // within the outline category. It is the only plain outline object that
    // must be pulled back before the first-half containers; ineligible outline
    // streams remain in the post-container set (q9o3).
    let first_half_outline_root = plan
        .part6_outline_objects
        .first()
        .copied()
        .filter(|root| !first_half_member_set.contains(root));
    if let Some(root) = first_half_outline_root {
        first_half_post_plain.remove(&root);
    }
    // `part3_batches` is assembled as private, shared, then outline batches in
    // `LinearizationPlan::objstm_batches_generate`/`..._preserve`; retain that
    // qpdf category boundary for the first-half placement anchor.
    let first_half_outline_batch_count = resolved_batch_plan
        .part3_batches
        .iter()
        .filter(|batch| {
            batch
                .members
                .iter()
                .any(|member| plan.part6_outline_objects.contains(member))
        })
        .count();
    if let Some(pre_objects) = plan
        .optimization
        .as_ref()
        .and_then(|optimization| optimization.pre_optimization_object_refs())
    {
        // qpdf's `lc_first_page_private` sequence emits a plain object that
        // optimization minted for page 0 before the first-half ObjStm
        // container. Keep Part-2 objects in that ordinary first-page sequence.
        // The post-container rule remains for Part-3 shared objects,
        // open-document plain objects, and outlines; their qpdf placement is
        // independently pinned by the corresponding hint/container fixtures.
        first_half_post_plain.extend(
            plan.part3_objects
                .iter()
                .chain(&plan.part4_open_document_plain)
                .chain(&plan.part6_outline_objects)
                .copied()
                .filter(|object| {
                    !pre_objects.contains(object) && !first_half_member_set.contains(object)
                }),
        );
    }
    // Open-document batches are numbered FIRST in the first half (right after
    // the catalog, before the hint); Part-3 batches are numbered last within
    // the first half (qpdf packs the first-page shared dicts + /Pages tree +
    // /Info there); Part-4 batches are interleaved among the second-half
    // objects at their part position.
    //
    // qpdf supports linearize+encrypt+ObjStm. Placement must therefore happen
    // before the `/Encrypt` slot is inserted; the slot reservation below then
    // shifts the placed map and the derived ObjStm layout is built afterwards
    // from the shifted map.
    let relocation = if emits_object_streams {
        local_renumber.place_objstm_members_per_half(
            &resolved_batch_plan.open_document_batches,
            &resolved_batch_plan.part3_batches,
            &resolved_batch_plan.part4_batches,
            &second_half_anchors,
            &second_half_post_plain,
            &first_half_post_plain,
            first_half_outline_batch_count,
            first_half_outline_root,
        )
    } else {
        ObjStmRelocation::default()
    };
    let mut container_numbers = relocation.container_numbers.clone();

    // Build the encryption context and reserve the `/Encrypt` dict's object
    // slot BEFORE anything below reads `param_dict_ref()`, `hint_stream_slot()`,
    // or `len()` off `renumber` — `reserve_encrypt_dict_slot` shifts every
    // already-assigned slot at/after the (old) hint-stream position by one,
    // and `Part1Bytes::build`, `hint_stream_new_num`, `total_count`, and the
    // Part-1 dict serialization all read those numbers off the SAME
    // `local_renumber` this mutates — every one of those reads happens
    // through the `renumber` shadow assigned right after this block, so
    // placing the reservation here (rather than scattered at each read site)
    // covers all of them at once.
    //
    // ObjStm placement runs before this reservation. Inserting the encryption
    // sentinel at the hint slot then shifts only the first-half objects that
    // follow it; the container numbers below are adjusted by the same amount.
    //
    // qpdf reserves the linearized `/Encrypt` slot after part layout is known,
    // but the parameter state was already built by the common writer setup.
    let encrypt_ctx = if let Some(parameters) = encryption_parameters {
        let encrypt_ref = local_renumber.reserve_encrypt_dict_slot();
        for container_number in &mut container_numbers {
            if *container_number >= encrypt_ref.number {
                *container_number += 1;
            }
        }
        Some(parameters.into_context(encrypt_ref))
    } else {
        None
    };
    let mut encrypted_string_emitter = encrypt_ctx
        .as_ref()
        .map(EncryptedStringEmitter::from_context);

    // Draw the hint stream's AES IV once for this whole invocation and use it
    // while constructing the one complete hint object — see that function's
    // doc for qpdf's encrypt-once/replay boundary. `--static-aes-iv`
    // keeps using the same fixed test vector every other AES call in this
    // writer already uses, so that path is byte-for-byte unchanged. When no
    // AES cipher is in play (RC4, or `encrypt_ctx` is `None`) the value is
    // never read; `[0u8; 16]` is a harmless placeholder.
    let hint_stream_aes_iv: [u8; 16] = match &encrypt_ctx {
        Some(ctx) if ctx.static_aes_iv => crate::pipeline::aes::static_initialization_vector(),
        Some(ctx) if crate::writer::cipher_needs_aes_iv(ctx.cipher) => {
            let mut iv = [0u8; 16];
            // cov:ignore-start: defensive — the OS CSPRNG does not fail on
            // any platform this crate's test suite runs on; mirrors the
            // same untested-in-practice getrandom failure arm in the writer's
            // canonical stream pipeline.
            getrandom::fill(&mut iv).map_err(|e| {
                crate::Error::Unsupported(format!(
                    "OS CSPRNG (getrandom) unavailable for AES IV generation: {e}"
                ))
            })?;
            // cov:ignore-end
            iv
        }
        _ => [0u8; 16],
    };

    let renumber: &RenumberMap = &local_renumber;

    // Floor the header to 1.5 only when the output actually carries an ObjStm
    // container (qpdf raises the minimum on real emission, not on mode). When
    // all batch lists are empty the placement early-returned and no container
    // is written, so the non-ObjStm linearized goldens stay at the 1.2 floor.
    //
    // Adobe developer-extension propagation (qpdf QPDFWriter.cc L1355-1450
    // `addDeveloperExtension`, and the pairwise `setMinimumPDFVersion`
    // contributions at L806-815 that give V=5 R=6/R=5 `--encrypt` their
    // `/Extensions /ADBE /ExtensionLevel` 8/3 floor) — mirrors
    // `crate::writer::emit_canonical_pdf_inner`'s handling
    // (writer.rs:3154-3238), reusing the SAME pairwise-combine function so
    // the injected `/BaseVersion` always agrees with the header version
    // computed from the identical `(eff_version, eff_ext)` pair. `source_ver`
    // is cloned to an owned `String` first so the borrow-checker sees no
    // conflict between the immutable `pdf.version()` read and the `&mut self`
    // `pdf.adobe_extension_level()` call just below it (mirrors the flat
    // writer's own `source_ver`/`source_ext` locals).
    let source_ver = pdf.version().to_string();
    let source_ext = pdf.adobe_extension_level()?.unwrap_or(0);
    let (eff_version, eff_ext) =
        effective_pdf_version_and_ext(&source_ver, source_ext, options, true, emits_object_streams);
    let part1 = Part1Bytes::build(plan, renumber, eff_version);
    let part1_placeholders = part1.placeholders.clone();
    let part1_dict_region = part1.dict_writable_region.clone();

    let catalog_orig = plan.root_ref.ok_or_else(|| {
        crate::Error::Unsupported(
            "linearization writer: plan.root_ref is None — \
             cannot determine catalog reference for the trailer"
                .to_string(),
        )
    })?;
    let catalog_new_ref: ObjectRef = renumber.new_for_original(catalog_orig).ok_or_else(|| {
        crate::Error::Unsupported(format!(
            "linearization writer: catalog {catalog_orig} is not in RenumberMap \
             (planner / renumber inconsistency)"
        ))
    })?;

    let hint_stream_new_num: u32 = renumber.hint_stream_slot();

    // ------------------------------------------------------------------
    // Build the ObjStm layout from the relocated map (stable across both
    // layout passes). Container + member numbers now live INSIDE the
    // renumber map (relocation appended them), so the pair tables never
    // shift between passes — only the surrounding byte offsets do.
    // ------------------------------------------------------------------
    let objstm_layout =
        ObjStmLayout::build_from_batches(&resolved_batch_plan, &container_numbers, renumber)?;

    // Map each ObjStm container's new object number to the key qpdf uses when
    // ordering a page's shared identifiers. qpdf builds that order from
    // `obj_user_to_objects` (a `std::set<QPDFObjGen>` keyed by object number), so
    // it is the ascending order of the referenced objects' numbers at
    // linearization time (QPDF_linearization.cc:1388-1402).
    //
    // - Generate: the containers are fresh `makeIndirectObject` objects numbered
    //   after every source object in even-split order, hence `(1, split_index)`.
    // - Preserve: the containers reuse the source ObjStm objects and keep their
    //   source numbers, hence `(0, source_container_number)` in the same key
    //   space as plain source objects.
    let container_shared_sort_key: std::collections::BTreeMap<u32, (u8, u32)> = match options
        .object_streams
    {
        crate::writer::ObjectStreamMode::Preserve => {
            let mut keys = std::collections::BTreeMap::new();
            for container in objstm_layout
                .open_document
                .iter()
                .chain(&objstm_layout.part3)
                .chain(&objstm_layout.part4)
            {
                let source_container_number =
                    preserved_source_container_number(container, &source_container_by_member)?;
                keys.insert(container.container_new_num, (0, source_container_number));
            }
            keys
        }
        _ => {
            use crate::linearization::plan::objstm_membership_linearized_with_eligibility;
            let assigned = plan.renumber_assigned_refs();
            let membership = objstm_membership_linearized_with_eligibility(
                pdf,
                &assigned,
                plan.optimization
                    .as_ref()
                    .and_then(|optimization| optimization.generate_objstm_eligible()),
            )?; // cov:ignore: closing line of a multi-line call; llvm-cov misattributes the hit count to the previous line, not an untested branch
            let mut rank = std::collections::BTreeMap::new();
            for (split_index, members) in membership.iter().enumerate() {
                // `objstm_membership_linearized` drops empty containers, so
                // `first()` is always present.
                let first = *members
                    .first()
                    .expect("objstm_membership_linearized never yields an empty container");
                // Only rank containers the Generate layout actually
                // materialized (members present in `member_to_container`).
                if let Some(&(container_num, _)) = objstm_layout.member_to_container.get(&first) {
                    rank.insert(container_num, (1, split_index as u32));
                }
            }
            rank
        }
    };

    // Highest object number actually used in the output.  After relocation
    // the renumber map already counts every plain object, every ObjStm
    // container, every member, AND both split xref-stream objects (the two
    // reserved slots), so `len()` is the highest slot.  Adding 1 yields the
    // /Size value (numbering is 1-based; Size counts the free entry at
    // object 0).  No extra object number is consumed for the xref stream(s)
    // on the ObjStm path — they live in their pre-reserved slots.
    let total_count: u32 = renumber
        .len()
        .checked_add(1)
        .and_then(|n| u32::try_from(n).ok())
        .ok_or_else(|| {
            crate::Error::Unsupported(
                "linearization writer: /Size overflows u32 (too many objects / \
                 ObjStm containers)"
                    .to_string(),
            )
        })?;

    let info_handle = source_trailer_handle.try_get_key(b"/Info")?;
    let info_new_ref: Option<ObjectRef> = plan
        .raw
        .info
        .and_then(|object_gen| renumber.new_for_raw(object_gen))
        .or_else(|| {
            info_handle
                .qpdf_obj_gen()
                .and_then(|object_gen| renumber.new_for_raw(object_gen))
        });

    let first_page_object_new_num: u32 = {
        let first_page_hint = plan.page_hints.first().ok_or_else(|| {
            crate::Error::Unsupported(
                "linearization plan has no page hints (empty document?)".to_string(),
            )
        })?;
        renumber
            .new_for_original(first_page_hint.page_ref)
            .ok_or_else(|| {
                crate::Error::Unsupported(format!(
                    "first-page page_ref {} has no renumber entry",
                    first_page_hint.page_ref,
                ))
            })?
            .number
    };

    let second_half_container_nums: std::collections::BTreeSet<u32> = objstm_layout
        .part4
        .iter()
        .map(|c| c.container_new_num)
        .collect();
    let open_document_container_nums: std::collections::BTreeSet<u32> = objstm_layout
        .open_document
        .iter()
        .map(|c| c.container_new_num)
        .collect();
    // Outlines Hint Table inputs (qpdf in_outlines / calculateHOutline).
    // `None` when the document has no outlines, in which case no `/O` key or
    // outline table is emitted (byte-identical to the no-outline path).
    let outlines = plan
        .optimization
        .as_ref()
        .map(|optimization| optimization.raw_objects_for_root_key(b"Outlines"))
        .unwrap_or_default();
    let outline_info = compute_outline_hint_info(&outlines, pdf, renumber, &objstm_layout)?;
    // qpdf routes the primary hint stream through its global stream-compression
    // setting as well: Preserve and Uncompress emit the raw bit-packed table
    // without `/Filter`; Compress emits `/FlateDecode`.
    let structural_streams_filtered =
        matches!(effective_stream_policy(options), Some(CompressStreams::Yes));
    let raw_removed_refs: BTreeSet<QpdfObjGen> = plan
        .removed_refs
        .iter()
        .filter_map(|object_ref| QpdfObjGen::try_from_object_ref(*object_ref).ok())
        .collect();
    let raw_content_normalize_refs = &plan.raw.content_normalize_refs;
    // ------------------------------------------------------------------
    // Build qpdf's first-pass representation unconditionally. It is the source
    // for hint-table offsets and lengths, and is also the source of the
    // incremental deterministic-ID digest and optional pass-1 artifact.
    //
    // qpdf seeds the linearized `--deterministic-id` from its *first* write pass
    // — a throwaway buffer with an empty parameter dict, no hint stream, and an
    // unresolved first-page xref (`QPDFWriter::writeLinearized` →
    // `computeDeterministicIDData`, qpdf 11.9.0; the hint stream is written only
    // afterwards). That pass-1 buffer is loop-invariant (it carries no hint
    // stream, so it never depends on a later hint-object splice), so emit it
    // once here and digest it. This pass-1 digest is computed for every
    // deterministic-ID route. The final pass receives a trailer view with the
    // computed identifier and emits it directly at every `/ID` site, so no
    // post-write scan or seekable output buffer is needed. The pass-1 buffer
    // itself keeps the all-zero `/ID` placeholder (its trailer writers get
    // `id_writer = None`), exactly as qpdf's pass 1 does, so the digest depends
    // only on the input and is stable.
    let pass1_part1 = build_pass1_part1(&part1);
    let mut pass1_target = Pass1OutputTarget::new(pass1_path)?;
    let mut pass1_sink = OutputSink::new(&mut pass1_target);
    if deterministic_id {
        pass1_sink.begin_digest();
    }
    let pass1_result = do_write_pass(
        plan,
        renumber,
        &raw_removed_refs,
        raw_content_normalize_refs,
        pdf,
        &mut pass1_sink,
        &pass1_part1,
        catalog_new_ref,
        hint_stream_new_num,
        total_count,
        info_new_ref,
        first_page_object_new_num,
        None,
        structural_streams_filtered,
        &pass1_source_trailer,
        &objstm_layout,
        &relocation,
        options,
        true,
        None,
        encrypt_ctx.as_ref(),
        encrypted_string_emitter.as_mut(),
        eff_version,
        eff_ext,
        None,
    );
    let pass1_finish = pass1_sink.finish_document();
    let pass1_file_length = pass1_sink.position_usize()?;
    let pass1_digest = if deterministic_id {
        Some(pass1_sink.take_digest())
    } else {
        None
    };
    drop(pass1_sink);
    let mut pass1_output = pass1_result?; // cov:ignore: pass-1 mode uses the same write path as the successful final pass while omitting only the hint object.
    pass1_finish?;
    let pass1_digest = pass1_digest.transpose()?;

    let classic_det_id: Option<(Vec<u8>, [u8; 16])> = if deterministic_id {
        Some(crate::writer::compute_deterministic_id_from_digest(
            pass1_digest.expect("deterministic pass-1 digest is enabled"),
            &det_id_info_suffix,
            det_id_source_id0.as_deref(),
        ))
    } else {
        None
    };

    // ------------------------------------------------------------------
    // qpdf's pass-1 hint generation is writer-owned and does not depend on
    // the input reader type. Keep it outside the generic linearized writer so
    // every output target shares one code and allocation boundary.
    let hint_stream_object = build_hint_stream_from_pass1(&HintStreamBuildInput {
        plan,
        renumber,
        objstm_layout: &objstm_layout,
        container_shared_sort_key: &container_shared_sort_key,
        pass1_output: &pass1_output,
        hint_stream_new_num,
        second_half_container_nums: &second_half_container_nums,
        open_document_container_nums: &open_document_container_nums,
        outline_info: outline_info.as_ref(),
        structural_streams_filtered,
        encrypt_ctx: encrypt_ctx.as_ref(),
        hint_stream_aes_iv,
    })?;

    if pass1_path.is_some() {
        let debug_comments = format!(
            "% hint_offset={}\n\
             % hint_length={}\n\
             % second_xref_offset={}\n\
             % second_xref_end={}\n",
            pass1_output.hint_stream_offset,
            hint_stream_object.len(),
            pass1_output.last_xref_offset,
            pass1_output.second_xref_end
        );
        // qpdf appends these comments immediately after closing the pass-1
        // pipeline and before starting pass 2 (`QPDFWriter.cc:2886-2900`).
        pass1_target.write_debug_comments(debug_comments.as_bytes());
    }

    // qpdf's second pass uses the pass-1 coordinates as its source of truth:
    // the framed hint object is inserted at its recorded slot, so every later
    // offset receives exactly one hint-length adjustment. Build that physical
    // final map before emitting anything to the configured sink. This is what
    // lets the first-page xref and the compact Part-1 dictionary be written
    // forward instead of repaired after a non-seekable sink has consumed them.
    let hint_stream_length = hint_stream_object.len();
    let hint_stream_offset = pass1_output.hint_stream_offset;
    for (&number, offset) in pass1_output.xref_offsets.iter_mut() {
        if number != hint_stream_new_num && *offset >= hint_stream_offset {
            let adjusted = (*offset).checked_add(hint_stream_length).ok_or_else(|| {
                // cov:ignore-start: supported PDF offsets fit in usize
                crate::Error::Unsupported(
                    "linearization final xref offset exceeds usize range".to_string(),
                )
                // cov:ignore-end
            })?; // cov:ignore: supported PDF offsets fit in usize
            *offset = adjusted;
        }
    }
    pass1_output
        .xref_offsets
        .insert(hint_stream_new_num, hint_stream_offset);

    let final_main_xref_offset = pass1_output
        .last_xref_offset
        .checked_add(hint_stream_length)
        .ok_or_else(|| {
            // cov:ignore-start: supported PDF offsets fit in usize
            crate::Error::Unsupported(
                "linearization final main xref offset exceeds usize range".to_string(),
            )
            // cov:ignore-end
        })?; // cov:ignore: supported PDF offsets fit in usize
    let final_end_of_first_page_offset = pass1_output
        .end_of_first_page_offset
        .checked_add(hint_stream_length)
        .ok_or_else(|| {
            // cov:ignore-start: supported PDF offsets fit in usize
            crate::Error::Unsupported(
                "linearization final first-page end exceeds usize range".to_string(),
            )
            // cov:ignore-end
        })?; // cov:ignore: supported PDF offsets fit in usize
    let final_last_xref_first_entry_offset = pass1_output
        .last_xref_first_entry_offset
        .checked_add(hint_stream_length)
        .ok_or_else(|| {
            // cov:ignore-start: supported PDF offsets fit in usize
            crate::Error::Unsupported(
                "linearization final xref entry offset exceeds usize range".to_string(),
            )
            // cov:ignore-end
        })?; // cov:ignore: supported PDF offsets fit in usize
    let final_file_length = pass1_file_length
        .checked_add(hint_stream_length)
        .ok_or_else(|| {
            // cov:ignore-start: supported PDF offsets fit in usize
            crate::Error::Unsupported(
                "linearization final file length exceeds usize range".to_string(),
            )
            // cov:ignore-end
        })?; // cov:ignore: supported PDF offsets fit in usize
    let page_count = plan.page_hints.len() as u32;

    let mut final_part1_offsets = LinearizedOffsets {
        file_length: final_file_length,
        hint_stream_offset: pass1_output.hint_stream_offset,
        hint_stream_length,
        first_page_object_new_num,
        end_of_first_page_offset: final_end_of_first_page_offset,
        last_xref_keyword_offset: final_main_xref_offset,
        last_xref_offset: final_last_xref_first_entry_offset.saturating_sub(1),
        page_count,
        part1_placeholders: part1_placeholders.clone(),
        xref_offsets: BTreeMap::new(),
        first_trailer_prev_range: 0..0,
        dict_writable_region: part1_dict_region.clone(),
    };
    let mut final_part1 = part1.clone();
    crate::linearization::back_patch::back_patch_param_dict(
        &mut final_part1.bytes,
        &mut final_part1_offsets,
    )?; // cov:ignore: final values are bounded by the fixed Part-1 reserve
    let final_layout = FinalLinearizedLayout {
        xref_offsets: &mut pass1_output.xref_offsets,
        main_xref_offset: final_main_xref_offset,
    };

    // The deterministic ID is known now, before the final pass. Install it in
    // the final trailer view so both classic and xref-stream trailers emit it
    // directly; only pass 1 keeps the all-zero qpdf placeholder.
    let final_source_trailer = if let Some((id0, id1)) = &classic_det_id {
        let trailer = source_trailer_handle.shallow_copy()?;
        trailer.replace_key(
            b"/ID",
            ObjectHandle::array(vec![
                ObjectHandle::string(id0.clone()),
                ObjectHandle::string(id1.to_vec()),
            ]),
        )?; // cov:ignore: final trailer clone accepts the validated ID handle
        trailer
    } else {
        source_trailer_handle.shallow_copy()?
    };

    // Final pass: write the layout with the exact hint object generated
    // above. The pass-1 virtual offsets and the spliced object length are
    // therefore related by qpdf's adjusted-offset rule.
    //
    // The final trailer view already contains the computed identifier, so
    // both classic and ObjStm/xref-stream routes write the final `/ID` bytes
    // directly while the sink remains forward-only.
    let streaming_output = final_output.is_some();
    let mut final_bytes = Vec::new();
    let target: &mut dyn OutputTarget = match final_output {
        Some(target) => target,
        None => &mut final_bytes,
    };
    let mut final_sink = OutputSink::new(target);
    let final_result = do_write_pass(
        plan,
        renumber,
        &raw_removed_refs,
        raw_content_normalize_refs,
        pdf,
        &mut final_sink,
        &final_part1,
        catalog_new_ref,
        hint_stream_new_num,
        total_count,
        info_new_ref,
        first_page_object_new_num,
        Some(hint_stream_object.as_slice()),
        structural_streams_filtered,
        &final_source_trailer,
        &objstm_layout,
        &relocation,
        options,
        false,
        None,
        encrypt_ctx.as_ref(),
        encrypted_string_emitter.as_mut(),
        eff_version,
        eff_ext,
        Some(final_layout),
    );
    let final_finish = final_sink.finish_document();
    let final_output_length = final_sink.position_usize()?;
    drop(final_sink);
    let final_output = final_result?; // cov:ignore: pass 2 reuses the validated plan and fixed layout after pass 1 succeeds; this is only defensive error propagation.
    final_finish?;
    let LinearizedPassOutput {
        xref_offsets: _final_xref_offsets,
        first_page_xref_offset: final_first_page_xref_offset,
        hint_stream_offset: final_hint_stream_offset,
        hint_stream_obj_total_len: final_hint_stream_obj_total_len,
        end_of_first_page_offset: final_end_of_first_page_offset,
        last_xref_offset: final_last_xref_keyword_offset,
        last_xref_first_entry_offset: final_last_xref_first_entry_offset,
        second_xref_end: _final_second_xref_end,
        first_trailer_prev_range: final_first_trailer_prev_range,
        id_ranges: _final_id_ranges,
    } = final_output;

    let mut old_to_new: BTreeMap<ObjectRef, ObjectRef> = renumber
        .iter_in_layout_order()
        .map(|(new_ref, old_ref)| (old_ref, new_ref))
        .collect();

    // qpdf's getRenumberedObjGen reports the source ObjStm container's logical
    // output identity even though the output container is a freshly serialized
    // object. The source container is intentionally absent from the ordinary
    // linearization plan (only its members are body objects), so add this
    // canonical writer-result mapping from the resolved Preserve layout. This
    // lets test_renumber compare the same source object universe as qpdf
    // without making the helper reconstruct container ownership.
    if options.object_streams == crate::writer::ObjectStreamMode::Preserve
        && !objstm_layout.is_empty()
    {
        for container in objstm_layout
            .open_document
            .iter()
            .chain(&objstm_layout.part3)
            .chain(&objstm_layout.part4)
        {
            let source_container_number =
                preserved_source_container_number(container, &source_container_by_member)?;
            old_to_new.insert(
                ObjectRef::new(source_container_number, 0),
                ObjectRef::new(container.container_new_num, 0),
            );
        }
    }

    let mut written_xref = pass1_output
        .xref_offsets
        .iter()
        .map(|(&number, &offset)| {
            (
                ObjectRef::new(number, 0),
                crate::XrefEntry::Uncompressed {
                    offset: offset as u64,
                },
            )
        })
        .collect::<BTreeMap<_, _>>();
    if !objstm_layout.is_empty() {
        // cov:ignore-start: every non-empty ObjStm layout pass records its first-page xref offset;
        // a missing value is an internal invariant failure, not a supported input shape.
        let first_xref_offset = final_first_page_xref_offset.ok_or_else(|| {
            crate::Error::Unsupported(
                "linearization result: missing first-page xref offset".to_string(),
            )
        })?;
        // cov:ignore-end
        written_xref.insert(
            ObjectRef::new(relocation.first_xref_slot, 0),
            crate::XrefEntry::Uncompressed {
                offset: first_xref_offset as u64,
            },
        );
        written_xref.insert(
            ObjectRef::new(relocation.main_xref_slot, 0),
            crate::XrefEntry::Uncompressed {
                offset: final_last_xref_keyword_offset as u64,
            },
        );
        for container in objstm_layout
            .open_document
            .iter()
            .chain(&objstm_layout.part3)
            .chain(&objstm_layout.part4)
        {
            for (index, &(_original, new_ref)) in container.members.iter().enumerate() {
                written_xref.insert(
                    new_ref,
                    crate::XrefEntry::Compressed {
                        stream: container.container_new_num,
                        index: index as u32,
                    },
                );
            }
        }
    }

    // Move the one writer-owned final xref map into the in-memory inspection
    // metadata after all WriterResult consumers have read it.
    let offsets = LinearizedOffsets {
        file_length: final_output_length,
        hint_stream_offset: final_hint_stream_offset,
        hint_stream_length: final_hint_stream_obj_total_len,
        first_page_object_new_num,
        end_of_first_page_offset: final_end_of_first_page_offset,
        last_xref_keyword_offset: final_last_xref_keyword_offset,
        // /T = first_entry_pos - 1, matching qpdf's convention.
        // qpdf's check validates: file_T == first_entry_pos - 1.
        last_xref_offset: final_last_xref_first_entry_offset.saturating_sub(1),
        page_count,
        part1_placeholders: final_part1_offsets.part1_placeholders.clone(),
        xref_offsets: pass1_output.xref_offsets,
        first_trailer_prev_range: final_first_trailer_prev_range,
        dict_writable_region: part1_dict_region,
    };

    let writer_result = WriterResult::new(old_to_new, written_xref);
    let document = if streaming_output {
        None
    } else {
        Some(LinearizedDocument {
            bytes: final_bytes,
            offsets: offsets.clone(),
        })
    };
    Ok(LinearizedWriteResult {
        document,
        writer_result,
    })
}

/// Inputs for the qpdf-shaped pass-1 hint generation and framing boundary.
///
/// This deliberately contains no `Pdf<R>`: qpdf's hint tables are generated
/// from pass-1 coordinates and writer-owned layout state, then the completed
/// framed object is replayed unchanged during pass 2.
struct HintStreamBuildInput<'a> {
    plan: &'a LinearizationPlan,
    renumber: &'a RenumberMap,
    objstm_layout: &'a ObjStmLayout,
    container_shared_sort_key: &'a BTreeMap<u32, (u8, u32)>,
    pass1_output: &'a LinearizedPassOutput,
    hint_stream_new_num: u32,
    second_half_container_nums: &'a BTreeSet<u32>,
    open_document_container_nums: &'a BTreeSet<u32>,
    outline_info: Option<&'a OutlineHintInfo>,
    structural_streams_filtered: bool,
    encrypt_ctx: Option<&'a crate::writer::EncryptionContext>,
    hint_stream_aes_iv: [u8; 16],
}

/// Build qpdf's complete hint-stream object from one pass-1 result.
///
/// Keeping the pass-1 table construction, selected payload encoding, and
/// dictionary/encryption framing behind a non-generic boundary prevents the
/// `write_linearized_impl<R>` monomorphizations from each carrying a copy of
/// this writer-only work. The returned bytes are the single object replayed by
/// pass 2, matching qpdf's generateHintStream + writeHintStream boundary
/// (QPDF_linearization.cc:1758-1795, QPDFWriter.cc:2287-2327).
#[inline(never)]
fn build_hint_stream_from_pass1(input: &HintStreamBuildInput<'_>) -> Result<Vec<u8>> {
    let plan = input.plan;
    let renumber = input.renumber;
    let objstm_layout = input.objstm_layout;
    let container_shared_sort_key = input.container_shared_sort_key;
    let pass1_output = input.pass1_output;
    let hint_stream_new_num = input.hint_stream_new_num;
    let second_half_container_nums = input.second_half_container_nums;
    let open_document_container_nums = input.open_document_container_nums;
    let outline_info = input.outline_info;
    let structural_streams_filtered = input.structural_streams_filtered;
    let encrypt_ctx = input.encrypt_ctx;
    let hint_stream_aes_iv = input.hint_stream_aes_iv;

    // ------------------------------------------------------------------
    // Build every hint table once from qpdf's pass-1 output. Pass 1 omits the
    // hint object, so these offsets are already the virtual coordinates that
    // qpdf stores in the hint tables.
    // ------------------------------------------------------------------
    let xref_offsets = &pass1_output.xref_offsets;
    let hint_stream_offset = pass1_output.hint_stream_offset;
    let last_xref_offset = pass1_output.last_xref_offset;
    // ------------------------------------------------------------------
    // Compute per-object byte lengths from pass 1.
    // Use the xref keyword offset (not first_entry_offset) for length computation.
    // ------------------------------------------------------------------
    let byte_lengths = compute_byte_lengths(
        xref_offsets,
        last_xref_offset,
        hint_stream_new_num,
        renumber.param_dict_ref().number,
    );

    // ------------------------------------------------------------------
    // Per-page byte lengths.
    //
    // Page 0 owns the shared objects physically (they sit before /E),
    // so its byte_length includes Part 2 + Part 3.  Pages 1..N use only
    // their own private objects.
    // ------------------------------------------------------------------
    // Members routed into a Part-3 ObjStm have no standalone bytes (they
    // live inside the container); their physical contribution is the
    // container object itself, which IS in `byte_lengths`.  Sum the
    // still-plain part3 objects, then add every Part-3 container's bytes.
    let part3_plain_len: u64 = plan
        .part3_objects
        .iter()
        .filter(|orig| {
            !objstm_layout.member_to_container.contains_key(orig)
                && !objstm_layout
                    .source_container_numbers
                    .contains(&orig.number)
        })
        .map(|orig| {
            renumber
                .new_for_original(*orig)
                .and_then(|new_ref| byte_lengths.get(&new_ref.number).copied())
                .unwrap_or(0) as u64
        })
        .sum();
    let raw_plain_byte_len = |orig: &QpdfObjGen| -> u64 {
        renumber
            .new_for_raw(*orig)
            .and_then(|new_ref| byte_lengths.get(&new_ref.number).copied())
            .unwrap_or(0) as u64
    };
    let raw_part3_plain_len: u64 = plan
        .raw
        .part3_objects
        .iter()
        .filter(|object_gen| object_gen.to_object_ref().is_none())
        .map(raw_plain_byte_len)
        .sum();
    let part3_container_len: u64 = objstm_layout
        .part3
        .iter()
        .map(|c| byte_lengths.get(&c.container_new_num).copied().unwrap_or(0) as u64)
        .sum();
    let part3_byte_len: u64 = part3_plain_len + raw_part3_plain_len + part3_container_len;

    // Manually-constructed plans must keep `per_page_private_objects`
    // aligned with `page_hints` (one entry per page).
    validate_per_page_private_objects(plan)?;

    // Containers a non-first page must not add to its byte length: only a
    // part7 container owned entirely by this one page is a section object.
    // A page-private object that the even split placed in the first-page
    // (part6) container or in a part8 (multi-page-shared) container is
    // physically outside this page's section, so its container's bytes belong
    // elsewhere. Same classification as the per-page object-count fold.
    let non_page_owned = crate::linearization::hint_page::non_page_owned_containers(
        plan,
        &objstm_layout.member_to_container,
    );
    let plain_byte_len = |orig: &ObjectRef| -> u64 {
        renumber
            .new_for_original(*orig)
            .and_then(|new_ref| byte_lengths.get(&new_ref.number).copied())
            .unwrap_or(0) as u64
    };
    let per_page_byte_lengths: Vec<u64> = plan
        .per_page_private_objects
        .iter()
        .enumerate()
        .map(|(page_idx, privates)| {
            if page_idx == 0 {
                // Page 0: Part 2 (always plain) + Part 3 (plain + containers)
                // + Part 6 outline plain objects (UseOutlines, classic path).
                // ObjStm outline members are already counted inside Part-3
                // containers (part3_container_len), so only plain ones are added.
                let part2_len: u64 = privates
                    .iter()
                    .filter(|orig| {
                        !objstm_layout.member_to_container.contains_key(*orig)
                            && !objstm_layout
                                .source_container_numbers
                                .contains(&orig.number)
                    })
                    .map(plain_byte_len)
                    .sum::<u64>()
                    + plan
                        .raw
                        .part2_objects
                        .iter()
                        .filter(|object_gen| object_gen.to_object_ref().is_none())
                        .map(raw_plain_byte_len)
                        .sum::<u64>();
                let part6_plain_len: u64 = plan
                    .raw
                    .outline_first_page_members
                    .iter()
                    .filter(|object_gen| object_gen.to_object_ref().is_none())
                    .map(raw_plain_byte_len)
                    .sum();
                let part6_public_plain_len: u64 = plan
                    .part6_outline_objects
                    .iter()
                    .filter(|orig| {
                        !objstm_layout.member_to_container.contains_key(*orig)
                            && !objstm_layout
                                .source_container_numbers
                                .contains(&orig.number)
                    })
                    .map(plain_byte_len)
                    .sum();
                part2_len + part3_byte_len + part6_public_plain_len + part6_plain_len
            } else {
                // Pages 1..N: a private compressed into this page's own part7
                // ObjStm has no standalone bytes — its physical contribution is
                // the container object, counted ONCE. Containers not owned by
                // this single page (first-page part6, or multi-page part8) are
                // excluded; their bytes live in another section.
                let mut len = 0u64;
                let mut containers: std::collections::BTreeSet<u32> =
                    std::collections::BTreeSet::new();
                for orig in privates {
                    match objstm_layout.member_to_container.get(orig) {
                        Some(&(container_num, _)) => {
                            if !non_page_owned.contains(&container_num) {
                                containers.insert(container_num);
                            }
                        }
                        None if objstm_layout
                            .source_container_numbers
                            .contains(&orig.number) =>
                        {
                            // cov:ignore-start: a planned Preserve source container always has a placed renumber entry
                            if let Some(new_ref) = renumber.new_for_original(*orig) {
                                if !non_page_owned.contains(&new_ref.number) {
                                    containers.insert(new_ref.number);
                                }
                            }
                            // cov:ignore-end
                        }
                        None => len += plain_byte_len(orig),
                    }
                }
                len += plan
                    .raw
                    .per_page_private_objects
                    .get(page_idx)
                    .into_iter()
                    .flatten()
                    .filter(|object_gen| object_gen.to_object_ref().is_none())
                    .map(raw_plain_byte_len)
                    .sum::<u64>();
                len + containers
                    .iter()
                    .map(|c| byte_lengths.get(c).copied().unwrap_or(0) as u64)
                    .sum::<u64>()
            }
        })
        .collect();

    // ------------------------------------------------------------------
    // Patch hint tables.
    // ------------------------------------------------------------------
    let mut po_table = PageOffsetHintTable::from_plan(
        plan,
        renumber,
        &objstm_layout.member_to_container,
        container_shared_sort_key,
        second_half_container_nums,
        open_document_container_nums,
    );
    let mut so_table = SharedObjectHintTable::from_plan(
        plan,
        renumber,
        &objstm_layout.member_to_container,
        second_half_container_nums,
        open_document_container_nums,
    );

    // location_of_first_page = byte offset of the hint stream object itself.
    //
    // Per PDF Annex F and qpdf's implementation, this field stores the absolute
    // byte offset of the hint stream object (the start of the first-page section).
    // qpdf interprets it as: actual_page_object_offset = location_of_first_page + H_length,
    // where H_length is the full byte span of the hint stream object (stored as /H[1]).
    //
    // Since the hint stream always starts immediately after Part 1, and Part 1 length
    // is constant across both passes, hint_stream_offset is stable.
    po_table.header.location_of_first_page = hint_stream_offset as u64;

    // Page length fields.
    //
    // Content-stream fields (items 6-9 of header, items 6-7 of each per-page
    // entry) follow qpdf's heuristic from QPDF_linearization.cc:1786-1808:
    // since the page objects are not interleaved with the content stream,
    // qpdf reuses the page-length values for the content-length fields and
    // leaves the content-offset fields at 0 (matching Adobe implementation
    // note 127).  Mirroring this gives readers a usable initial-rendering
    // hint and keeps us on the path toward bytes-identical hint streams.
    let least_pl = per_page_byte_lengths.iter().copied().min().unwrap_or(0);
    let max_pl = per_page_byte_lengths.iter().copied().max().unwrap_or(0);
    let bits_delta_pl = bits_needed(max_pl.saturating_sub(least_pl));
    po_table.header.least_page_length = least_pl;
    po_table.header.bits_page_length_delta = bits_delta_pl;
    po_table.header.least_content_length = least_pl;
    po_table.header.bits_content_length_delta = bits_delta_pl;
    // `per_page_byte_lengths.len() == page_hints.len() ==
    // po_table.entries.len()` is enforced by the length check at the
    // top of this block, so zip is bounds-check-free.
    for (entry, &bl) in po_table
        .entries
        .iter_mut()
        .zip(per_page_byte_lengths.iter())
    {
        let delta = bl.saturating_sub(least_pl);
        entry.page_length_minus_least = delta;
        entry.content_stream_length = delta;
    }

    // Shared object table fields.
    //
    // The shared hint table covers all plan.shared_hints entries (part2
    // entries first, then part3 entries).  Per qpdf's checkHSharedObject,
    // the table starts at the first-page section's first object (part2[0] =
    // page dict), so we use shared_hints[0] for the location field.
    // Collect byte lengths for all shared hint entries in plan order.
    //
    // Resolve renumber + pass-1 byte-length lookups strictly:
    // a missing entry indicates a planner / renumber inconsistency or
    // a pass-1 coverage bug, both of which would silently produce
    // a hint table with `least_length = 0` / `header.location = 0` if
    // we substituted zeros.  Bubble Err so the writer fails loudly
    // and the caller can surface the broken plan.
    // Iterate the FOLDED shared list (the same list the hint tables are
    // built from): first-page ObjStm members are folded into a single
    // container entry whose byte length is the container object's own
    // length.  A folded container entry carries the container's *new*
    // object number with the sentinel generation `u16::MAX` (see
    // `LinearizationPlan::canonical_shared_hints`); every other entry
    // carries a real original ref (generation 0).  We discriminate by
    // that sentinel — no live object uses generation `u16::MAX` — so a
    // real original ref whose number happens to coincide with a
    // container's new number can never be mistaken for a container (and
    // vice versa).
    let folded_shared = plan.canonical_raw_shared_hints(
        &objstm_layout.member_to_container,
        renumber,
        second_half_container_nums,
        open_document_container_nums,
    );
    let shared_section_lens: Vec<u64> = folded_shared
        .iter()
        .map(|h| -> Result<u64> {
            // Folded container entry: the synthetic ref's sentinel
            // generation identifies it. Use the container object's
            // own byte length.
            if let Some(container) = h.container {
                // cov:ignore-start: unreachable — a first-half
                // container is always emitted (and probed) before
                // this back-patch, so its byte length is present; the
                // guard defends against a layout/probe mismatch.
                let len = byte_lengths.get(&container).copied().ok_or_else(|| {
                    crate::Error::Unsupported(format!(
                        "shared hint container (new #{container}) has no probed byte length",
                    ))
                })?;
                // cov:ignore-end
                return Ok(len as u64);
            }
            // cov:ignore-start: unreachable — non-container shared
            // hints are plan objects with a renumber entry, and every
            // plain shared object is emitted (and probed) before this
            // back-patch; absence signals a planner/renumber/probe
            // inconsistency.
            let object = h.object.ok_or_else(|| {
                crate::Error::Unsupported(
                    "shared hint entry has neither a raw object nor a container".to_string(),
                )
            })?;
            let new_ref = renumber.new_for_raw(object).ok_or_else(|| {
                crate::Error::Unsupported(format!(
                    "shared hint raw object {} {} has no renumber entry",
                    object.get_obj(),
                    object.get_gen()
                ))
            })?;
            let len = byte_lengths.get(&new_ref.number).copied().ok_or_else(|| {
                crate::Error::Unsupported(format!(
                    "shared hint raw object {} {} (new #{}) has no probed byte length",
                    object.get_obj(),
                    object.get_gen(),
                    new_ref.number
                ))
            })?;
            // cov:ignore-end
            Ok(len as u64)
        })
        .collect::<Result<Vec<_>>>()?;

    let least = shared_section_lens.iter().copied().min().unwrap_or(0);
    let max = shared_section_lens.iter().copied().max().unwrap_or(0);
    so_table.header.least_length = least;
    so_table.header.bits_length_delta = bits_needed(max.saturating_sub(least));

    // Location (item 2): qpdf's pass-1 virtual byte offset of the first
    // Part-8 shared object. In the final file qpdf's
    // `adjusted_offset(location)` adds the exact `/H[1]` bytes that are
    // spliced between Part 1 and this object.
    //
    // This is only meaningful when nshared_total > nshared_first_page
    // (i.e., there are Part-8 objects).  When part4_other_pages_shared
    // is empty the location value is ignored (qpdf Implementation Note 131).
    // `from_plan` already set `first_object_number` to the FIRST
    // SECOND-HALF (Part-8) shared entry — the container number when that
    // entry is an ObjStm container, or the object's own number when it is
    // plain — and crucially EXCLUDES part4-shared objects that the global
    // even split placed in a first-page (part6) container (those are
    // before /E, not Part-8). It is 0 when there are no Part-8 entries
    // (location is then ignored per Implementation Note 131). Look up that
    // object's probe offset for the `location` field; the object number
    // itself is already correct, so it is not overwritten here.
    let first_part8_lookup_num = so_table.header.first_object_number;
    if first_part8_lookup_num != 0 {
        let first_part8_off = xref_offsets
            .get(&first_part8_lookup_num)
            .copied()
            // cov:ignore-start: the first Part-8 entry (a container or a
            // plain Part-8 object) is always probed in the same pass that
            // fills `xref_offsets`, so this lookup never misses for a
            // well-formed plan.
            .ok_or_else(|| {
                crate::Error::Unsupported(format!(
                    "first Part-8 shared object (lookup #{first_part8_lookup_num}) \
                         has no probed offset"
                ))
            })?;
        // cov:ignore-end
        so_table.header.location = first_part8_off as u64;
    }

    // Per-object length_minus_least.  group_offset is no longer a
    // per-entry field (see hint_stream::encode_shared_object_entries:
    // it does not match Annex F.4.5 / qpdf's HSharedObjectEntry layout
    // and was previously emitting an extra 32 bits per entry that
    // qpdf misinterpreted as the next entry's length delta).
    // `nobjects_minus_one` stays at 0 from `from_plan`.  `so_table.objects`
    // and `shared_section_lens` are both built from the folded shared
    // list, so zipping keeps the per-object length deltas aligned.
    for (obj, &len) in so_table.objects.iter_mut().zip(&shared_section_lens) {
        obj.length_minus_least = (len.saturating_sub(least)) as u32;
    }

    // Patch the Outlines Hint Table (qpdf calculateHOutline): fill the
    // per-pass offset/length for the first outline unit (see
    // `build_outline_hint_table`).
    let outline_table = outline_info
        .as_ref()
        .map(|info| build_outline_hint_table(info, xref_offsets, &byte_lengths))
        .transpose()?;

    // Re-encode hint stream with patched tables.
    let hint_mode = if structural_streams_filtered {
        HintStreamMode::Compressed
    } else {
        HintStreamMode::Uncompressed
    };
    let new_hint =
        encode_hint_stream_selected(&po_table, &so_table, outline_table.as_ref(), hint_mode)?;
    let new_shared_s = new_hint.shared_section_offset_in_uncompressed;
    let new_outline_o = new_hint.outline_section_offset_in_uncompressed;

    // qpdf frames and encrypts the complete hint object once after pass 1.
    // Pass 2 receives this exact buffer and splices it without re-encoding
    // the payload or drawing another IV.
    let mut hint_stream_object = Vec::new();
    append_hint_stream_object(
        &mut hint_stream_object,
        ObjectRef::new(hint_stream_new_num, 0),
        &new_hint.payload,
        new_shared_s,
        new_outline_o,
        structural_streams_filtered,
        encrypt_ctx,
        hint_stream_aes_iv,
    )?; // cov:ignore: internally-built hint payload and encryption context make this only a defensive propagation boundary.
    Ok(hint_stream_object)
}

// ---------------------------------------------------------------------------
// Unit tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use md5::Digest as _;
    use std::io::Cursor;
    use std::rc::Rc;

    use crate::writer::{output::OutputSink, ProgressReporter, WriteCipher};

    fn test_encryption_context() -> crate::writer::EncryptionContext {
        crate::writer::EncryptionContext {
            encrypt_dict: ObjectHandle::dictionary(Vec::new()),
            file_key: vec![1; 5],
            cipher: WriteCipher::PerObject(crate::encryption::standard::ObjectKeyAlg::Rc4),
            encryption_v: 2,
            encryption_r: 3,
            encrypt_ref: ObjectRef::new(99, 0),
            id0: b"id".to_vec(),
            static_aes_iv: true,
            encrypt_metadata: true,
            metadata_ref: None,
        }
    }

    #[test]
    fn part7_owner_uses_the_manual_plan_fallback_without_a_set_table() {
        let member = ObjectRef::new(7, 0);
        let other = ObjectRef::new(8, 0);
        let plan = LinearizationPlan {
            per_page_private_objects: vec![vec![], vec![member]],
            ..LinearizationPlan::default()
        };

        assert_eq!(part7_owner_for_plan(&plan, member), Some(1));
        assert_eq!(part7_owner_for_plan(&plan, other), None);
    }

    #[test]
    fn raw_second_half_anchor_sees_raw_part7_plain_peers() {
        let member = ObjectRef::new(7, 0);
        let page = ObjectRef::new(2, 0);
        let plan = LinearizationPlan {
            page_hints: vec![
                crate::linearization::plan::PageHintEntry::placeholder(ObjectRef::new(1, 0)),
                crate::linearization::plan::PageHintEntry::placeholder(page),
            ],
            per_page_private_objects: vec![vec![], vec![page, member]],
            raw: crate::linearization::plan::RawLinearizationPlan {
                per_page_private_objects: vec![
                    vec![],
                    vec![
                        QpdfObjGen::new(2, 0),
                        QpdfObjGen::new(7, 0),
                        QpdfObjGen::new(8, 65_536),
                    ],
                ],
                part4_other_pages_private: vec![
                    QpdfObjGen::new(2, 0),
                    QpdfObjGen::new(7, 0),
                    QpdfObjGen::new(8, 65_536),
                ],
                projection_gap: true,
                ..Default::default()
            },
            ..LinearizationPlan::default()
        };
        let batches = vec![RoutedObjStmBatch {
            members: vec![member],
            route: ContainerPart::OtherPagePrivate,
            source_container_number: None,
        }];

        let anchors = second_half_container_anchors(&plan, &batches);
        assert_eq!(
            anchors,
            vec![SecondHalfContainerAnchor::After(QpdfObjGen::new(2, 0))]
        );
    }

    #[test]
    fn raw_second_half_anchor_covers_part9_outline_and_preserve_modes() {
        let plan = LinearizationPlan {
            raw: crate::linearization::plan::RawLinearizationPlan {
                part4_rest: vec![QpdfObjGen::new(8, 65_536)],
                part9_outline_objects: vec![QpdfObjGen::new(7, 0)],
                projection_gap: true,
                ..Default::default()
            },
            ..LinearizationPlan::default()
        };
        let batches = vec![
            RoutedObjStmBatch {
                members: vec![ObjectRef::new(7, 0)],
                route: ContainerPart::Rest,
                source_container_number: None,
            },
            RoutedObjStmBatch {
                members: vec![ObjectRef::new(9, 0)],
                route: ContainerPart::Rest,
                source_container_number: Some(99),
            },
        ];

        let anchors = second_half_container_anchors(&plan, &batches);
        assert_eq!(
            anchors,
            vec![
                SecondHalfContainerAnchor::BeforeFirst,
                SecondHalfContainerAnchor::After(QpdfObjGen::new(8, 65_536)),
            ]
        );
    }

    #[test]
    fn hint_generation_boundary_preserves_plan_validation() {
        let plan = LinearizationPlan {
            per_page_private_objects: vec![Vec::new()],
            ..LinearizationPlan::default()
        };
        let renumber = RenumberMap::from_plan(&plan);
        let container_shared_sort_key = BTreeMap::new();
        let pass1_output = LinearizedPassOutput {
            xref_offsets: BTreeMap::new(),
            first_page_xref_offset: None,
            hint_stream_offset: 0,
            hint_stream_obj_total_len: 0,
            end_of_first_page_offset: 0,
            last_xref_offset: 0,
            last_xref_first_entry_offset: 0,
            second_xref_end: 0,
            first_trailer_prev_range: 0..0,
            id_ranges: Vec::new(),
        };
        let input = HintStreamBuildInput {
            plan: &plan,
            renumber: &renumber,
            objstm_layout: &ObjStmLayout::default(),
            container_shared_sort_key: &container_shared_sort_key,
            pass1_output: &pass1_output,
            hint_stream_new_num: 2,
            second_half_container_nums: &BTreeSet::new(),
            open_document_container_nums: &BTreeSet::new(),
            outline_info: None,
            structural_streams_filtered: false,
            encrypt_ctx: None,
            hint_stream_aes_iv: [0; 16],
        };

        let error = build_hint_stream_from_pass1(&input).expect_err("invalid plan must fail");
        assert!(error
            .to_string()
            .contains("per_page_private_objects length"));
    }

    #[test]
    fn pass1_target_is_forward_only_and_counted() {
        let mut target = Pass1OutputTarget::discard();
        let mut sink = OutputSink::new(&mut target);
        sink.begin_digest();
        sink.write_bytes(b"pass-1")
            .expect("pass-1 bytes are accepted");

        let digest = sink.take_digest().expect("pass-1 digest is enabled");
        let expected: [u8; 16] = md5::Md5::digest(b"pass-1").into();
        assert_eq!(sink.position(), 6);
        assert_eq!(digest, expected);
        assert!(
            target.patch_bytes(0..1, b"x").is_err(),
            "pass-1 target must remain forward-only"
        );
    }

    #[test]
    fn repeated_padding_writes_large_and_partial_chunks() {
        let mut bytes = Vec::new();
        let mut sink = OutputSink::new(&mut bytes);

        write_repeated_bytes(&mut sink, b' ', 4096 * 2 + 7).expect("padding writes");

        drop(sink);
        assert_eq!(bytes.len(), 4096 * 2 + 7);
        assert!(bytes.iter().all(|&byte| byte == b' '));
    }

    #[test]
    fn linearization_body_stream_and_objstm_paths_write_through_output_sink() {
        let stream = ObjectHandle::stream(
            ObjectHandle::dictionary(Vec::new()),
            Rc::new(b"stream-data".to_vec()),
        );
        let renumber = RenumberMap::from_plan(&LinearizationPlan::default());
        let mut plain_bytes = Vec::new();
        let mut plain_sink = OutputSink::new(&mut plain_bytes);
        append_body_object(
            &mut plain_sink,
            ObjectRef::new(1, 0),
            ObjectRef::new(1, 0),
            &stream,
            &WriterOptions::default(),
            None,
            None,
            &renumber,
            &BTreeSet::new(),
            &BTreeSet::new(),
        )
        .expect("plain stream body writes");
        drop(plain_sink);
        assert!(plain_bytes
            .windows(b"endstream".len())
            .any(|window| window == b"endstream"));

        let container = ObjStmContainer {
            container_new_num: 2,
            members: Vec::new(),
        };
        let mut pdf = Pdf::empty().expect("empty PDF for ObjStm output");
        let mut plain_objstm_bytes = Vec::new();
        let mut plain_objstm_sink = OutputSink::new(&mut plain_objstm_bytes);
        append_objstm_container_object(
            &mut plain_objstm_sink,
            &container,
            &renumber,
            &mut pdf,
            &BTreeSet::new(),
            &WriterOptions::default(),
            None,
        )
        .expect("plain ObjStm body writes");
        drop(plain_objstm_sink);

        let mut encrypted_pdf = Pdf::empty().expect("empty PDF for encrypted ObjStm output");
        let encryption = test_encryption_context();
        let mut encrypted_bytes = Vec::new();
        let mut encrypted_sink = OutputSink::new(&mut encrypted_bytes);
        append_objstm_container_object(
            &mut encrypted_sink,
            &container,
            &renumber,
            &mut encrypted_pdf,
            &BTreeSet::new(),
            &WriterOptions::default(),
            Some(&encryption),
        )
        .expect("encrypted ObjStm body writes");
        drop(encrypted_sink);
        assert!(plain_objstm_bytes.starts_with(b"2 0 obj\n"));
        assert!(encrypted_bytes.starts_with(b"2 0 obj\n"));
    }

    #[test]
    fn classic_main_xref_emits_free_entries_for_missing_offsets() {
        let trailer = ObjectHandle::dictionary(vec![(
            b"/ID".to_vec(),
            ObjectHandle::array(vec![
                ObjectHandle::new_indirect_unresolved(ObjectRef::new(8, 0), -1),
                ObjectHandle::string(vec![1; 16]),
            ]),
        )]);
        let mut bytes = Vec::new();
        let mut sink = OutputSink::new(&mut bytes);

        write_main_xref_and_trailer(
            &mut sink,
            &BTreeMap::new(),
            3,
            0,
            &trailer,
            &|object_gen| Ok(object_gen.to_object_ref().expect("test ID ref is valid")),
            &BTreeSet::new(),
            None,
        )
        .expect("classic xref with missing offsets");
        drop(sink);
        assert!(bytes
            .windows(b"0000000000 65535 f \n".len())
            .any(|window| window == b"0000000000 65535 f \n"));
    }

    fn one_page_pdf_with_direct_outlines() -> Vec<u8> {
        let mut pdf = b"%PDF-1.4\n".to_vec();
        let off1 = pdf.len();
        pdf.extend_from_slice(
            b"1 0 obj\n<< /Type /Catalog /Pages 2 0 R /Outlines << /Count 0 >> >>\nendobj\n",
        );
        let off2 = pdf.len();
        pdf.extend_from_slice(b"2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n");
        let off3 = pdf.len();
        pdf.extend_from_slice(
            b"3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n",
        );
        let xref = pdf.len();
        pdf.extend_from_slice(
            format!(
                "xref\n0 4\n0000000000 65535 f \n{off1:010} 00000 n \n{off2:010} 00000 n \n{off3:010} 00000 n \ntrailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"
            )
            .as_bytes(),
        );
        pdf
    }

    #[test]
    fn linearized_generate_falls_back_without_a_setup_snapshot() {
        let mut pdf = Pdf::open(std::io::Cursor::new(
            include_bytes!("../../../../tests/fixtures/compat/one-page.pdf").to_vec(),
        ))
        .expect("open linearized Generate fixture");
        let options = WriterOptions {
            object_streams: crate::writer::ObjectStreamMode::Generate,
            static_id: true,
            ..WriterOptions::default()
        };
        // Direct callers of this lower-level route may not have the common
        // PdfWriter setup snapshot. Keep the fallback exercised separately
        // from the production path, which always supplies one for Generate.
        let setup = crate::writer::build_writer_setup(&mut pdf, &options).unwrap();
        let mut bytes = Vec::new();
        write_linearized_for_pdf_writer(&mut pdf, &options, None, setup, &mut bytes)
            .expect("linearized Generate fallback succeeds");
        assert!(bytes
            .windows(b"/Type /ObjStm".len())
            .any(|window| { window == b"/Type /ObjStm" }));
    }

    #[test]
    fn linearized_writer_keeps_catalog_planning_mutation_after_progress_failure() {
        // The canonical optimization pass promotes direct /Outlines before
        // writing. A later qpdf progress-reporter failure must not let
        // restoration clear that permanent change.
        let mut pdf =
            Pdf::open(Cursor::new(one_page_pdf_with_direct_outlines())).expect("source parses");
        let root_ref = pdf.root_ref().expect("Catalog present");

        let options = WriterOptions {
            progress_reporter: Some(ProgressReporter::new(Box::new(|_| {
                Err(crate::Error::System("test progress failure".to_owned()))
            }))),
            ..WriterOptions::default()
        };
        let setup = crate::writer::build_writer_setup(&mut pdf, &options).unwrap();
        let mut bytes = Vec::new();
        let error = write_linearized_for_pdf_writer(&mut pdf, &options, None, setup, &mut bytes)
            .expect_err("canonical progress reporter failure must abort writing");
        assert!(
            error.to_string().contains("test progress failure"),
            "unexpected writer error: {error}"
        );

        let root = pdf.get_object_handle(root_ref);
        root.try_is_scalar().expect("Catalog resolves");
        assert!(
            root.try_get_key(b"/Outlines")
                .expect("Outlines lookup")
                .is_indirect(),
            "planning must keep qpdf's direct /Outlines promotion"
        );
    }

    #[test]
    fn body_object_append_propagates_member_resolution_errors() {
        let unresolved = ObjectHandle::new_indirect_unresolved(ObjectRef::new(91, 0), -1);
        let plan = LinearizationPlan::default();
        let renumber = RenumberMap::from_plan(&plan);
        let mut bytes = Vec::new();
        let mut sink = OutputSink::new(&mut bytes);
        let error = append_body_object(
            &mut sink,
            ObjectRef::new(1, 0),
            ObjectRef::new(91, 0),
            &unresolved,
            &WriterOptions::default(),
            None,
            None,
            &renumber,
            &BTreeSet::new(),
            &BTreeSet::new(),
        )
        .expect_err("body-object emission must propagate member resolution errors");
        assert!(matches!(
            error,
            crate::Error::Internal(message) if message == "object 91 0 belongs to a dropped PDF"
        ));
    }

    #[test]
    fn linearization_trailer_serializes_live_direct_custom_values() {
        let pdf = Pdf::empty().expect("create trailer reference owner");
        let indirect = pdf
            .make_indirect_from_object_handle(ObjectHandle::integer(11))
            .expect("create indirect custom value");
        let indirect_ref = indirect.object_ref().unwrap();
        let removed = pdf
            .make_indirect_from_object_handle(ObjectHandle::integer(12))
            .expect("create removed custom value");
        let removed_ref = removed.object_ref().unwrap();
        let trailer = ObjectHandle::dictionary(vec![
            (
                b"/Direct".to_vec(),
                ObjectHandle::dictionary(vec![(
                    b"/Name".to_vec(),
                    ObjectHandle::name(b"Value".to_vec()),
                )]),
            ),
            (b"/Indirect".to_vec(), indirect),
            (b"/Removed".to_vec(), removed),
            (b"/Null".to_vec(), ObjectHandle::null()),
            (b"/Size".to_vec(), ObjectHandle::integer(99)),
        ]);
        let map = |object_gen: QpdfObjGen| {
            assert_eq!(object_gen.to_object_ref(), Some(indirect_ref));
            Ok(ObjectRef::new(21, 0))
        };

        let entries = canonical_linearization_trailer_entries(
            &trailer,
            &map,
            &[QpdfObjGen::try_from_object_ref(removed_ref).unwrap()]
                .into_iter()
                .collect(),
        )
        .expect("serialize canonical linearization trailer entries");

        assert_eq!(
            entries,
            vec![
                (b"/Direct".to_vec(), b"<< /Name /Value >>".to_vec()),
                (b"/Indirect".to_vec(), b"21 0 R".to_vec()),
            ]
        );
    }
}