shadowforge 0.3.3

Quantum-resistant steganography toolkit for journalists and whistleblowers
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
//! PDF processing adapter using lopdf and pdfium-render.

use std::collections::HashMap;
use std::env;
use std::io::BufWriter;
use std::path::Path;

use base64::Engine;
use base64::engine::general_purpose;
use bytes::Bytes;
use image::{DynamicImage, ImageFormat};
use lopdf::{Document, Object, dictionary};
use pdfium_render::prelude::*;

use crate::domain::analysis::estimate_capacity;
use crate::domain::errors::{PdfError, StegoError};
use crate::domain::ports::{EmbedTechnique, ExtractTechnique, PdfProcessor};
use crate::domain::types::{Capacity, CoverMedia, CoverMediaKind, Payload, StegoTechnique};

// Metadata keys
const KEY_PAGE_COUNT: &str = "page_count";
const DEFAULT_DPI: u16 = 150;

/// PDF processor implementation using lopdf and pdfium-render.
///
/// Handles PDF loading/saving, page rasterisation, and PDF reconstruction.
#[derive(Debug)]
pub struct PdfProcessorImpl {
    /// DPI for page rasterisation.
    dpi: u16,
}

impl Default for PdfProcessorImpl {
    fn default() -> Self {
        Self { dpi: DEFAULT_DPI }
    }
}

impl PdfProcessorImpl {
    /// Create a new PDF processor with the given DPI.
    #[must_use]
    pub const fn new(dpi: u16) -> Self {
        Self { dpi }
    }

    fn bind_pdfium() -> Result<Pdfium, PdfError> {
        let mut bind_errors = Vec::new();

        // 1. Try explicit env var override (highest priority)
        if let Some(pdfium_dir) = env::var_os("PDFIUM_DYNAMIC_LIB_PATH") {
            let library_path = Pdfium::pdfium_platform_library_name_at_path(&pdfium_dir);
            match Pdfium::bind_to_library(library_path) {
                Ok(bindings) => return Ok(Pdfium::new(bindings)),
                Err(error) => bind_errors.push(format!(
                    "PDFIUM_DYNAMIC_LIB_PATH={}: {error}",
                    Path::new(&pdfium_dir).display()
                )),
            }
        }

        // 2. Try system library (searched via the OS dynamic linker)
        match Pdfium::bind_to_system_library() {
            Ok(bindings) => return Ok(Pdfium::new(bindings)),
            Err(error) => {
                bind_errors.push(format!("system library: {error}"));
            }
        }

        // 3. Try local directory (e.g., ./)
        let local_library = Pdfium::pdfium_platform_library_name_at_path("./");
        match Pdfium::bind_to_library(local_library) {
            Ok(bindings) => return Ok(Pdfium::new(bindings)),
            Err(error) => bind_errors.push(format!("./: {error}")),
        }

        // 4. Fail with helpful error — use PdfError::BindFailed so it's not confused with a page render failure
        Err(PdfError::BindFailed {
            reason: format!(
                "Failed to load pdfium library. Binding attempts: {}. \
                 Download a prebuilt binary from https://github.com/bblanchon/pdfium-binaries/, \
                 set PDFIUM_DYNAMIC_LIB_PATH, or disable the 'pdf' feature with --no-default-features --features corpus,adaptive.",
                bind_errors.join("; ")
            ),
        })
    }
}

impl PdfProcessor for PdfProcessorImpl {
    fn load_pdf(&self, path: &Path) -> Result<CoverMedia, PdfError> {
        // Load PDF document
        let doc = Document::load(path).map_err(|e| PdfError::ParseFailed {
            reason: e.to_string(),
        })?;

        // Check if encrypted
        if doc.is_encrypted() {
            return Err(PdfError::Encrypted);
        }

        // Count pages
        let page_count = doc.get_pages().len();

        // Read raw bytes
        let bytes = std::fs::read(path).map_err(|e| PdfError::IoError {
            reason: e.to_string(),
        })?;

        // Build metadata
        let mut metadata = HashMap::new();
        metadata.insert(KEY_PAGE_COUNT.to_string(), page_count.to_string());

        Ok(CoverMedia {
            kind: CoverMediaKind::PdfDocument,
            data: Bytes::from(bytes),
            metadata,
        })
    }

