flpdf-cli 0.10.0

Command-line tools for flpdf, mirroring qpdf inspection and rewrite subcommands.
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
//! Top-level qpdf-compatible inline-image transformation coverage.

use assert_cmd::Command;
use serde_json::Value;
use std::path::Path;
use std::process::{Command as ProcessCommand, Output};

const EXPECTED_QPDF_VERSION: &str = "qpdf version 11.9.0";

fn assemble_pdf(objects: &[(u32, Vec<u8>)]) -> Vec<u8> {
    let mut bytes = b"%PDF-1.4\n".to_vec();
    let mut offsets = vec![0usize; objects.len() + 1];
    for (number, body) in objects {
        offsets[*number as usize] = bytes.len();
        bytes.extend_from_slice(format!("{number} 0 obj\n").as_bytes());
        bytes.extend_from_slice(body);
        bytes.extend_from_slice(b"\nendobj\n");
    }
    let xref_offset = bytes.len();
    bytes.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
    bytes.extend_from_slice(b"0000000000 65535 f \n");
    for offset in offsets.into_iter().skip(1) {
        bytes.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
    }
    bytes.extend_from_slice(
        format!(
            "trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n",
            objects.len() + 1
        )
        .as_bytes(),
    );
    bytes
}

fn stream_object(dictionary: &[u8], data: &[u8]) -> Vec<u8> {
    let mut object = dictionary.to_vec();
    object.extend_from_slice(b"\nstream\n");
    object.extend_from_slice(data);
    object.extend_from_slice(b"\nendstream");
    object
}

