flpdf-cli 0.7.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
//! CLI coverage for qpdf's `--optimize-images` transformation.

use assert_cmd::Command;
use predicates::prelude::*;
use serde_json::Value;
use std::path::Path;
use std::process::Command as ProcessCommand;

fn build_raw_grayscale_image_pdf(width: usize, height: usize) -> Vec<u8> {
    build_raw_image_pdf(width, height, "DeviceGray", 1)
}

fn build_raw_image_pdf(
    width: usize,
    height: usize,
    colorspace: &str,
    components: usize,
) -> Vec<u8> {
    let pixels = vec![128u8; width * height * components];
    build_raw_image_pdf_with_pixels(width, height, colorspace, components, pixels)
}

fn build_raw_image_pdf_with_pixels(
    width: usize,
    height: usize,
    colorspace: &str,
    components: usize,
    pixels: Vec<u8>,
) -> Vec<u8> {
    assert_eq!(pixels.len(), width * height * components);
    let content = b"q 200 0 0 200 0 0 cm /Im1 Do Q\n";
    let image_dictionary = format!(
        "<< /Type /XObject /Subtype /Image /Width {width} /Height {height} /ColorSpace /{colorspace} /BitsPerComponent 8 /Length {} >>",
        pixels.len()
    );
    let content_dictionary = format!("<< /Length {} >>", content.len());
    let objects = [
        (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 << /Im1 5 0 R >> >> /Contents 4 0 R >>".to_vec(),
        ),
        (4, stream_object(content_dictionary.as_bytes(), content)),
        (5, stream_object(image_dictionary.as_bytes(), &pixels)),
    ];

    let mut pdf = b"%PDF-1.4\n".to_vec();
    let mut offsets = Vec::with_capacity(objects.len());
    for (number, body) in objects {
        offsets.push((number, pdf.len()));
        pdf.extend_from_slice(format!("{number} 0 obj\n").as_bytes());
        pdf.extend_from_slice(&body);
        pdf.extend_from_slice(b"\nendobj\n");
    }
    let xref_offset = pdf.len();
    pdf.extend_from_slice(b"xref\n0 6\n");
    pdf.extend_from_slice(b"0000000000 65535 f \n");
    for (_, offset) in offsets {
        pdf.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
    }
    pdf.extend_from_slice(
        format!("trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n{xref_offset}\n%%EOF\n").as_bytes(),
    );
    pdf
}

fn raw_stream(path: &Path, object: u32) -> Vec<u8> {
    let output = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([&format!("--show-object={object}"), "--raw-stream-data"])
        .arg(path)
        .output()
        .expect("run flpdf raw stream");
    assert!(output.status.success(), "raw stream failed: {output:?}");
    output.stdout
}

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 first_image(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:?}");
    let json: Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
    json["pages"][0]["images"][0].clone()
}

fn image_filters(path: &Path) -> Vec<String> {
    first_image(path)["filter"]
        .as_array()
        .expect("image filter array")
        .iter()
        .map(|filter| filter.as_str().expect("filter name").to_owned())
        .collect()
}

fn image_object(path: &Path) -> u32 {
    first_image(path)["object"]
        .as_str()
        .and_then(|object| object.split_whitespace().next())
        .and_then(|number| number.parse().ok())
        .expect("image object reference")
}

fn qpdf_11_9_available() -> bool {
    let output = ProcessCommand::new("/usr/bin/qpdf")
        .arg("--version")
        .output();
    output.is_ok_and(|output| {
        output.status.success() && String::from_utf8_lossy(&output.stdout).contains("11.9.0")
    })
}

fn qpdf_first_image(path: &Path) -> Value {
    let output = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--json", "--json-key=pages"])
        .arg(path)
        .output()
        .expect("run qpdf JSON");
    assert!(output.status.success(), "qpdf JSON failed: {output:?}");
    let json: Value = serde_json::from_slice(&output.stdout).expect("valid qpdf JSON");
    json["pages"][0]["images"][0].clone()
}

fn qpdf_raw_stream(path: &Path, object: u32) -> Vec<u8> {
    let output = ProcessCommand::new("/usr/bin/qpdf")
        .args([&format!("--show-object={object}"), "--raw-stream-data"])
        .arg(path)
        .output()
        .expect("run qpdf raw stream");
    assert!(
        output.status.success(),
        "qpdf raw stream failed: {output:?}"
    );
    output.stdout
}