    fn save_pdf(&self, media: &CoverMedia, path: &Path) -> Result<(), PdfError> {
        // Write raw PDF bytes to file
        std::fs::write(path, &media.data).map_err(|e| PdfError::IoError {
            reason: e.to_string(),
        })?;

        Ok(())
    }

    fn render_pages_to_images(&self, pdf: &CoverMedia) -> Result<Vec<CoverMedia>, PdfError> {
        // Initialize pdfium library using the CI-provided path when available.
        let pdfium = Self::bind_pdfium()?;

        // Load PDF from bytes
        let document = pdfium
            .load_pdf_from_byte_vec(pdf.data.to_vec(), None)
            .map_err(|e| PdfError::ParseFailed {
                reason: e.to_string(),
            })?;

        let page_count = document.pages().len();
        let mut images = Vec::with_capacity(page_count as usize);

        // Render each page
        for page_index in 0..page_count {
            let page = document
                .pages()
                .get(page_index)
                .map_err(|e| PdfError::RenderFailed {
                    page: page_index as usize,
                    reason: e.to_string(),
                })?;

            // Render to bitmap
            #[expect(
                clippy::cast_possible_truncation,
                reason = "DPI calculation for render"
            )]
            let target_width = (page.width().value * f32::from(self.dpi) / 72.0) as i32;

            let bitmap = page
                .render_with_config(&PdfRenderConfig::new().set_target_width(target_width))
                .map_err(|e| PdfError::RenderFailed {
                    page: page_index as usize,
                    reason: e.to_string(),
                })?;

            // Convert to RGBA8 image
            let width = bitmap.width().cast_unsigned();
            let height = bitmap.height().cast_unsigned();
            let rgba_data = bitmap.as_rgba_bytes();

            let img =
                image::RgbaImage::from_raw(width, height, rgba_data.clone()).ok_or_else(|| {
                    PdfError::RenderFailed {
                        page: page_index as usize,
                        reason: "invalid bitmap dimensions".to_string(),
                    }
                })?;

            // Build metadata
            let mut metadata = HashMap::new();
            metadata.insert("width".to_string(), width.to_string());
            metadata.insert("height".to_string(), height.to_string());
            metadata.insert("format".to_string(), "Png".to_string());
            metadata.insert("page_index".to_string(), page_index.to_string());