fn single_page_pdf_with_content(content: &[u8]) -> Vec<u8> {
    assemble_pdf(&[
        (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
        (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
        (
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R >>".to_vec(),
        ),
        (
            4,
            stream_object(
                format!("<< /Length {} >>", content.len()).as_bytes(),
                content,
            ),
        ),
    ])
}

fn inline_image_pdf() -> Vec<u8> {
    let content = inline_image_content(b"/G", &[0, 64, 128, 255], true);
    single_page_pdf_with_content(&content)
}

fn inline_image_content(colorspace: &[u8], payload: &[u8], with_ei: bool) -> Vec<u8> {
    inline_image_content_with_dimensions(2, 2, colorspace, payload, with_ei)
}

fn inline_image_content_with_dimensions(
    width: u8,
    height: u8,
    colorspace: &[u8],
    payload: &[u8],
    with_ei: bool,
) -> Vec<u8> {
    let mut content = format!("q 200 0 0 200 0 0 cm BI /W {width} /H {height} /CS ").into_bytes();
    content.extend_from_slice(colorspace);
    content.extend_from_slice(b" /BPC 8 ID\n");
    content.extend_from_slice(payload);
    if with_ei {
        content.extend_from_slice(b"\nEI Q\n");
    } else {
        content.extend_from_slice(b"\nQ\n");
    }
    content
}

fn mixed_threshold_inline_image_pdf() -> Vec<u8> {
    let mut content = inline_image_content_with_dimensions(2, 2, b"/G", &[0, 64, 128, 255], true);
    content.extend_from_slice(&inline_image_content_with_dimensions(
        4,
        4,
        b"/G",
        &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
        true,
    ));
    single_page_pdf_with_content(&content)
}

fn two_page_inline_image_pdf() -> Vec<u8> {
    let first = inline_image_content(b"/G", &[0, 64, 128, 255], true);
    let second = inline_image_content(b"/G", &[255, 128, 64, 0], true);
    assemble_pdf(&[
        (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
        (2, b"<< /Type /Pages /Kids [3 0 R 5 0 R] /Count 2 >>".to_vec()),
        (
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R >>".to_vec(),
        ),
        (
            4,
            stream_object(format!("<< /Length {} >>", first.len()).as_bytes(), &first),
        ),
        (
            5,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 6 0 R >>".to_vec(),
        ),
        (
            6,
            stream_object(format!("<< /Length {} >>", second.len()).as_bytes(), &second),
        ),
    ])
}

fn nested_form_inline_image_pdf() -> Vec<u8> {
    let page_content = b"q /Fm1 Do Q\n".to_vec();
    let form_content = inline_image_content(b"/G", &[0, 64, 128, 255], true);
    assemble_pdf(&[
        (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
        (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
        (
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /XObject << /Fm1 5 0 R >> >> /Contents 4 0 R >>".to_vec(),
        ),
        (
            4,
            stream_object(
                format!("<< /Length {} >>", page_content.len()).as_bytes(),
                &page_content,
            ),
        ),
        (
            5,
            stream_object(
                format!(
                    "<< /Type /XObject /Subtype /Form /FormType 1 /BBox [0 0 200 200] /Resources << >> /Length {} >>",
                    form_content.len()
                )
                .as_bytes(),
                &form_content,
            ),
        ),
    ])
}

fn named_colorspace_inline_image_pdf() -> Vec<u8> {
    let content = inline_image_content(b"/CS1", &[0, 64, 128, 255], true);
    assemble_pdf(&[
        (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
        (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
        (
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /ColorSpace << /CS1 /DeviceGray >> >> /Contents 4 0 R >>".to_vec(),
        ),
        (
            4,
            stream_object(format!("<< /Length {} >>", content.len()).as_bytes(), &content),
        ),
    ])
}

fn malformed_resource_containers_inline_images_pdf() -> Vec<u8> {
    let mut content = inline_image_content(b"/Foo", &[0, 64, 128, 255], true);
    content.extend_from_slice(&inline_image_content(b"/Bar", &[255, 128, 64, 0], true));
    assemble_pdf(&[
        (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
        (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
        (
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << /XObject 5 /ColorSpace 6 >> /Contents 4 0 R >>".to_vec(),
        ),
        (
            4,
            stream_object(format!("<< /Length {} >>", content.len()).as_bytes(), &content),
        ),
    ])
}

fn no_inline_image_pdf() -> Vec<u8> {
    let content = b"q Q\n";
    assemble_pdf(&[
        (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
        (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
        (
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R >>".to_vec(),
        ),
        (
            4,
            stream_object(format!("<< /Length {} >>", content.len()).as_bytes(), content),
        ),
    ])
}

fn damaged_inline_image_pdf() -> Vec<u8> {
    let content = inline_image_content(b"/G", &[0, 64, 128, 255], false);
    assemble_pdf(&[
        (1, b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()),
        (2, b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()),
        (
            3,
            b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 200 200] /Resources << >> /Contents 4 0 R >>".to_vec(),
        ),
        (
            4,
            stream_object(format!("<< /Length {} >>", content.len()).as_bytes(), &content),
        ),
    ])
}

fn eof_inline_image_pdf() -> Vec<u8> {
    let mut content = b"q 200 0 0 200 0 0 cm BI /W 2 /H 2 /CS /G /BPC 8 ID\n".to_vec();
    content.extend_from_slice(&[0, 64, 128, 255]);
    single_page_pdf_with_content(&content)
}

fn qpdf_or_skip() -> bool {
    let result = ProcessCommand::new("qpdf").arg("--version").output();
    let version = result.ok().and_then(|output| {
        output
            .status
            .success()
            .then(|| String::from_utf8_lossy(&output.stdout).into_owned())
    });
    let exact = version
        .as_deref()
        .and_then(|version| version.lines().next())
        == Some(EXPECTED_QPDF_VERSION);
    if exact {
        return true;
    }
    if std::env::var_os("CI").is_some() {
        panic!(
            "qpdf 11.9.0 is required for inline-image oracle tests; found {:?}",
            version
        );
    }
    eprintln!(
        "[SKIP cli_inline_images_transform] qpdf 11.9.0 is unavailable; found {:?}",
        version
    );
    false
}

fn run_qpdf_rewrite(flags: &[String], input: &Path, output: &Path) -> Output {
    ProcessCommand::new("qpdf")
        .args(flags)
        .arg(input)
        .arg(output)
        .output()
        .expect("qpdf 11.9.0 is available")
}

fn run_flpdf_rewrite(flags: &[String], input: &Path, output: &Path) -> Output {
    let mut command = Command::cargo_bin("flpdf").expect("flpdf binary");
    command
        .args(flags)
        .arg(input)
        .arg(output)
        .output()
        .expect("run flpdf")
}

/// Run qpdf when the pinned 11.9.0 oracle is present.
///
/// The flpdf-only assertions in the pre-existing tests below do not need the
/// oracle, so gate only the comparison rather than returning early and
/// skipping the whole test on a machine without qpdf.
fn run_qpdf_rewrite_if_available(flags: &[String], input: &Path, output: &Path) -> Option<Output> {
    qpdf_or_skip().then(|| run_qpdf_rewrite(flags, input, output))
}

fn run_qpdf_page_selection(input: &Path, output: &Path) -> Output {
    ProcessCommand::new("qpdf")
        .args([
            "--externalize-inline-images",
            "--ii-min-bytes=0",
            "--static-id",
        ])
        .arg(input)
        .args(["--pages"])
        .arg(input)
        .args(["1", "--"])
        .arg(output)
        .output()
        .expect("qpdf 11.9.0 is available")
}

fn run_flpdf_page_selection(input: &Path, output: &Path) -> Output {
    let mut command = Command::cargo_bin("flpdf").expect("flpdf binary");
    command
        .args([
            "--externalize-inline-images",
            "--ii-min-bytes=0",
            "--static-id",
        ])
        .arg(input)
        .args(["--pages"])
        .arg(input)
        .args(["1", "--"])
        .arg(output)
        .output()
        .expect("run flpdf page selection")
}

fn qpdf_pages_json(path: &Path) -> Value {
    let output = ProcessCommand::new("qpdf")
        .args(["--json=2", "--json-key=pages"])
        .arg(path)
        .output()
        .expect("run qpdf JSON");
    assert!(
        output.status.success(),
        "qpdf JSON failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
    serde_json::from_slice(&output.stdout).expect("valid qpdf JSON")
}

fn flpdf_pages_json(path: &Path) -> Value {
    let output = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--json=2", "--json-key=pages"])
        .arg(path)
        .output()
        .expect("run flpdf JSON");
    assert!(output.status.success(), "JSON failed: {output:?}");
    serde_json::from_slice(&output.stdout).expect("valid JSON")
}

fn normalized_page_images(value: &Value) -> Vec<Vec<Value>> {
    value["pages"]
        .as_array()
        .expect("pages array")
        .iter()
        .map(|page| {
            page["images"]
                .as_array()
                .expect("images array")
                .iter()
                .map(|image| {
                    let mut image = image.clone();
                    image
                        .as_object_mut()
                        .expect("image object")
                        .remove("object");
                    image
                })
                .collect()
        })
        .collect()
}

fn assert_page_images_match(qpdf_output: &Path, flpdf_output: &Path) {
    let oracle = normalized_page_images(&qpdf_pages_json(qpdf_output));
    assert_eq!(
        oracle,
        normalized_page_images(&flpdf_pages_json(flpdf_output)),
        "flpdf inline-image page metadata must match qpdf 11.9.0"
    );
    // Reading flpdf's own output with flpdf moves the writer and the JSON
    // reader together, so a matching pair of errors stays green. Read the same
    // file with qpdf as well to pin the written document, not the round trip.
    assert_eq!(
        oracle,
        normalized_page_images(&qpdf_pages_json(flpdf_output)),
        "qpdf 11.9.0 must see the same inline-image metadata in flpdf's output"
    );
}

/// Compare the whole `--qdf` output, plus stderr and exit status, against
/// qpdf 11.9.0's own.
///
/// qpdf's `inline-images.test` compares whole files rather than metadata
/// (`qpdf/qtest/inline-images.test:93-94`), which is what makes it catch a
/// transform that lands in the wrong place. The page-image JSON cannot: qpdf's
/// `doJSONPages` lists only the images a page owns directly
/// (`libqpdf/QPDFJob.cc:1044` -> `QPDFPageObjectHelper::getImages`,
/// `libqpdf/QPDFPageObjectHelper.cc:376-384`), while `externalizeInlineImages`
/// also recurses into Form XObject resources
/// (`libqpdf/QPDFPageObjectHelper.cc:430-434`), so a nested-form or
/// content-only difference shows up as `[] == []`.
///
/// `--qdf` disables stream compression, so the DEFLATE backend difference that
/// CLAUDE.md allows as deviation (A) never reaches the output and this
/// comparison needs no `qpdf-zlib-compat` feature.
fn assert_qdf_bytes_match(input: &Path, extra_flags: &[&str], label: &str) {
    if !qpdf_or_skip() {
        return;
    }
    let directory = tempfile::tempdir().expect("tempdir");
    let qpdf_output = directory.path().join("qpdf.pdf");
    let flpdf_output = directory.path().join("flpdf.pdf");
    let mut flags = vec!["--qdf".to_owned(), "--static-id".to_owned()];
    flags.extend(extra_flags.iter().map(|flag| (*flag).to_owned()));

    let qpdf = run_qpdf_rewrite(&flags, input, &qpdf_output);
    let flpdf = run_flpdf_rewrite(&flags, input, &flpdf_output);

    assert_streams_and_status_match(&qpdf, &flpdf, label);
    assert_eq!(
        std::fs::read(&qpdf_output).expect("qpdf output"),
        std::fs::read(&flpdf_output).expect("flpdf output"),
        "{label}: --qdf output must be byte-identical to qpdf 11.9.0"
    );
}

/// Compare exit status and both captured streams against qpdf 11.9.0.
///
/// Writing progress, diagnostics or PDF data to stdout is an observable CLI
/// regression for any caller that pipes it, and neither the exit status nor
/// the output file would show it; an unexpected warning on stderr is the same
/// kind of hole. Only the program-name prefix is normalized away.
fn assert_streams_and_status_match(qpdf: &Output, flpdf: &Output, label: &str) {
    assert_eq!(
        qpdf.status.code(),
        flpdf.status.code(),
        "{label}: exit status must match qpdf 11.9.0"
    );
    assert_eq!(
        String::from_utf8_lossy(&qpdf.stderr).replace("qpdf:", ""),
        String::from_utf8_lossy(&flpdf.stderr).replace("flpdf:", ""),
        "{label}: diagnostics must match qpdf 11.9.0 apart from the program name"
    );
    assert_eq!(
        String::from_utf8_lossy(&qpdf.stdout).replace("qpdf:", ""),
        String::from_utf8_lossy(&flpdf.stdout).replace("flpdf:", ""),
        "{label}: standard output must match qpdf 11.9.0 apart from the program name"
    );
}

/// Whole-file `--qdf` comparison for the page-selection invocation.
///
/// [`assert_qdf_bytes_match`] takes its flags as a flat list, which cannot
/// reproduce `--pages <file> 1 --` with the primary input placed before the
/// segment. Run the same shape the metadata comparison uses so both checks
/// exercise one parsing path.
fn assert_page_selection_qdf_bytes_match(input: &Path) {
    if !qpdf_or_skip() {
        return;
    }
    let directory = tempfile::tempdir().expect("tempdir");
    let qpdf_output = directory.path().join("qpdf-qdf.pdf");
    let flpdf_output = directory.path().join("flpdf-qdf.pdf");

    let qpdf = ProcessCommand::new("qpdf")
        .args([
            "--qdf",
            "--externalize-inline-images",
            "--ii-min-bytes=0",
            "--static-id",
        ])
        .arg(input)
        .args(["--pages"])
        .arg(input)
        .args(["1", "--"])
        .arg(&qpdf_output)
        .output()
        .expect("qpdf 11.9.0 is available");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([
            "--qdf",
            "--externalize-inline-images",
            "--ii-min-bytes=0",
            "--static-id",
        ])
        .arg(input)
        .args(["--pages"])
        .arg(input)
        .args(["1", "--"])
        .arg(&flpdf_output)
        .output()
        .expect("run flpdf page selection");

    assert_streams_and_status_match(&qpdf, &flpdf, "page selection");
    assert_eq!(
        std::fs::read(&qpdf_output).expect("qpdf output"),
        std::fs::read(&flpdf_output).expect("flpdf output"),
        "page selection: --qdf output must be byte-identical to qpdf 11.9.0"
    );
}

fn image_transform_flags(externalize: bool, optimize: bool, keep_inline: bool) -> Vec<String> {
    let mut flags = vec!["--static-id".to_owned()];
    if externalize {
        flags.push("--externalize-inline-images".to_owned());
    }
    if externalize || optimize {
        flags.push("--ii-min-bytes=0".to_owned());
    }
    if optimize {
        flags.push("--optimize-images".to_owned());
    }
    if keep_inline {
        flags.push("--keep-inline-images".to_owned());
    }
    flags
}

#[test]
fn top_level_externalize_inline_images_converts_inline_image_to_xobject() {
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("input.pdf");
    let qpdf_output = directory.path().join("qpdf.pdf");
    let output = directory.path().join("output.pdf");
    std::fs::write(&input, inline_image_pdf()).expect("write input");

    let qpdf = run_qpdf_rewrite_if_available(
        &[
            "--externalize-inline-images".to_owned(),
            "--ii-min-bytes=0".to_owned(),
            "--static-id".to_owned(),
        ],
        &input,
        &qpdf_output,
    );
    if let Some(qpdf) = &qpdf {
        assert!(
            qpdf.status.success(),
            "qpdf externalization failed: {}",
            String::from_utf8_lossy(&qpdf.stderr)
        );
    }

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([
            "--externalize-inline-images",
            "--ii-min-bytes=0",
            "--static-id",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    if qpdf.is_some() {
        assert_page_images_match(&qpdf_output, &output);
    }
    let image = &flpdf_pages_json(&output)["pages"][0]["images"][0];
    assert_eq!(image["name"], "/IIm1");
    assert_eq!(image["width"], 2);
    assert_eq!(image["height"], 2);
}

#[test]
fn top_level_externalize_inline_images_honors_inclusive_payload_threshold() {
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("input.pdf");
    let qpdf_at_limit = directory.path().join("qpdf-at-limit.pdf");
    let qpdf_above_limit = directory.path().join("qpdf-above-limit.pdf");
    let at_limit = directory.path().join("at-limit.pdf");
    let above_limit = directory.path().join("above-limit.pdf");
    std::fs::write(&input, inline_image_pdf()).expect("write input");

    let qpdf_at_limit_result = run_qpdf_rewrite_if_available(
        &[
            "--externalize-inline-images".to_owned(),
            "--ii-min-bytes=5".to_owned(),
            "--static-id".to_owned(),
        ],
        &input,
        &qpdf_at_limit,
    );
    if let Some(result) = &qpdf_at_limit_result {
        assert!(result.status.success());
    }
    let qpdf_above_limit_result = run_qpdf_rewrite_if_available(
        &[
            "--externalize-inline-images".to_owned(),
            "--ii-min-bytes=6".to_owned(),
            "--static-id".to_owned(),
        ],
        &input,
        &qpdf_above_limit,
    );
    if let Some(result) = &qpdf_above_limit_result {
        assert!(result.status.success());
    }

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([
            "--externalize-inline-images",
            "--ii-min-bytes=5",
            "--static-id",
        ])
        .arg(&input)
        .arg(&at_limit)
        .assert()
        .success();
    assert_eq!(
        flpdf_pages_json(&at_limit)["pages"][0]["images"]
            .as_array()
            .unwrap()
            .len(),
        1
    );
    if qpdf_at_limit_result.is_some() {
        assert_page_images_match(&qpdf_at_limit, &at_limit);
    }

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([
            "--externalize-inline-images",
            "--ii-min-bytes=6",
            "--static-id",
        ])
        .arg(&input)
        .arg(&above_limit)
        .assert()
        .success();
    assert!(flpdf_pages_json(&above_limit)["pages"][0]["images"]
        .as_array()
        .expect("image array")
        .is_empty());
    if qpdf_above_limit_result.is_some() {
        assert_page_images_match(&qpdf_above_limit, &above_limit);
    }
    // At `--ii-min-bytes=6` the five-byte image stays inline, so no XObject is
    // produced and both page-image arrays are empty. Compare the whole file so
    // the retained `BI ... EI` content itself is checked.
    assert_qdf_bytes_match(
        &input,
        &["--externalize-inline-images", "--ii-min-bytes=6"],
        "above the inclusive threshold",
    );
    assert_qdf_bytes_match(
        &input,
        &["--externalize-inline-images", "--ii-min-bytes=5"],
        "at the inclusive threshold",
    );
}

#[test]
fn mixed_inline_image_sizes_match_qpdf_at_thresholds() {
    if !qpdf_or_skip() {
        return;
    }
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("mixed-input.pdf");
    std::fs::write(&input, mixed_threshold_inline_image_pdf()).expect("write input");

    let cases: [(usize, &[&str], usize); 3] = [
        (0, &["/IIm1", "/IIm2"], 0),
        (10, &["/IIm1"], 1),
        (100, &[], 2),
    ];
    for (threshold, expected_images, expected_inline_images) in cases {
        let qpdf_output = directory.path().join(format!("qpdf-{threshold}.pdf"));
        let flpdf_output = directory.path().join(format!("flpdf-{threshold}.pdf"));
        let flags = vec![
            "--qdf".to_owned(),
            "--static-id".to_owned(),
            "--externalize-inline-images".to_owned(),
            format!("--ii-min-bytes={threshold}"),
        ];
        let qpdf = run_qpdf_rewrite(&flags, &input, &qpdf_output);
        assert!(
            qpdf.status.success(),
            "qpdf threshold {threshold} failed: {}",
            String::from_utf8_lossy(&qpdf.stderr)
        );
        let flpdf = run_flpdf_rewrite(&flags, &input, &flpdf_output);
        assert!(
            flpdf.status.success(),
            "flpdf threshold {threshold} failed: {}",
            String::from_utf8_lossy(&flpdf.stderr)
        );
        assert_streams_and_status_match(&qpdf, &flpdf, &format!("mixed threshold {threshold}"));

        let qpdf_bytes = std::fs::read(&qpdf_output).expect("qpdf output");
        let flpdf_bytes = std::fs::read(&flpdf_output).expect("flpdf output");
        assert_eq!(
            qpdf_bytes, flpdf_bytes,
            "threshold {threshold}: --qdf output must be byte-identical to qpdf 11.9.0"
        );
        assert_eq!(
            qpdf_bytes
                .windows(3)
                .filter(|token| *token == b"BI ")
                .count(),
            expected_inline_images,
            "threshold {threshold}: retained inline-image count"
        );

        let qpdf_json = qpdf_pages_json(&qpdf_output);
        let qpdf_names: Vec<&str> = qpdf_json["pages"][0]["images"]
            .as_array()
            .expect("qpdf image array")
            .iter()
            .map(|image| image["name"].as_str().expect("qpdf image name"))
            .collect();
        assert_eq!(qpdf_names, expected_images);
        let flpdf_json = flpdf_pages_json(&flpdf_output);
        let flpdf_names: Vec<&str> = flpdf_json["pages"][0]["images"]
            .as_array()
            .expect("flpdf image array")
            .iter()
            .map(|image| image["name"].as_str().expect("flpdf image name"))
            .collect();
        assert_eq!(flpdf_names, expected_images);
    }
}

#[test]
fn large_delimited_ei_payload_matches_qpdf() {
    if !qpdf_or_skip() {
        return;
    }
    // This is qpdf 11.9.0's qpdf/qtest/qpdf/large-inline-image.pdf fixture:
    // its ASCII85 data contains several delimiter-surrounded EI candidates.
    let input = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("tests/fixtures/inline-images/large-inline-image.pdf");
    let directory = tempfile::tempdir().expect("tempdir");
    let qpdf_output = directory.path().join("qpdf.pdf");
    let flpdf_output = directory.path().join("flpdf.pdf");
    let flags = ["--qdf".to_owned(), "--static-id".to_owned()];

    let qpdf = run_qpdf_rewrite(&flags, &input, &qpdf_output);
    assert!(
        qpdf.status.success(),
        "qpdf large inline image failed: {}",
        String::from_utf8_lossy(&qpdf.stderr)
    );
    let flpdf = run_flpdf_rewrite(&flags, &input, &flpdf_output);
    assert!(
        flpdf.status.success(),
        "flpdf large inline image failed: {}",
        String::from_utf8_lossy(&flpdf.stderr)
    );
    assert_streams_and_status_match(&qpdf, &flpdf, "large inline image with delimited EI data");
    assert_eq!(
        std::fs::read(&qpdf_output).expect("qpdf output"),
        std::fs::read(&flpdf_output).expect("flpdf output"),
        "large inline-image --qdf output must be byte-identical to qpdf 11.9.0"
    );
}

#[test]
fn eof_inside_inline_image_matches_qpdf_exit_three() {
    if !qpdf_or_skip() {
        return;
    }
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("eof-inline-image.pdf");
    std::fs::write(&input, eof_inline_image_pdf()).expect("write input");

    let cases: [(&[&str], &str); 2] = [
        (&["--qdf", "--static-id"], "EOF in inline image"),
        (
            &["--qdf", "--externalize-inline-images", "--static-id"],
            "externalized EOF in inline image",
        ),
    ];
    for (index, (flags, label)) in cases.into_iter().enumerate() {
        let qpdf_output = directory.path().join(format!("qpdf-eof-{index}.pdf"));
        let flpdf_output = directory.path().join(format!("flpdf-eof-{index}.pdf"));
        let flags: Vec<String> = flags.iter().map(|flag| (*flag).to_owned()).collect();
        let qpdf = run_qpdf_rewrite(&flags, &input, &qpdf_output);
        let flpdf = run_flpdf_rewrite(&flags, &input, &flpdf_output);

        assert_eq!(qpdf.status.code(), Some(3), "qpdf {label} must exit 3");
        assert_eq!(flpdf.status.code(), Some(3), "flpdf {label} must exit 3");
        assert_streams_and_status_match(&qpdf, &flpdf, label);
        assert_eq!(
            std::fs::read(&qpdf_output).expect("qpdf output"),
            std::fs::read(&flpdf_output).expect("flpdf output"),
            "{label}: --qdf output must be byte-identical to qpdf 11.9.0"
        );
    }
}

#[test]
fn explicit_externalization_overrides_keep_inline_images() {
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("input.pdf");
    let qpdf_output = directory.path().join("qpdf.pdf");
    let output = directory.path().join("output.pdf");
    std::fs::write(&input, inline_image_pdf()).expect("write input");

    let qpdf = run_qpdf_rewrite_if_available(
        &[
            "--externalize-inline-images".to_owned(),
            "--keep-inline-images".to_owned(),
            "--ii-min-bytes=0".to_owned(),
            "--static-id".to_owned(),
        ],
        &input,
        &qpdf_output,
    );
    if let Some(qpdf) = &qpdf {
        assert!(qpdf.status.success());
    }

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([
            "--externalize-inline-images",
            "--keep-inline-images",
            "--ii-min-bytes=0",
            "--static-id",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    assert_eq!(
        flpdf_pages_json(&output)["pages"][0]["images"]
            .as_array()
            .unwrap()
            .len(),
        1
    );
    if qpdf.is_some() {
        assert_page_images_match(&qpdf_output, &output);
    }
}

#[test]
fn rewrite_subcommand_accepts_externalize_inline_images() {
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("input.pdf");
    let qpdf_output = directory.path().join("qpdf.pdf");
    let output = directory.path().join("output.pdf");
    std::fs::write(&input, inline_image_pdf()).expect("write input");

    let qpdf = run_qpdf_rewrite_if_available(
        &[
            "--externalize-inline-images".to_owned(),
            "--ii-min-bytes=0".to_owned(),
            "--static-id".to_owned(),
        ],
        &input,
        &qpdf_output,
    );
    if let Some(qpdf) = &qpdf {
        assert!(qpdf.status.success());
    }

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([
            "rewrite",
            "--externalize-inline-images",
            "--ii-min-bytes=0",
            "--static-id",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    assert_eq!(
        flpdf_pages_json(&output)["pages"][0]["images"]
            .as_array()
            .unwrap()
            .len(),
        1
    );
    if qpdf.is_some() {
        assert_page_images_match(&qpdf_output, &output);
    }
}

#[test]
fn externalize_and_optimize_flags_match_qpdf_truth_table() {
    if !qpdf_or_skip() {
        return;
    }
    let cases = [
        (false, false, false),
        (false, false, true),
        (false, true, false),
        (false, true, true),
        (true, false, false),
        (true, false, true),
        (true, true, false),
        (true, true, true),
    ];
    for (externalize, optimize, keep_inline) in cases {
        let directory = tempfile::tempdir().expect("tempdir");
        let input = directory.path().join("input.pdf");
        let qpdf_output = directory.path().join("qpdf.pdf");
        let flpdf_output = directory.path().join("flpdf.pdf");
        std::fs::write(&input, inline_image_pdf()).expect("write input");
        let flags = image_transform_flags(externalize, optimize, keep_inline);

        let qpdf = run_qpdf_rewrite(&flags, &input, &qpdf_output);
        assert!(
            qpdf.status.success(),
            "qpdf truth-table case ({externalize}, {optimize}, {keep_inline}) failed: {}",
            String::from_utf8_lossy(&qpdf.stderr)
        );
        let flpdf = run_flpdf_rewrite(&flags, &input, &flpdf_output);
        assert!(
            flpdf.status.success(),
            "flpdf truth-table case ({externalize}, {optimize}, {keep_inline}) failed: {}",
            String::from_utf8_lossy(&flpdf.stderr)
        );
        assert_page_images_match(&qpdf_output, &flpdf_output);
        // Rows where qpdf keeps the image inline produce no XObject at all, so
        // the page-image JSON is `[] == []` for them. The whole-file
        // comparison sees the retained `BI ... EI` content itself.
        let extra: Vec<&str> = flags
            .iter()
            .filter(|flag| flag.as_str() != "--static-id")
            .map(String::as_str)
            .collect();
        assert_qdf_bytes_match(
            &input,
            &extra,
            &format!("truth table ({externalize}, {optimize}, {keep_inline})"),
        );
    }
}

#[test]
fn page_selection_with_externalization_matches_qpdf() {
    if !qpdf_or_skip() {
        return;
    }
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("input.pdf");
    let qpdf_output = directory.path().join("qpdf.pdf");
    let flpdf_output = directory.path().join("flpdf.pdf");
    std::fs::write(&input, two_page_inline_image_pdf()).expect("write input");

    let qpdf = run_qpdf_page_selection(&input, &qpdf_output);
    assert!(
        qpdf.status.success(),
        "qpdf --pages externalization failed: {}",
        String::from_utf8_lossy(&qpdf.stderr)
    );
    let flpdf = run_flpdf_page_selection(&input, &flpdf_output);
    assert!(
        flpdf.status.success(),
        "flpdf --pages externalization failed: {}",
        String::from_utf8_lossy(&flpdf.stderr)
    );
    assert_page_images_match(&qpdf_output, &flpdf_output);
    // The page-image JSON is identical for either selected page, so it cannot
    // tell them apart; the whole-file comparison can.
    assert_page_selection_qdf_bytes_match(&input);
}

#[test]
fn nested_forms_named_colorspaces_and_empty_pages_match_qpdf() {
    if !qpdf_or_skip() {
        return;
    }
    let cases = [
        ("nested-form", nested_form_inline_image_pdf()),
        ("named-colorspace", named_colorspace_inline_image_pdf()),
        ("no-inline-image", no_inline_image_pdf()),
    ];
    for (name, bytes) in cases {
        let directory = tempfile::tempdir().expect("tempdir");
        let input = directory.path().join(format!("{name}-input.pdf"));
        let qpdf_output = directory.path().join(format!("{name}-qpdf.pdf"));
        let flpdf_output = directory.path().join(format!("{name}-flpdf.pdf"));
        std::fs::write(&input, bytes).expect("write input");
        let flags = vec![
            "--externalize-inline-images".to_owned(),
            "--ii-min-bytes=0".to_owned(),
            "--static-id".to_owned(),
        ];

        let qpdf = run_qpdf_rewrite(&flags, &input, &qpdf_output);
        assert!(
            qpdf.status.success(),
            "qpdf {name} externalization failed: {}",
            String::from_utf8_lossy(&qpdf.stderr)
        );
        let flpdf = run_flpdf_rewrite(&flags, &input, &flpdf_output);
        assert!(
            flpdf.status.success(),
            "flpdf {name} externalization failed: {}",
            String::from_utf8_lossy(&flpdf.stderr)
        );
        assert_page_images_match(&qpdf_output, &flpdf_output);
        assert_qdf_bytes_match(
            &input,
            &["--externalize-inline-images", "--ii-min-bytes=0"],
            name,
        );
    }
}

#[test]
fn malformed_resource_containers_match_qpdf_for_each_inline_image() {
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("malformed-resources-input.pdf");
    std::fs::write(&input, malformed_resource_containers_inline_images_pdf()).expect("write input");

    assert_qdf_bytes_match(
        &input,
        &["--externalize-inline-images", "--ii-min-bytes=0"],
        "malformed resource containers",
    );
}

#[test]
fn damaged_inline_image_recovery_matches_qpdf() {
    if !qpdf_or_skip() {
        return;
    }
    let directory = tempfile::tempdir().expect("tempdir");
    let input = directory.path().join("damaged-input.pdf");
    let qpdf_output = directory.path().join("damaged-qpdf.pdf");
    let flpdf_output = directory.path().join("damaged-flpdf.pdf");
    std::fs::write(&input, damaged_inline_image_pdf()).expect("write input");
    let flags = vec![
        "--externalize-inline-images".to_owned(),
        "--ii-min-bytes=0".to_owned(),
        "--static-id".to_owned(),
    ];

    let qpdf = run_qpdf_rewrite(&flags, &input, &qpdf_output);
    assert!(
        qpdf.status.success(),
        "qpdf damaged inline-image recovery failed: {}",
        String::from_utf8_lossy(&qpdf.stderr)
    );
    let flpdf = run_flpdf_rewrite(&flags, &input, &flpdf_output);
    assert!(
        flpdf.status.success(),
        "flpdf damaged inline-image recovery failed: {}",
        String::from_utf8_lossy(&flpdf.stderr)
    );
    assert_page_images_match(&qpdf_output, &flpdf_output);
    assert_qdf_bytes_match(
        &input,
        &["--externalize-inline-images", "--ii-min-bytes=0"],
        "damaged inline image",
    );
}