#[test]
fn rewrite_subcommand_preserves_image_dictionary_and_clears_decode_parms() {
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    let output = tempdir.path().join("output.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["rewrite", "--static-id", "--optimize-images"])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let image = first_image(&output);
    assert_eq!(image["filter"], serde_json::json!(["/DCTDecode"]));
    assert_eq!(image["decodeparms"], serde_json::json!([null]));
    assert_eq!(image["width"], 200);
    assert_eq!(image["height"], 200);
    assert_eq!(image["colorspace"], "/DeviceGray");
}

#[test]
fn optimize_images_honors_inclusive_minimum_width() {
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    let output = tempdir.path().join("output.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([
            "--static-id",
            "--optimize-images",
            "--oi-min-width=200",
            "--oi-min-height=0",
            "--oi-min-area=0",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    assert!(!image_filters(&output).contains(&"/DCTDecode".to_owned()));
}

#[test]
fn optimize_images_uses_one_by_one_sampling_for_cmyk() {
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    let output = tempdir.path().join("output.pdf");
    std::fs::write(&input, build_raw_image_pdf(200, 200, "DeviceCMYK", 4)).expect("write input");

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args([
            "--static-id",
            "--optimize-images",
            "--oi-min-width=0",
            "--oi-min-height=0",
            "--oi-min-area=0",
        ])
        .arg(&input)
        .arg(&output)
        .assert()
        .success();

    let jpeg = raw_stream(&output, image_object(&output));
    let expected_sof = [
        0xff, 0xc0, 0x00, 0x14, 0x08, 0x00, 0xc8, 0x00, 0xc8, 0x04, 0x43, 0x11, 0x00, 0x4d, 0x11,
        0x00, 0x59, 0x11, 0x00, 0x4b, 0x11, 0x00,
    ];
    assert!(
        jpeg.windows(expected_sof.len())
            .any(|window| window == expected_sof),
        "CMYK JPEG should retain qpdf's 1x1 sampling factors"
    );
}

#[test]
fn optimize_images_runs_after_page_selection() {
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    let output = tempdir.path().join("output.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--static-id", "--optimize-images"])
        .arg(&input)
        .args(["--pages", ".", "--"])
        .arg(&output)
        .assert()
        .success();

    assert_eq!(image_filters(&output), vec!["/DCTDecode"]);
}

#[test]
fn optimize_images_is_applied_before_json_pages_output() {
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");

    let output = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--optimize-images", "--json=2", "--json-key=pages"])
        .arg(&input)
        .output()
        .expect("run JSON");
    assert!(output.status.success(), "JSON failed: {output:?}");
    let json: Value = serde_json::from_slice(&output.stdout).expect("valid JSON");
    assert_eq!(
        json["pages"][0]["images"][0]["filter"],
        serde_json::json!(["/DCTDecode"])
    );
}

#[test]
fn optimize_images_recompresses_an_eligible_raw_image() {
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    let output = tempdir.path().join("output.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--static-id", "--optimize-images", "--verbose"])
        .arg(&input)
        .arg(&output)
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "optimizing image reduces size from",
        ));

    assert_eq!(image_filters(&output), vec!["/DCTDecode"]);
}

#[test]
fn optimize_images_emits_qpdf_identical_jpeg_bytes_for_gray_rgb_and_cmyk() {
    if !qpdf_11_9_available() {
        return;
    }

    for (colorspace, components) in [("DeviceGray", 1), ("DeviceRGB", 3), ("DeviceCMYK", 4)] {
        for (pattern, pixels) in [
            ("uniform", vec![128u8; 200 * 200 * components]),
            (
                "structured",
                (0..200 * 200 * components)
                    .map(|index| ((index * 37 + index / 200 * 11) % 256) as u8)
                    .collect(),
            ),
        ] {
            let tempdir = tempfile::tempdir().expect("tempdir");
            let input = tempdir.path().join("input.pdf");
            let qpdf_output = tempdir.path().join("qpdf.pdf");
            let flpdf_output = tempdir.path().join("flpdf.pdf");
            std::fs::write(
                &input,
                build_raw_image_pdf_with_pixels(200, 200, colorspace, components, pixels),
            )
            .expect("write input");

            let qpdf = ProcessCommand::new("/usr/bin/qpdf")
                .args([
                    "--static-id",
                    "--optimize-images",
                    "--oi-min-width=0",
                    "--oi-min-height=0",
                    "--oi-min-area=0",
                ])
                .arg(&input)
                .arg(&qpdf_output)
                .output()
                .expect("run qpdf optimize-images");
            assert!(
                qpdf.status.success(),
                "qpdf optimize-images failed for {colorspace}/{pattern}: {qpdf:?}"
            );

            Command::cargo_bin("flpdf")
                .expect("flpdf binary")
                .args([
                    "--static-id",
                    "--optimize-images",
                    "--oi-min-width=0",
                    "--oi-min-height=0",
                    "--oi-min-area=0",
                ])
                .arg(&input)
                .arg(&flpdf_output)
                .assert()
                .success();

            let qpdf_image = qpdf_first_image(&qpdf_output);
            assert_eq!(
                qpdf_image["filter"],
                serde_json::json!(["/DCTDecode"]),
                "fixture was not optimized by qpdf for {colorspace}/{pattern}"
            );
            assert_eq!(
                image_filters(&flpdf_output),
                vec!["/DCTDecode"],
                "fixture was not optimized by flpdf for {colorspace}/{pattern}"
            );

            let qpdf_object = qpdf_image["object"]
                .as_str()
                .and_then(|object| object.split_whitespace().next())
                .and_then(|number| number.parse().ok())
                .expect("qpdf image object reference");
            let flpdf_object = image_object(&flpdf_output);
            assert_eq!(
                qpdf_raw_stream(&qpdf_output, qpdf_object),
                raw_stream(&flpdf_output, flpdf_object),
                "JPEG bytes differ from qpdf for {colorspace}/{pattern}"
            );
        }
    }
}