            images.push(CoverMedia {
                kind: CoverMediaKind::PngImage,
                data: Bytes::from(img.into_raw()),
                metadata,
            });
        }

        Ok(images)
    }

    #[expect(
        clippy::too_many_lines,
        reason = "PDF reconstruction logic is inherently complex"
    )]
    fn rebuild_pdf_from_images(
        &self,
        images: Vec<CoverMedia>,
        _original: &CoverMedia,
    ) -> Result<CoverMedia, PdfError> {
        // Create a new PDF document
        let mut doc = Document::with_version("1.7");

        // Add each image as a page
        for (page_index, img_media) in images.iter().enumerate() {
            // Parse dimensions from metadata
            let width: u32 = img_media
                .metadata
                .get("width")
                .ok_or_else(|| PdfError::RebuildFailed {
                    reason: "missing width metadata".to_string(),
                })?
                .parse()
                .map_err(|e: std::num::ParseIntError| PdfError::RebuildFailed {
                    reason: e.to_string(),
                })?;

            let height: u32 = img_media
                .metadata
                .get("height")
                .ok_or_else(|| PdfError::RebuildFailed {
                    reason: "missing height metadata".to_string(),
                })?
                .parse()
                .map_err(|e: std::num::ParseIntError| PdfError::RebuildFailed {
                    reason: e.to_string(),
                })?;

            // Convert RGBA data to PNG bytes
            let img = image::RgbaImage::from_raw(width, height, img_media.data.to_vec())
                .ok_or_else(|| PdfError::RebuildFailed {
                    reason: "invalid image dimensions or data length".to_string(),
                })?;

            let dynamic_img = DynamicImage::ImageRgba8(img);
            let mut png_bytes = Vec::new();
            dynamic_img
                .write_to(&mut std::io::Cursor::new(&mut png_bytes), ImageFormat::Png)
                .map_err(|e| PdfError::RebuildFailed {
                    reason: e.to_string(),
                })?;

            // Create a page with the image dimensions (convert pixels to points: 72 DPI)
            #[expect(clippy::cast_precision_loss, reason = "image dimensions to PDF points")]
            let page_width = width as f32 * 72.0 / f32::from(self.dpi);
            #[expect(clippy::cast_precision_loss, reason = "image dimensions to PDF points")]
            let page_height = height as f32 * 72.0 / f32::from(self.dpi);

            let page_id = doc.new_object_id();
            let page = doc.add_object(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), page_width.into(), page_height.into()],
                "Contents" => Object::Reference((page_id.0 + 1, 0)),
                "Resources" => lopdf::dictionary! {
                    "XObject" => lopdf::dictionary! {
                        "Image1" => Object::Reference((page_id.0 + 2, 0)),
                    },
                },
            });

            // Create content stream that displays the image
            let content = format!("q\n{page_width} 0 0 {page_height} 0 0 cm\n/Image1 Do\nQ");
            let content_id = doc.add_object(lopdf::Stream::new(
                lopdf::dictionary! {},
                content.into_bytes(),
            ));

            // Add the PNG image as an XObject
            let image_id = doc.add_object(lopdf::Stream::new(
                lopdf::dictionary! {
                    "Type" => "XObject",
                    "Subtype" => "Image",
                    "Width" => i64::from(width),
                    "Height" => i64::from(height),
                    "ColorSpace" => "DeviceRGB",
                    "BitsPerComponent" => 8,
                    "Filter" => "FlateDecode",
                },
                png_bytes,
            ));

            // Verify object IDs match what we referenced
            assert_eq!(page, (page_id.0, 0));
            assert_eq!(content_id, (page_id.0 + 1, 0));
            assert_eq!(image_id, (page_id.0 + 2, 0));

            // Add page to pages collection
            if doc.catalog().is_err() {
                // Create catalog and pages root
                let pages_obj_id = doc.new_object_id();
                let catalog_id = doc.add_object(lopdf::dictionary! {
                    "Type" => "Catalog",
                    "Pages" => Object::Reference(pages_obj_id),
                });
                doc.trailer.set("Root", Object::Reference(catalog_id));

                doc.objects.insert(
                    pages_obj_id,
                    lopdf::Object::Dictionary(lopdf::dictionary! {
                        "Type" => "Pages",
                        "Kids" => vec![Object::Reference(page)],
                        "Count" => 1,
                    }),
                );
            } else {
                // Add to existing pages
                if let Ok(pages_ref) = doc.catalog().and_then(|c| c.get(b"Pages"))
                    && let Ok(pages_obj_id) = pages_ref.as_reference()
                    && let Ok(pages_dict) = doc.get_object_mut(pages_obj_id)
                    && let Object::Dictionary(dict) = pages_dict
                {
                    // Get current kids array
                    let mut kids = if let Ok(Object::Array(arr)) = dict.get(b"Kids") {
                        arr.clone()
                    } else {
                        vec![]
                    };
                    kids.push(Object::Reference(page));

                    dict.set("Kids", Object::Array(kids));
                    #[expect(clippy::cast_possible_wrap, reason = "page count fits in i64")]
                    dict.set("Count", (page_index + 1) as i64);
                }
            }
        }

        // Serialize to bytes
        let mut pdf_bytes = Vec::new();
        doc.save_to(&mut BufWriter::new(&mut pdf_bytes))
            .map_err(|e| PdfError::RebuildFailed {
                reason: e.to_string(),
            })?;

        // Build metadata
        let mut metadata = HashMap::new();
        metadata.insert(KEY_PAGE_COUNT.to_string(), images.len().to_string());

        Ok(CoverMedia {
            kind: CoverMediaKind::PdfDocument,
            data: Bytes::from(pdf_bytes),
            metadata,
        })
    }

    fn embed_in_content_stream(
        &self,
        pdf: CoverMedia,
        payload: &Payload,
    ) -> Result<CoverMedia, PdfError> {
        // Load PDF from bytes
        let mut doc = Document::load_from(&pdf.data[..]).map_err(|e| PdfError::ParseFailed {
            reason: e.to_string(),
        })?;

        // Convert payload to bits
        let payload_bits: Vec<u8> = payload
            .as_bytes()
            .iter()
            .flat_map(|byte| (0..8).rev().map(move |i| (byte >> i) & 1))
            .collect();

        let mut bit_index = 0;

        // Iterate through all objects to find content streams
        let object_ids: Vec<_> = doc.objects.keys().copied().collect();
        for obj_id in object_ids {
            if bit_index >= payload_bits.len() {
                break;
            }

            if let Ok(obj) = doc.get_object_mut(obj_id)
                && let Object::Stream(stream) = obj
            {
                // Parse content stream
                let content = String::from_utf8_lossy(&stream.content);
                let mut modified_content = String::new();
                let mut tokens: Vec<&str> = content.split_whitespace().collect();

                for token in &mut tokens {
                    if bit_index >= payload_bits.len() {
                        modified_content.push_str(token);
                        modified_content.push(' ');
                        continue;
                    }

                    // Check if token is a number
                    if let Ok(mut num) = token.parse::<i32>() {
                        // Embed bit in LSB — bit_index < payload_bits.len() guaranteed by guard above
                        if let Some(&bit) = payload_bits.get(bit_index) {
                            if bit == 1 {
                                num |= 1; // Set LSB
                            } else {
                                num &= !1; // Clear LSB
                            }
                        }
                        modified_content.push_str(&num.to_string());
                        bit_index += 1;
                    } else {
                        modified_content.push_str(token);
                    }
                    modified_content.push(' ');
                }

                // Update stream content
                stream.set_content(modified_content.trim().as_bytes().to_vec());
            }
        }

        if bit_index < payload_bits.len() {
            return Err(PdfError::EmbedFailed {
                reason: format!(
                    "insufficient capacity: embedded {bit_index}/{} bits",
                    payload_bits.len()
                ),
            });
        }

        // Serialize modified PDF
        let mut pdf_bytes = Vec::new();
        doc.save_to(&mut pdf_bytes)
            .map_err(|e| PdfError::EmbedFailed {
                reason: e.to_string(),
            })?;

        Ok(CoverMedia {
            kind: pdf.kind,
            data: Bytes::from(pdf_bytes),
            metadata: pdf.metadata,
        })
    }

    fn extract_from_content_stream(&self, pdf: &CoverMedia) -> Result<Payload, PdfError> {
        // Load PDF from bytes
        let doc = Document::load_from(&pdf.data[..]).map_err(|e| PdfError::ParseFailed {
            reason: e.to_string(),
        })?;

        let mut extracted_bits = Vec::new();

        // Iterate through all objects to find content streams
        for obj in doc.objects.values() {
            if let Object::Stream(stream) = obj {
                // Parse content stream
                let content = String::from_utf8_lossy(&stream.content);
                let tokens: Vec<&str> = content.split_whitespace().collect();

                for token in tokens {
                    // Check if token is a number
                    if let Ok(num) = token.parse::<i32>() {
                        // Extract LSB
                        #[expect(clippy::cast_sign_loss, reason = "LSB is always 0 or 1")]
                        extracted_bits.push((num & 1) as u8);
                    }
                }
            }
        }

        // Convert bits to bytes
        if extracted_bits.is_empty() {
            return Err(PdfError::ExtractFailed {
                reason: "no numeric values found in content streams".to_string(),
            });
        }

        let mut payload_bytes = Vec::new();
        for chunk in extracted_bits.chunks(8) {
            if chunk.len() == 8 {
                let mut byte = 0u8;
                for (i, bit) in chunk.iter().enumerate() {
                    byte |= bit << (7 - i);
                }
                payload_bytes.push(byte);
            }
        }

        Ok(Payload::from_bytes(payload_bytes))
    }

    fn embed_in_metadata(
        &self,
        pdf: CoverMedia,
        payload: &Payload,
    ) -> Result<CoverMedia, PdfError> {
        // Load PDF from bytes
        let mut doc = Document::load_from(&pdf.data[..]).map_err(|e| PdfError::ParseFailed {
            reason: e.to_string(),
        })?;

        // Base64-encode payload
        let encoded = general_purpose::STANDARD.encode(payload.as_bytes());

        // Create XMP metadata with custom field
        let xmp_content = format!(
            r#"<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/">
  <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
    <rdf:Description rdf:about=""
      xmlns:sf="http://shadowforge.org/ns/1.0/">
      <sf:HiddenData>{encoded}</sf:HiddenData>
    </rdf:Description>
  </rdf:RDF>
</x:xmpmeta>
<?xpacket end="w"?>"#
        );

        // Create metadata stream
        let metadata_id = doc.add_object(lopdf::Stream::new(
            lopdf::dictionary! {
                "Type" => "Metadata",
                "Subtype" => "XML",
            },
            xmp_content.into_bytes(),
        ));

        // Add metadata reference to catalog
        if let Ok(catalog) = doc.catalog_mut() {
            catalog.set("Metadata", Object::Reference(metadata_id));
        } else {
            return Err(PdfError::EmbedFailed {
                reason: "failed to access catalog".to_string(),
            });
        }

        // Serialize modified PDF
        let mut pdf_bytes = Vec::new();
        doc.save_to(&mut pdf_bytes)
            .map_err(|e| PdfError::EmbedFailed {
                reason: e.to_string(),
            })?;

        Ok(CoverMedia {
            kind: pdf.kind,
            data: Bytes::from(pdf_bytes),
            metadata: pdf.metadata,
        })
    }

    fn extract_from_metadata(&self, pdf: &CoverMedia) -> Result<Payload, PdfError> {
        // Load PDF from bytes
        let doc = Document::load_from(&pdf.data[..]).map_err(|e| PdfError::ParseFailed {
            reason: e.to_string(),
        })?;

        // Get catalog
        let catalog = doc.catalog().map_err(|e| PdfError::ExtractFailed {
            reason: format!("failed to access catalog: {e}"),
        })?;

        // Get metadata reference
        let metadata_ref = catalog
            .get(b"Metadata")
            .map_err(|_| PdfError::ExtractFailed {
                reason: "no metadata found in catalog".to_string(),
            })?
            .as_reference()
            .map_err(|_| PdfError::ExtractFailed {
                reason: "metadata is not a reference".to_string(),
            })?;

        // Get metadata stream
        let metadata_obj = doc
            .get_object(metadata_ref)
            .map_err(|e| PdfError::ExtractFailed {
                reason: format!("failed to get metadata object: {e}"),
            })?;

        let metadata_stream = metadata_obj
            .as_stream()
            .map_err(|_| PdfError::ExtractFailed {
                reason: "metadata is not a stream".to_string(),
            })?;

        // Parse XMP content
        let xmp_content = String::from_utf8_lossy(&metadata_stream.content);

        // Extract base64 data from <sf:HiddenData> tag
        let start_tag = "<sf:HiddenData>";
        let end_tag = "</sf:HiddenData>";

        let start_idx = xmp_content
            .find(start_tag)
            .ok_or_else(|| PdfError::ExtractFailed {
                reason: "no sf:HiddenData tag found".to_string(),
            })?
            .strict_add(start_tag.len());

        let end_idx = xmp_content
            .find(end_tag)
            .ok_or_else(|| PdfError::ExtractFailed {
                reason: "no closing sf:HiddenData tag found".to_string(),
            })?;

        let encoded_data = &xmp_content[start_idx..end_idx];

        // Decode base64
        let decoded = general_purpose::STANDARD
            .decode(encoded_data.trim())
            .map_err(|e| PdfError::ExtractFailed {
                reason: format!("base64 decode failed: {e}"),
            })?;

        Ok(Payload::from_bytes(decoded))
    }
}

fn ensure_pdf_cover(cover: &CoverMedia, technique: StegoTechnique) -> Result<Capacity, StegoError> {
    if cover.kind != CoverMediaKind::PdfDocument {
        return Err(StegoError::UnsupportedCoverType {
            reason: format!("{technique:?} requires a PDF cover"),
        });
    }

    Ok(Capacity {
        bytes: estimate_capacity(cover, technique),
        technique,
    })
}

fn map_pdf_error(error: PdfError) -> StegoError {
    match error {
        PdfError::Encrypted => StegoError::UnsupportedCoverType {
            reason: "encrypted PDF documents are not supported".to_string(),
        },
        PdfError::ExtractFailed { .. } => StegoError::NoPayloadFound,
        PdfError::RenderFailed { page, reason } => StegoError::MalformedCoverData {
            reason: format!("pdf render failed on page {page}: {reason}"),
        },
        PdfError::ParseFailed { reason }
        | PdfError::RebuildFailed { reason }
        | PdfError::EmbedFailed { reason }
        | PdfError::IoError { reason } => StegoError::MalformedCoverData {
            reason: format!("pdf processing failed: {reason}"),
        },
        PdfError::BindFailed { reason } => StegoError::UnsupportedCoverType {
            reason: format!("pdfium library is not available: {reason}"),
        },
    }
}