#[test]
fn rewrite_subcommand_applies_optimize_images_with_page_selection() {
    // The rewrite subcommand's page-operation guard used to reject
    // --optimize-images unconditionally, even though run_page_extraction
    // (called for `--pages`) already threads image options through via
    // `cmd.optimize_images.then_some(image_options)` — the same way the
    // top-level `--pages` route already does (see
    // optimize_images_runs_after_page_selection above).
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    let output = tempdir.path().join("output.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .arg("rewrite")
        .arg(&input)
        .arg(&output)
        .args(["--static-id", "--optimize-images", "--pages"])
        .arg(&input)
        .args(["1", "--"])
        .assert()
        .success();

    assert_eq!(image_filters(&output), vec!["/DCTDecode"]);
}

#[test]
fn optimize_images_is_accepted_with_check_like_qpdf() {
    if !qpdf_11_9_available() {
        return;
    }
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");

    // `createQPDF` runs `handleTransformations` before `writeQPDF` picks the
    // inspection branch (`QPDFJob.cc:473,484-491`), so the check report comes
    // from the transformed document. Compare against qpdf itself rather than
    // against flpdf without the flag: the check report never names the
    // recompressed image, so a flpdf-vs-flpdf equality stays green whether or
    // not the transformation actually runs.
    let qpdf = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--optimize-images", "--check"])
        .arg(&input)
        .output()
        .expect("run qpdf --check");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--optimize-images", "--check"])
        .arg(&input)
        .output()
        .expect("run flpdf --check");
    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(flpdf.stderr, qpdf.stderr);
}

#[test]
fn externalize_inline_images_is_accepted_with_check_like_qpdf() {
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");

    Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--externalize-inline-images", "--check"])
        .arg(&input)
        .assert()
        .success();
}

#[test]
fn image_transform_options_are_applied_to_inspection_modes_like_qpdf() {
    if !qpdf_11_9_available() {
        return;
    }
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = tempdir.path().join("input.pdf");
    std::fs::write(&input, build_raw_grayscale_image_pdf(200, 200)).expect("write input");
    let inspection_modes = [
        vec!["--show-npages"],
        vec!["--show-pages"],
        vec!["--show-pages", "--with-images"],
        vec!["--show-xref"],
        vec!["--show-linearization"],
        vec!["--show-encryption"],
        vec!["--show-object=trailer"],
    ];

    for image_option in ["--optimize-images", "--externalize-inline-images"] {
        for mode in &inspection_modes {
            let qpdf = ProcessCommand::new("/usr/bin/qpdf")
                .arg(image_option)
                .args(mode)
                .arg(&input)
                .output()
                .expect("run qpdf inspection");
            let flpdf = Command::cargo_bin("flpdf")
                .expect("flpdf binary")
                .arg(image_option)
                .args(mode)
                .arg(&input)
                .output()
                .expect("run flpdf inspection");
            assert_eq!(
                flpdf.status.code(),
                qpdf.status.code(),
                "{image_option} {mode:?}"
            );
            assert_eq!(flpdf.stdout, qpdf.stdout, "{image_option} {mode:?}");
            assert_eq!(flpdf.stderr, qpdf.stderr, "{image_option} {mode:?}");
        }
    }

    // `--show-pages --with-images` is the only inspection report that names the
    // image objects, so it is the only one that can observe the transformation:
    // `--optimize-images` installs a fresh stream through `pdf.newStream()`
    // (`QPDFJob.cc:2156-2177`), moving /Im1 to a new object number. Without
    // this the loop above would still pass if the wiring regressed, since qpdf
    // and flpdf would then merely agree on the untransformed report.
    let plain = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--show-pages", "--with-images"])
        .arg(&input)
        .output()
        .expect("run flpdf --show-pages --with-images");
    let optimized = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--optimize-images", "--show-pages", "--with-images"])
        .arg(&input)
        .output()
        .expect("run flpdf --optimize-images --show-pages --with-images");
    assert_ne!(
        optimized.stdout, plain.stdout,
        "--optimize-images must reach the --show-pages --with-images report"
    );
}

/// A one-page PDF that carries both an optimizable raw image and an embedded
/// file, built with the pinned qpdf so the attachment shape is qpdf's own.
///
/// `tests/fixtures/compat/attachment-two-page.pdf` has an attachment but no
/// image, so the image phase is a no-op there and cannot show whether it ran.
fn image_pdf_with_attachment(directory: &Path) -> std::path::PathBuf {
    let image = directory.join("image.pdf");
    let payload = directory.join("payload.txt");
    let combined = directory.join("image-attachment.pdf");
    std::fs::write(&image, build_raw_grayscale_image_pdf(200, 200)).expect("write image fixture");
    std::fs::write(&payload, b"payload\n").expect("write payload");

    let status = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--static-id", "--compress-streams=n", "--add-attachment"])
        .arg(&payload)
        .args(["--key=attachment.txt", "--"])
        .arg(&image)
        .arg(&combined)
        .status()
        .expect("run qpdf to attach the payload");
    assert!(status.success(), "building the attachment fixture failed");
    combined
}

#[test]
fn optimize_images_runs_with_remove_attachment_like_qpdf() {
    if !qpdf_11_9_available() {
        return;
    }
    let tempdir = tempfile::tempdir().expect("tempdir");
    let input = image_pdf_with_attachment(tempdir.path());
    let qpdf_output = tempdir.path().join("qpdf.pdf");
    let flpdf_output = tempdir.path().join("flpdf.pdf");

    let qpdf = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--optimize-images", "--remove-attachment=attachment.txt"])
        .arg(&input)
        .arg(&qpdf_output)
        .output()
        .expect("run qpdf attachment/image combination");
    assert!(qpdf.status.success(), "qpdf combination failed: {qpdf:?}");

    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--optimize-images", "--remove-attachment=attachment.txt"])
        .arg(&input)
        .arg(&flpdf_output)
        .output()
        .expect("run flpdf attachment/image combination");
    assert_eq!(flpdf.status.code(), qpdf.status.code());

    let qpdf_list = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--list-attachments"])
        .arg(&qpdf_output)
        .output()
        .expect("list qpdf attachments");
    let flpdf_list = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--list-attachments"])
        .arg(&flpdf_output)
        .output()
        .expect("list flpdf attachments");
    assert_eq!(flpdf_list.status.code(), qpdf_list.status.code());
    assert_eq!(flpdf_list.stdout, qpdf_list.stdout);
    assert_eq!(flpdf_list.stderr, qpdf_list.stderr);

    // The image phase has to have run: qpdf recompresses this raw image to
    // DCT, and dropping the transformation would leave the filter list empty.
    assert_eq!(image_filters(&qpdf_output), vec!["/DCTDecode"]);
    assert_eq!(image_filters(&flpdf_output), vec!["/DCTDecode"]);
    // Object identity proves the image phase ran before the attachment phase,
    // the order `handleTransformations` uses (`QPDFJob.cc:2151-2157` then
    // `:2229-2245`).
    assert_eq!(image_object(&flpdf_output), image_object(&qpdf_output));
}

#[test]
fn optimize_images_is_accepted_with_attachment_inspection_like_qpdf() {
    if !qpdf_11_9_available() {
        return;
    }
    let input = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/attachment-two-page.pdf");

    let qpdf_list = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--optimize-images", "--list-attachments"])
        .arg(&input)
        .output()
        .expect("run qpdf attachment listing");
    let flpdf_list = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--optimize-images", "--list-attachments"])
        .arg(&input)
        .output()
        .expect("run flpdf attachment listing");
    assert_eq!(flpdf_list.status.code(), qpdf_list.status.code());
    assert_eq!(flpdf_list.stdout, qpdf_list.stdout);
    assert_eq!(flpdf_list.stderr, qpdf_list.stderr);

    let qpdf_show = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--optimize-images", "--show-attachment=attachment.txt"])
        .arg(&input)
        .output()
        .expect("run qpdf attachment show");
    let flpdf_show = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .args(["--optimize-images", "--show-attachment=attachment.txt"])
        .arg(&input)
        .output()
        .expect("run flpdf attachment show");
    assert_eq!(flpdf_show.status.code(), qpdf_show.status.code());
    assert_eq!(flpdf_show.stdout, qpdf_show.stdout);
    assert_eq!(flpdf_show.stderr, qpdf_show.stderr);
}

#[test]
fn optimize_images_is_accepted_with_empty_attachment_inspection_like_qpdf() {
    if !qpdf_11_9_available() {
        return;
    }
    let qpdf = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--empty", "--optimize-images", "--show-attachment=missing"])
        .output()
        .expect("run qpdf empty attachment inspection");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .env("FLPDF_PROGNAME", "qpdf")
        .args(["--empty", "--optimize-images", "--show-attachment=missing"])
        .output()
        .expect("run flpdf empty attachment inspection");
    assert_eq!(flpdf.status.code(), qpdf.status.code());
    assert_eq!(flpdf.stdout, qpdf.stdout);
    assert_eq!(flpdf.stderr, qpdf.stderr);
}

#[test]
fn optimize_images_is_accepted_with_add_and_copy_attachment_like_qpdf() {
    if !qpdf_11_9_available() {
        return;
    }
    let tempdir = tempfile::tempdir().expect("tempdir");
    let payload = tempdir.path().join("payload.txt");
    std::fs::write(&payload, b"payload").expect("write payload");
    let base =
        Path::new(env!("CARGO_MANIFEST_DIR")).join("../../tests/fixtures/compat/one-page.pdf");
    let donor = Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/fixtures/compat/attachment-two-page.pdf");

    let qpdf_add = tempdir.path().join("qpdf-add.pdf");
    let flpdf_add = tempdir.path().join("flpdf-add.pdf");
    let qpdf = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--optimize-images", "--add-attachment"])
        .arg(&payload)
        .args(["--key=newkey", "--"])
        .arg(&base)
        .arg(&qpdf_add)
        .output()
        .expect("run qpdf add attachment");
    assert!(qpdf.status.success(), "qpdf add failed: {qpdf:?}");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .arg("--optimize-images")
        .arg(&base)
        .args(["--add-attachment"])
        .arg(&payload)
        .args(["--key=newkey", "--"])
        .arg(&flpdf_add)
        .output()
        .expect("run flpdf add attachment");
    assert!(flpdf.status.success(), "flpdf add failed: {flpdf:?}");

    let qpdf_copy = tempdir.path().join("qpdf-copy.pdf");
    let flpdf_copy = tempdir.path().join("flpdf-copy.pdf");
    let qpdf = ProcessCommand::new("/usr/bin/qpdf")
        .args(["--optimize-images", "--copy-attachments-from"])
        .arg(&donor)
        .args(["--"])
        .arg(&base)
        .arg(&qpdf_copy)
        .output()
        .expect("run qpdf copy attachments");
    assert!(qpdf.status.success(), "qpdf copy failed: {qpdf:?}");
    let flpdf = Command::cargo_bin("flpdf")
        .expect("flpdf binary")
        .arg("--optimize-images")
        .arg(&base)
        .args(["--copy-attachments-from"])
        .arg(&donor)
        .args(["--"])
        .arg(&flpdf_copy)
        .output()
        .expect("run flpdf copy attachments");
    assert!(flpdf.status.success(), "flpdf copy failed: {flpdf:?}");

    for (qpdf_output, flpdf_output, key) in [
        (&qpdf_add, &flpdf_add, "newkey"),
        (&qpdf_copy, &flpdf_copy, "attachment.txt"),
    ] {
        let qpdf_list = ProcessCommand::new("/usr/bin/qpdf")
            .arg("--list-attachments")
            .arg(qpdf_output)
            .output()
            .expect("list qpdf attachment output");
        let flpdf_list = Command::cargo_bin("flpdf")
            .expect("flpdf binary")
            .arg("--list-attachments")
            .arg(flpdf_output)
            .output()
            .expect("list flpdf attachment output");
        assert!(String::from_utf8_lossy(&qpdf_list.stdout).contains(key));
        assert!(String::from_utf8_lossy(&flpdf_list.stdout).contains(key));
    }
}