/// Stego adapter that embeds payloads in PDF content streams.
#[derive(Debug, Default)]
pub struct PdfContentStreamStego {
    processor: PdfProcessorImpl,
}

impl PdfContentStreamStego {
    /// Create a content-stream PDF stego adapter with default processor settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl EmbedTechnique for PdfContentStreamStego {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::PdfContentStream
    }

    fn capacity(&self, cover: &CoverMedia) -> Result<Capacity, StegoError> {
        ensure_pdf_cover(cover, <Self as EmbedTechnique>::technique(self))
    }

    fn embed(&self, cover: CoverMedia, payload: &Payload) -> Result<CoverMedia, StegoError> {
        ensure_pdf_cover(&cover, <Self as EmbedTechnique>::technique(self))?;
        self.processor
            .embed_in_content_stream(cover, payload)
            .map_err(map_pdf_error)
    }
}

impl ExtractTechnique for PdfContentStreamStego {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::PdfContentStream
    }

    fn extract(&self, stego: &CoverMedia) -> Result<Payload, StegoError> {
        ensure_pdf_cover(stego, <Self as ExtractTechnique>::technique(self))?;
        self.processor
            .extract_from_content_stream(stego)
            .map_err(map_pdf_error)
    }
}

/// Stego adapter that embeds payloads in PDF metadata fields.
#[derive(Debug, Default)]
pub struct PdfMetadataStego {
    processor: PdfProcessorImpl,
}

impl PdfMetadataStego {
    /// Create a metadata PDF stego adapter with default processor settings.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

impl EmbedTechnique for PdfMetadataStego {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::PdfMetadata
    }

    fn capacity(&self, cover: &CoverMedia) -> Result<Capacity, StegoError> {
        ensure_pdf_cover(cover, <Self as EmbedTechnique>::technique(self))
    }

    fn embed(&self, cover: CoverMedia, payload: &Payload) -> Result<CoverMedia, StegoError> {
        ensure_pdf_cover(&cover, <Self as EmbedTechnique>::technique(self))?;
        self.processor
            .embed_in_metadata(cover, payload)
            .map_err(map_pdf_error)
    }
}

impl ExtractTechnique for PdfMetadataStego {
    fn technique(&self) -> StegoTechnique {
        StegoTechnique::PdfMetadata
    }

    fn extract(&self, stego: &CoverMedia) -> Result<Payload, StegoError> {
        ensure_pdf_cover(stego, <Self as ExtractTechnique>::technique(self))?;
        self.processor
            .extract_from_metadata(stego)
            .map_err(map_pdf_error)
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    type TestResult = Result<(), Box<dyn std::error::Error>>;

    #[test]
    fn test_load_minimal_pdf() -> TestResult {
        let processor = PdfProcessorImpl::default();
        let dir = tempdir()?;
        let path = dir.path().join("minimal.pdf");

        // Create a minimal valid PDF with one page
        let mut doc = Document::with_version("1.7");
        let catalog_pages = doc.new_object_id();
        let first_page = doc.new_object_id();

        doc.objects.insert(
            first_page,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
                "Contents" => Object::Reference((first_page.0 + 1, 0)),
            }),
        );

        doc.add_object(lopdf::Stream::new(lopdf::dictionary! {}, b"".to_vec()));

        doc.objects.insert(
            catalog_pages,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Pages",
                "Kids" => vec![Object::Reference(first_page)],
                "Count" => 1,
            }),
        );

        let catalog_id = doc.add_object(lopdf::dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(catalog_pages),
        });

        doc.trailer.set("Root", Object::Reference(catalog_id));
        doc.save(&path)?;

        // Load it
        let media = processor.load_pdf(&path)?;
        assert_eq!(media.kind, CoverMediaKind::PdfDocument);
        assert_eq!(media.metadata.get(KEY_PAGE_COUNT), Some(&"1".to_string()));
        Ok(())
    }

    #[test]
    #[ignore = "requires pdfium system library"]
    fn test_render_pages_returns_correct_count() -> TestResult {
        let processor = PdfProcessorImpl::default();
        let dir = tempdir()?;
        let path = dir.path().join("two_page.pdf");

        // Create a 2-page PDF
        let mut doc = Document::with_version("1.7");
        let catalog_pages = doc.new_object_id();

        let page1_id = doc.new_object_id();
        doc.objects.insert(
            page1_id,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
                "Contents" => Object::Reference((page1_id.0 + 1, 0)),
            }),
        );
        doc.add_object(lopdf::Stream::new(lopdf::dictionary! {}, b"".to_vec()));

        let page2_id = doc.new_object_id();
        doc.objects.insert(
            page2_id,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
                "Contents" => Object::Reference((page2_id.0 + 1, 0)),
            }),
        );
        doc.add_object(lopdf::Stream::new(lopdf::dictionary! {}, b"".to_vec()));

        doc.objects.insert(
            catalog_pages,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Pages",
                "Kids" => vec![
                    Object::Reference(page1_id),
                    Object::Reference(page2_id),
                ],
                "Count" => 2,
            }),
        );

        let catalog_id = doc.add_object(lopdf::dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(catalog_pages),
        });

        doc.trailer.set("Root", Object::Reference(catalog_id));
        doc.save(&path)?;

        // Load and render
        let media = processor.load_pdf(&path)?;
        let images = processor.render_pages_to_images(&media)?;
        assert_eq!(images.len(), 2);
        Ok(())
    }

    #[test]
    #[ignore = "requires pdfium system library"]
    fn test_rebuild_pdf_roundtrip() -> TestResult {
        let processor = PdfProcessorImpl::default();
        let dir = tempdir()?;
        let path = dir.path().join("original.pdf");

        // Create a 2-page PDF
        let mut doc = Document::with_version("1.7");
        let catalog_pages = doc.new_object_id();

        let page1_id = doc.new_object_id();
        doc.objects.insert(
            page1_id,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
                "Contents" => Object::Reference((page1_id.0 + 1, 0)),
            }),
        );
        doc.add_object(lopdf::Stream::new(lopdf::dictionary! {}, b"".to_vec()));

        let page2_id = doc.new_object_id();
        doc.objects.insert(
            page2_id,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
                "Contents" => Object::Reference((page2_id.0 + 1, 0)),
            }),
        );
        doc.add_object(lopdf::Stream::new(lopdf::dictionary! {}, b"".to_vec()));

        doc.objects.insert(
            catalog_pages,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Pages",
                "Kids" => vec![
                    Object::Reference(page1_id),
                    Object::Reference(page2_id),
                ],
                "Count" => 2,
            }),
        );

        let catalog_id = doc.add_object(lopdf::dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(catalog_pages),
        });

        doc.trailer.set("Root", Object::Reference(catalog_id));
        doc.save(&path)?;

        // Load, render, rebuild, and reload
        let original = processor.load_pdf(&path)?;
        let images = processor.render_pages_to_images(&original)?;
        let rebuilt = processor.rebuild_pdf_from_images(images, &original)?;

        // Save and reload to verify
        let rebuilt_path = dir.path().join("rebuilt.pdf");
        processor.save_pdf(&rebuilt, &rebuilt_path)?;
        let reloaded = processor.load_pdf(&rebuilt_path)?;

        assert_eq!(
            reloaded.metadata.get(KEY_PAGE_COUNT),
            original.metadata.get(KEY_PAGE_COUNT)
        );
        Ok(())
    }

    #[test]
    #[ignore = "lopdf requires actual encrypted content, not just Encrypt trailer"]
    fn test_encrypted_pdf_error() -> TestResult {
        let processor = PdfProcessorImpl::default();
        let dir = tempdir()?;
        let path = dir.path().join("encrypted.pdf");

        // Create an encrypted PDF
        let mut doc = Document::with_version("1.7");
        let catalog_pages = doc.new_object_id();
        let first_page = doc.new_object_id();

        doc.objects.insert(
            first_page,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
                "Contents" => Object::Reference((first_page.0 + 1, 0)),
            }),
        );

        doc.add_object(lopdf::Stream::new(lopdf::dictionary! {}, b"".to_vec()));

        doc.objects.insert(
            catalog_pages,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Pages",
                "Kids" => vec![Object::Reference(first_page)],
                "Count" => 1,
            }),
        );

        let catalog_id = doc.add_object(lopdf::dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(catalog_pages),
        });

        doc.trailer.set("Root", Object::Reference(catalog_id));

        // Add encryption dictionary
        doc.trailer
            .set("Encrypt", Object::Reference((doc.max_id + 1, 0)));
        doc.objects.insert(
            (doc.max_id + 1, 0),
            Object::Dictionary(lopdf::dictionary! {
                "Filter" => "Standard",
                "V" => 1,
                "R" => 2,
            }),
        );

        doc.save(&path)?;

        // Try to load it
        let result = processor.load_pdf(&path);
        assert!(matches!(result, Err(PdfError::Encrypted)));
        Ok(())
    }

    #[test]
    fn test_content_stream_lsb_roundtrip() -> TestResult {
        let processor = PdfProcessorImpl::default();
        let dir = tempdir()?;
        let path = dir.path().join("test.pdf");

        // Create a test PDF with content stream
        let mut doc = Document::with_version("1.7");
        let catalog_pages = doc.new_object_id();
        let first_page = doc.new_object_id();

        doc.objects.insert(
            first_page,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
                "Contents" => Object::Reference((first_page.0 + 1, 0)),
            }),
        );

        // Content stream with many numeric values for capacity
        let content = b"BT\n/F1 12 Tf\n100 700 Td\n(Hello) Tj\n200 650 Td\n(World) Tj\n50 600 Td\n(Test) Tj\n150 550 Td\n(PDF) Tj\nET\n1 0 0 1 0 0 cm\n";
        doc.add_object(lopdf::Stream::new(lopdf::dictionary! {}, content.to_vec()));

        doc.objects.insert(
            catalog_pages,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Pages",
                "Kids" => vec![Object::Reference(first_page)],
                "Count" => 1,
            }),
        );

        let catalog_id = doc.add_object(lopdf::dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(catalog_pages),
        });

        doc.trailer.set("Root", Object::Reference(catalog_id));
        doc.save(&path)?;

        // Load and embed payload (very small to fit limited capacity)
        let original = processor.load_pdf(&path)?;
        let payload = Payload::from_bytes(vec![0xAB]); // 1 byte = 8 bits (need 8+ numbers)
        let stego = processor.embed_in_content_stream(original, &payload)?;

        // Verify PDF is still parseable
        let stego_path = dir.path().join("stego.pdf");
        processor.save_pdf(&stego, &stego_path)?;
        let reloaded = processor.load_pdf(&stego_path)?;

        // Extract and verify
        let extracted = processor.extract_from_content_stream(&reloaded)?;
        assert_eq!(extracted.as_bytes(), payload.as_bytes());
        Ok(())
    }

    #[test]
    fn test_metadata_embed_roundtrip() -> TestResult {
        let processor = PdfProcessorImpl::default();
        let dir = tempdir()?;
        let path = dir.path().join("test.pdf");

        // Create a minimal test PDF
        let mut doc = Document::with_version("1.7");
        let catalog_pages = doc.new_object_id();
        let first_page = doc.new_object_id();

        doc.objects.insert(
            first_page,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Page",
                "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
                "Contents" => Object::Reference((first_page.0 + 1, 0)),
            }),
        );

        doc.add_object(lopdf::Stream::new(lopdf::dictionary! {}, b"".to_vec()));

        doc.objects.insert(
            catalog_pages,
            Object::Dictionary(lopdf::dictionary! {
                "Type" => "Pages",
                "Kids" => vec![Object::Reference(first_page)],
                "Count" => 1,
            }),
        );

        let catalog_id = doc.add_object(lopdf::dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(catalog_pages),
        });

        doc.trailer.set("Root", Object::Reference(catalog_id));
        doc.save(&path)?;

        // Load and embed payload
        let original = processor.load_pdf(&path)?;
        let payload = Payload::from_bytes(vec![0u8; 128]); // 128-byte payload
        let stego = processor.embed_in_metadata(original, &payload)?;

        // Verify PDF is still parseable
        let stego_path = dir.path().join("stego.pdf");
        processor.save_pdf(&stego, &stego_path)?;
        let reloaded = processor.load_pdf(&stego_path)?;

        // Extract and verify
        let extracted = processor.extract_from_metadata(&reloaded)?;
        assert_eq!(extracted.as_bytes(), payload.as_bytes());
        Ok(())
    }
}