zencodec 0.1.25

Shared traits and types for zen* image codecs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
//! Owned metadata for encode/decode roundtrip.
//!
//! [`Metadata`] carries ICC, EXIF, XMP, CICP, HDR, and orientation data
//! using `Arc<[u8]>` for byte buffers (cheap cloning via ref-count bump).
//!
//! # Forward compatibility
//!
//! This surface is shaped so it never needs a semver-major break. Every
//! growable record ([`Metadata`], [`MetadataFields`], [`ExifPolicy`]) is
//! `#[non_exhaustive]` and built from a constructor plus `with_*` setters, and
//! every disposition enum ([`MetadataPolicy`], [`IccRetention`],
//! [`Retention`](crate::exif::Retention)) is `#[non_exhaustive]` — so new
//! record fields and new enum variants both land additively, and downstream
//! cannot struct-literal or exhaustively match these types. Query
//! [`Retention`](crate::exif::Retention) via
//! [`keeps`](crate::exif::Retention::keeps) / `discards` rather than matching,
//! so callers stay correct as variants are added.
//!
//! Anticipated additive growth (each a new field or variant, never a break):
//! partial-XMP retention beside the whole-segment `xmp` switch, gain-map and
//! depth-map retention, new [`ExifPolicy`] categories, new [`IccRetention`]
//! modes, and new color-signaling fields on [`Metadata`] /
//! [`SourceColor`](crate::SourceColor).
//!
//! The known cross-codec carrier gaps (imazen/zenpipe#36 —
//! `Metadata::orientation` emission, decode-side EXIF-orientation
//! normalization, CICP wiring for native-carrier formats, and AVIF EXIF-blob
//! preservation) are fixable as behavioral changes in the codec adapters:
//! [`Metadata`] already models every value those fixes produce
//! ([`orientation`](Metadata::orientation), [`cicp`](Metadata::cicp),
//! [`exif`](Metadata::exif)), so none require a type, field, or signature
//! change here.

use alloc::sync::Arc;

use crate::Orientation;
use crate::exif::{Exif, ExifPolicy, Retention};
use crate::info::{Cicp, ContentLightLevel, DiffuseWhite, MasteringDisplay};
use zenpixels::{ColorPrimaries, TransferFunction};

/// Owned image metadata for encode/decode roundtrip.
///
/// Byte buffers (ICC, EXIF, XMP) use `Arc<[u8]>` so cloning is a cheap
/// ref-count bump. Construct via [`Metadata::none()`] + builders,
/// or extract from decoded info via `From<&ImageInfo>`.
#[derive(Clone, Debug, Default, PartialEq)]
#[non_exhaustive]
pub struct Metadata {
    /// ICC color profile.
    pub icc_profile: Option<Arc<[u8]>>,
    /// EXIF metadata.
    pub exif: Option<Arc<[u8]>>,
    /// XMP metadata.
    pub xmp: Option<Arc<[u8]>>,
    /// CICP color description.
    pub cicp: Option<Cicp>,
    /// Content Light Level Info for HDR content.
    pub content_light_level: Option<ContentLightLevel>,
    /// Mastering Display Color Volume for HDR content.
    pub mastering_display: Option<MasteringDisplay>,
    /// Absolute-luminance anchor — the nits that a relative-linear sample
    /// value of `1.0` represents.
    ///
    /// Codec-side contract: same as [`crate::SourceColor::diffuse_white`] — emit
    /// `Some(value)` for explicit signals AND for format-defined implicit
    /// defaults; reserve `None` for genuinely-ambiguous cases. See that
    /// field for the per-format guidance.
    pub diffuse_white: Option<DiffuseWhite>,
    /// EXIF orientation.
    pub orientation: Orientation,
}

// Metadata contains 3× Option<Arc<[u8]>> (fat pointers), so size varies by
// pointer width. Catch unexpected growth from new fields or alignment changes.
// (The diffuse_white Option<f32> anchor grew this 104 → 112 on 64-bit.)
#[cfg(target_pointer_width = "64")]
const _: () = assert!(core::mem::size_of::<Metadata>() == 112);

impl Metadata {
    /// Create empty metadata.
    pub fn none() -> Self {
        Self::default()
    }

    /// Set the ICC color profile.
    ///
    /// Accepts `Vec<u8>`, `&[u8]`, or `Arc<[u8]>`.
    pub fn with_icc(mut self, icc: impl Into<Arc<[u8]>>) -> Self {
        self.icc_profile = Some(icc.into());
        self
    }

    /// Set the EXIF metadata.
    ///
    /// Accepts `Vec<u8>`, `&[u8]`, or `Arc<[u8]>`.
    ///
    /// As a convenience, the Orientation tag (0x0112) is parsed from the
    /// blob and stored in `self.orientation` — but only if `self.orientation`
    /// is currently `Identity` (the default). Callers who set orientation
    /// explicitly via [`with_orientation`](Self::with_orientation) before
    /// `with_exif` keep their explicit value; callers who set it after
    /// also override the parsed one.
    pub fn with_exif(mut self, exif: impl Into<Arc<[u8]>>) -> Self {
        let bytes: Arc<[u8]> = exif.into();
        if self.orientation == Orientation::Identity
            && let Some(o) = parse_exif_orientation(&bytes)
        {
            self.orientation = o;
        }
        self.exif = Some(bytes);
        self
    }

    /// Set the EXIF Copyright tag, creating an EXIF blob if there is none and
    /// merging into the existing one otherwise.
    ///
    /// Written as ASCII (Exif 2.x, the most widely-read form). For UTF-8 (Exif
    /// 3.0) or other tags, build the blob via [`exif::Exif`](crate::exif::Exif)
    /// and pass it to [`with_exif`](Self::with_exif). Unparseable existing EXIF
    /// is replaced with a fresh blob carrying just this field.
    #[must_use]
    pub fn with_copyright(self, copyright: &str) -> Self {
        self.set_exif_string(copyright, |e, t| e.set_copyright(t))
    }

    /// Set the EXIF Artist tag. See [`with_copyright`](Self::with_copyright) for
    /// encoding and merge semantics.
    #[must_use]
    pub fn with_artist(self, artist: &str) -> Self {
        self.set_exif_string(artist, |e, t| e.set_artist(t))
    }

    /// Shared helper for [`with_copyright`]/[`with_artist`]: parse the existing
    /// EXIF (or start fresh via [`Exif::new`]), apply `set`, and re-serialize.
    fn set_exif_string(mut self, text: &str, set: impl FnOnce(&mut Exif<'_>, &str)) -> Self {
        let bytes = {
            // `exif` borrows `self.exif` here; `to_bytes` copies values out, so
            // `bytes` is owned and the borrow ends before we reassign below.
            let mut exif = self
                .exif
                .as_deref()
                .and_then(Exif::parse)
                .unwrap_or_default();
            set(&mut exif, text);
            exif.to_bytes()
        };
        self.exif = Some(Arc::from(bytes));
        self
    }

    /// Set the XMP metadata.
    ///
    /// Accepts `Vec<u8>`, `&[u8]`, or `Arc<[u8]>`.
    pub fn with_xmp(mut self, xmp: impl Into<Arc<[u8]>>) -> Self {
        self.xmp = Some(xmp.into());
        self
    }

    /// Set the CICP color description.
    pub fn with_cicp(mut self, cicp: Cicp) -> Self {
        self.cicp = Some(cicp);
        self
    }

    /// Set the Content Light Level Info.
    pub fn with_content_light_level(mut self, clli: ContentLightLevel) -> Self {
        self.content_light_level = Some(clli);
        self
    }

    /// Set the absolute-luminance anchor (the nits of relative-linear `1.0`).
    pub fn with_diffuse_white(mut self, white: DiffuseWhite) -> Self {
        self.diffuse_white = Some(white);
        self
    }

    /// Clear the absolute-luminance anchor — drop back to "unsignalled" so a
    /// downstream re-encoder knows there is no anchor to emit, or so the
    /// converter falls through to its `DiffuseWhite::BT2408` default.
    ///
    /// Needed because `Metadata` is `#[non_exhaustive]`: callers can't reach
    /// in with a struct literal to set the field back to `None`. Pairs with
    /// [`with_diffuse_white`](Self::with_diffuse_white).
    pub fn clear_diffuse_white(mut self) -> Self {
        self.diffuse_white = None;
        self
    }

    /// Set the Mastering Display Color Volume.
    pub fn with_mastering_display(mut self, mdcv: MasteringDisplay) -> Self {
        self.mastering_display = Some(mdcv);
        self
    }

    /// Set the EXIF orientation.
    pub fn with_orientation(mut self, orientation: Orientation) -> Self {
        self.orientation = orientation;
        self
    }

    /// Whether any metadata is present.
    pub fn is_empty(&self) -> bool {
        self.icc_profile.is_none()
            && self.exif.is_none()
            && self.xmp.is_none()
            && self.cicp.is_none()
            && self.content_light_level.is_none()
            && self.mastering_display.is_none()
            && self.orientation == Orientation::Identity
    }

    /// Derive the transfer function from CICP metadata.
    ///
    /// Returns the [`TransferFunction`] corresponding to the CICP
    /// `transfer_characteristics` code, or [`Unknown`](TransferFunction::Unknown)
    /// if CICP is absent or the code is not recognized.
    pub fn transfer_function(&self) -> TransferFunction {
        self.cicp
            .and_then(|c| TransferFunction::from_cicp(c.transfer_characteristics))
            .unwrap_or(TransferFunction::Unknown)
    }

    /// Derive the color primaries from CICP metadata.
    ///
    /// Returns [`Bt709`](ColorPrimaries::Bt709) if CICP is absent.
    pub fn color_primaries(&self) -> ColorPrimaries {
        self.cicp
            .map(|c| c.color_primaries_enum())
            .unwrap_or(ColorPrimaries::Bt709)
    }

    /// Apply a retention [`MetadataPolicy`], returning a filtered copy.
    ///
    /// The shared field-level metadata filter for re-encode / recompress
    /// pipelines: keep what a downstream image needs, strip the rest, without
    /// callers hand-parsing EXIF.
    ///
    /// - **ICC** is three-way ([`IccRetention`]): keep as-is, keep only when
    ///   it isn't a redundant sRGB ([`zenpixels::icc::is_common_srgb`]), or drop.
    /// - **EXIF** is pruned by category via [`ExifPolicy`]. The source blob
    ///   passes through unchanged (zero-copy `Arc` clone) when no category is
    ///   dropped and the embedded orientation already matches the field, and is
    ///   rewritten — offsets recomputed — only when pruning.
    /// - **Orientation** is reconciled: the embedded EXIF orientation tag is
    ///   rewritten to match the authoritative [`orientation`](Metadata::orientation)
    ///   field, so a baked-upright image (field `Identity`, blob still rotated)
    ///   cannot be double-rotated by a consumer that re-applies the tag.
    /// - **CICP** and **HDR** light-level/mastering are color *signaling* (they
    ///   change how pixels display); the presets keep them, a
    ///   [`Custom`](MetadataPolicy::Custom) policy can drop them.
    ///
    /// # HDR signaling and gain maps — keep these consistent with the pixels
    ///
    /// CICP (`transfer_characteristics`, `color_primaries`, `matrix_coefficients`)
    /// and the HDR `ContentLightLevel` / `MasteringDisplay` describe **how the
    /// stored pixels are to be interpreted**. They are not free-floating notes:
    /// a decoder uses CICP transfer (e.g. PQ or HLG) to linearize, and uses
    /// CLLI/MDCV to tone-map for the target display. If they disagree with the
    /// actual pixels, the image renders **wrong** (clipped highlights, wrong
    /// gamut, double tone-mapping).
    ///
    /// A **gain map** is a *separate plane* (not a field of [`Metadata`] — it
    /// lives at the encode-request / codec-output layer with its
    /// [`GainMapInfo`](crate::GainMapInfo)). The base image, its HDR signaling,
    /// and the gain map together reconstruct the HDR rendition. That coupling
    /// is the hazard:
    ///
    /// - **Dropping or flattening the gain map (HDR → SDR) without also fixing
    ///   the signaling leaves invalid metadata.** If you tone-map to an SDR
    ///   base and discard the gain map, but leave `transfer_characteristics =
    ///   PQ/HLG` and an MDCV describing a 1000-nit mastering display, a
    ///   conformant decoder will treat your SDR pixels as HDR and tone-map them
    ///   a second time — visibly wrong. When the gain map goes, the HDR
    ///   signaling that described the HDR rendition must go (or be rewritten to
    ///   match the SDR base: `transfer` → sRGB, drop CLLI/MDCV).
    /// - Conversely, **stripping CICP/HDR while keeping a gain map** orphans the
    ///   gain map (the decoder no longer knows the base is HDR-relative), so the
    ///   HDR rendition is lost or misrendered.
    ///
    /// `filtered` **cannot see the gain map** (it isn't in `Metadata`), so it
    /// cannot enforce this — the consistency is the **caller's responsibility**
    /// at the layer that owns the gain map. Practical guidance:
    ///
    /// - Keeping the gain map untouched → keep CICP/HDR (`Web` / `Preserve`).
    /// - Flattening to SDR and dropping the gain map → drop HDR here (a
    ///   [`Custom`](MetadataPolicy::Custom) policy with `hdr: Discard`, and set
    ///   the encoder's CICP to the SDR transfer) so the signaling matches the
    ///   pixels you actually wrote.
    ///
    /// `cicp` and `hdr` are deliberately *separate* retention flags so this
    /// SDR-flatten case is expressible (drop HDR light-level/mastering while
    /// keeping CICP primaries). The *inverse* — a `Custom` policy that drops
    /// `cicp` but keeps `hdr` — leaves the CLLI/MDCV light-level metadata with no
    /// transfer/primaries to interpret it against (orphaned HDR signaling); it is
    /// not rejected, so a `Custom` policy that drops color signaling should drop
    /// `hdr` too.
    #[must_use]
    pub fn filtered(&self, policy: &MetadataPolicy) -> Metadata {
        let f = policy.fields();
        let mut out = Metadata::none();

        // ICC — three-way; only KeepNonSrgb drops a redundant sRGB profile.
        out.icc_profile = match f.icc {
            IccRetention::Drop => None,
            // Target-blind retention keeps the profile; the CICP-conditional
            // drop is resolved against a concrete target in
            // `color::resolve_color_emit`, which `filtered` does not see.
            IccRetention::Keep
            | IccRetention::DropIfCicpRepresentable
            | IccRetention::DropIfCicpSafeSoleCarrier => self.icc_profile.clone(),
            IccRetention::KeepNonSrgb => self
                .icc_profile
                .as_ref()
                .filter(|icc| !zenpixels::icc::is_common_srgb(icc))
                .cloned(),
        };

        // Orientation field (codecs may apply it without re-reading the EXIF).
        out.orientation = if f.exif.orientation.keeps() {
            self.orientation
        } else {
            Orientation::Identity
        };

        // Color signaling.
        if f.cicp.keeps() {
            out.cicp = self.cicp;
        }
        if f.hdr.keeps() {
            out.content_light_level = self.content_light_level;
            out.mastering_display = self.mastering_display;
        }

        // XMP (whole-segment).
        if f.xmp.keeps() {
            out.xmp = self.xmp.clone();
        }

        // EXIF — pruned by category AND reconciled to the authoritative
        // `out.orientation` field in a *single* parse (see
        // `exif::retain_reconciled`). Reconciliation rewrites the embedded
        // orientation tag to match the field: a decoder that bakes orientation
        // upright sets the field to Identity while the source blob still carries
        // the original tag (e.g. Rotate90); left alone, a consumer re-applying the
        // tag would rotate twice. `Arc` clone (zero-copy) when nothing is pruned
        // and the tag already matches.
        out.exif = self.exif.as_ref().and_then(|src| {
            match crate::exif::retain_reconciled(src, &f.exif, Some(out.orientation))? {
                alloc::borrow::Cow::Borrowed(_) => Some(src.clone()),
                alloc::borrow::Cow::Owned(v) => Some(Arc::from(v)),
            }
        });
        out
    }
}

/// How to treat the ICC profile when filtering [`Metadata`].
///
/// `#[non_exhaustive]`: ICC handling can gain dispositions (e.g. a future
/// convert-to-sRGB or keep-if-display-referred mode) without a breaking
/// change. Match with a `_` arm.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum IccRetention {
    /// Always drop the profile.
    Drop,
    /// Keep the profile unless it is a redundant sRGB profile — the common
    /// choice (sRGB is the assumed default, so embedding it is pure weight).
    KeepNonSrgb,
    /// Keep the profile as-is, even a redundant sRGB one (byte-faithful).
    Keep,
    /// Drop the profile when it maps to a CICP expressible as code points
    /// (sRGB / Display-P3 / BT.2020 / BT.2100…) — i.e. CICP fully describes the
    /// color. **Target-aware**: only takes effect in
    /// [`color::resolve_color_emit`](crate::color::resolve_color_emit), where the
    /// target's CICP carrier is known. In the target-blind [`Metadata::filtered`]
    /// path it conservatively keeps the profile.
    DropIfCicpRepresentable,
    /// Drop the profile only when the target format's CICP is safe as the sole
    /// color carrier ([`EncodeCapabilities::cicp_safe_sole_carrier`](crate::encode::EncodeCapabilities::cicp_safe_sole_carrier)
    /// — JXL today) and CICP represents the color. Like
    /// [`DropIfCicpRepresentable`](Self::DropIfCicpRepresentable), this is
    /// target-aware and keeps the profile in [`Metadata::filtered`].
    DropIfCicpSafeSoleCarrier,
}

/// Per-field metadata retention for [`MetadataPolicy::Custom`].
///
/// EXIF is encapsulated in [`ExifPolicy`] (pruned by category); the remaining
/// fields use [`Retention`] (explicit `Keep`/`Discard`). This type is
/// `#[non_exhaustive]` (new fields can be added without a breaking change), so
/// downstream crates build from [`KEEP_ALL`](Self::KEEP_ALL) /
/// [`DISCARD_ALL`](Self::DISCARD_ALL) via the `with_*` builders rather than
/// struct-update syntax. Drop only GPS, keep all else:
///
/// ```
/// use zencodec::{MetadataFields, exif::{ExifPolicy, Retention}};
/// let fields = MetadataFields::KEEP_ALL
///     .with_exif(ExifPolicy::KEEP_ALL.with_gps(Retention::Discard));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct MetadataFields {
    /// ICC color profile.
    pub icc: IccRetention,
    /// EXIF, pruned by category.
    pub exif: ExifPolicy,
    /// XMP, whole-segment. The XMP packet (RDF/XML) can carry GPS
    /// (`exif:GPS*`), edit history (`photoshop:History`, `xmpMM:History`),
    /// and C2PA provenance (`xmpMM` manifests), so the presets that strip
    /// privacy/bloat ([`Web`](MetadataPolicy::Web)) discard it wholesale while
    /// keeping EXIF rights.
    ///
    /// Partial XMP (e.g. keep `dc:rights`/`dc:creator`, drop GPS + history +
    /// C2PA) is a planned future addition — it needs an RDF/XML parser, so it
    /// is deferred rather than half-done. It will arrive as a *new*
    /// `MetadataFields` field (this struct is `#[non_exhaustive]`, so adding
    /// one is non-breaking); `xmp` will remain the whole-segment master switch.
    pub xmp: Retention,
    /// CICP color signaling.
    pub cicp: Retention,
    /// HDR `ContentLightLevel` + `MasteringDisplay`.
    pub hdr: Retention,
}

impl MetadataFields {
    /// Keep every field (ICC kept as-is, including a redundant sRGB).
    pub const KEEP_ALL: Self = Self {
        icc: IccRetention::Keep,
        exif: ExifPolicy::KEEP_ALL,
        xmp: Retention::Keep,
        cicp: Retention::Keep,
        hdr: Retention::Keep,
    };
    /// Discard every field.
    pub const DISCARD_ALL: Self = Self {
        icc: IccRetention::Drop,
        exif: ExifPolicy::DISCARD_ALL,
        xmp: Retention::Discard,
        cicp: Retention::Discard,
        hdr: Retention::Discard,
    };

    /// Set ICC retention. (Builder — this type is `#[non_exhaustive]`.)
    #[must_use]
    pub const fn with_icc(mut self, r: IccRetention) -> Self {
        self.icc = r;
        self
    }
    /// Set the EXIF retention policy.
    #[must_use]
    pub const fn with_exif(mut self, p: ExifPolicy) -> Self {
        self.exif = p;
        self
    }
    /// Set XMP retention.
    #[must_use]
    pub const fn with_xmp(mut self, r: Retention) -> Self {
        self.xmp = r;
        self
    }
    /// Set CICP retention.
    #[must_use]
    pub const fn with_cicp(mut self, r: Retention) -> Self {
        self.cicp = r;
        self
    }
    /// Set HDR (light-level/mastering) retention.
    #[must_use]
    pub const fn with_hdr(mut self, r: Retention) -> Self {
        self.hdr = r;
        self
    }
}

/// Field-level metadata retention policy applied by [`Metadata::filtered`].
///
/// `Copy` (all variants, including `Custom(MetadataFields)`, are `Copy`) so it
/// can be bundled by value into [`EncodePolicy`](crate::encode::EncodePolicy).
///
/// **No `Default`.** Metadata retention is a privacy decision, so callers must
/// name a policy explicitly — there is no implicit fallback. [`Web`](Self::Web)
/// is the recommended privacy-safe choice for publishing.
///
/// # Delivery exceptions
///
/// Each variant's per-channel promise holds in the common case; these are the
/// edges where it does not, by design:
///
/// - **Unparseable or > 4 GiB EXIF under a *partial* policy ([`Web`](Self::Web),
///   [`ColorAndRotation`](Self::ColorAndRotation), or any [`Custom`](Self::Custom)
///   that drops an EXIF category) → the *whole* EXIF blob is dropped (fail-safe:
///   an unverifiable strip must not leak).** So the "keep EXIF orientation tag +
///   rights" part of those policies is *not* delivered for such a blob. The
///   authoritative [`orientation`](Metadata::orientation) **field** is separate
///   and is always preserved; only EXIF-blob-carried data (rights/copyright,
///   the embedded tag) is lost. [`PreserveExact`](Self::PreserveExact) /
///   [`Preserve`](Self::Preserve) keep EXIF byte-faithfully (no parse, so an
///   unparseable/oversize blob passes through unchanged).
/// - **[`Custom`](Self::Custom) keeping `camera` *through a prune*:** the rewrite
///   relocates `MakerNote` (0x927C) without fixing its maker-specific internal
///   offsets, and an uncompressed (StripOffsets) thumbnail is dropped on any
///   rewrite — see the [`exif`](crate::exif) module limitations. (The presets
///   sidestep this: `Web`/`ColorAndRotation` drop `camera`; `Preserve*` never
///   rewrite.)
/// - **CICP/HDR vs the pixels and any gain map** is the caller's responsibility —
///   `filtered` cannot see the gain map; see [`Metadata::filtered`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum MetadataPolicy {
    /// Keep everything the source carried, byte-faithfully — including a
    /// redundant sRGB ICC profile.
    ///
    /// One exception: if the embedded EXIF orientation tag disagrees with the
    /// authoritative [`orientation`](Metadata::orientation) field (e.g. a decoder
    /// baked the image upright and set the field to `Identity`), the tag is
    /// rewritten in place to match the field — preventing a double-rotation. The
    /// EXIF is otherwise byte-identical; only that 2-byte value changes, and only
    /// on a mismatch.
    PreserveExact,
    /// Keep everything, but drop a redundant sRGB ICC profile.
    Preserve,
    /// The web-publish set (recommended for publishing): keep the ICC profile
    /// (unless a redundant sRGB), EXIF orientation + rights (copyright/artist),
    /// and CICP / HDR color signaling. Drop the rest of EXIF (GPS, timestamps,
    /// camera/device identity, thumbnail) and all XMP.
    Web,
    /// Keep only what places pixels on screen: the ICC profile (unless a
    /// redundant sRGB), CICP / HDR color signaling, and EXIF orientation.
    /// Drops attribution, XMP, and all other EXIF.
    ColorAndRotation,
    /// Explicit per-field control via [`MetadataFields`].
    Custom(MetadataFields),
}

impl MetadataPolicy {
    /// Resolve the policy to its concrete per-field retention set.
    #[must_use]
    pub fn fields(&self) -> MetadataFields {
        match self {
            Self::PreserveExact => MetadataFields::KEEP_ALL,
            Self::Preserve => MetadataFields {
                icc: IccRetention::KeepNonSrgb,
                ..MetadataFields::KEEP_ALL
            },
            Self::Web => MetadataFields {
                icc: IccRetention::KeepNonSrgb,
                exif: ExifPolicy::ATTRIBUTED_ORIENTATION,
                xmp: Retention::Discard,
                cicp: Retention::Keep,
                hdr: Retention::Keep,
            },
            Self::ColorAndRotation => MetadataFields {
                icc: IccRetention::KeepNonSrgb,
                exif: ExifPolicy::ORIENTATION_ONLY,
                xmp: Retention::Discard,
                cicp: Retention::Keep,
                hdr: Retention::Keep,
            },
            Self::Custom(f) => *f,
        }
    }
}

/// Extract a [`Metadata`] from decoded [`ImageInfo`](crate::ImageInfo).
///
/// `info.orientation` is taken as the authoritative orientation **verbatim** — it
/// is *not* re-derived from the embedded EXIF tag. A decoder MUST set
/// `info.orientation` to the intended display orientation (the EXIF tag value if
/// it carries the rotation, or `Identity` if it baked the pixels upright). If a
/// decoder leaves `info.orientation` at the default `Identity` while
/// `embedded_metadata.exif` still carries a non-identity tag, [`filtered`](Metadata::filtered) will
/// reconcile the blob's tag down to `Identity` — silently discarding the rotation.
/// (The [`with_exif`](Metadata::with_exif) builder, by contrast, syncs the field
/// from the tag; `From` trusts the decoder.)
impl From<&crate::ImageInfo> for Metadata {
    fn from(info: &crate::ImageInfo) -> Self {
        Self {
            icc_profile: info.source_color.icc_profile.clone(),
            exif: info.embedded_metadata.exif.clone(),
            xmp: info.embedded_metadata.xmp.clone(),
            cicp: info.source_color.cicp,
            content_light_level: info.source_color.content_light_level,
            mastering_display: info.source_color.mastering_display,
            diffuse_white: info.source_color.diffuse_white,
            orientation: info.orientation,
        }
    }
}

/// Parse the EXIF Orientation tag (0x0112) from a TIFF/EXIF blob.
///
/// Delegates to the canonical implementation in
/// [`helpers::parse_exif_orientation`](crate::helpers::parse_exif_orientation),
/// which performs full bounds-checking, supports both `SHORT` and `LONG`
/// TIFF types, validates the TIFF magic, and caps IFD entry count to
/// prevent DoS from malformed data.
///
/// Handles both little-endian (`II*\0`) and big-endian (`MM\0*`) byte
/// orders. Returns `None` if the blob is malformed or no Orientation
/// tag exists.
fn parse_exif_orientation(blob: &[u8]) -> Option<Orientation> {
    crate::helpers::parse_exif_orientation(blob)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ImageFormat;

    #[test]
    fn metadata_roundtrip() {
        let info = crate::ImageInfo::new(100, 200, ImageFormat::Jpeg)
            .with_icc_profile(alloc::vec![1, 2, 3])
            .with_exif(alloc::vec![4, 5])
            .with_cicp(Cicp::SRGB)
            .with_content_light_level(ContentLightLevel {
                max_content_light_level: 1000,
                max_frame_average_light_level: 400,
            });
        let meta = info.metadata();
        assert_eq!(meta.icc_profile.as_deref(), Some([1, 2, 3].as_slice()));
        assert_eq!(meta.exif.as_deref(), Some([4, 5].as_slice()));
        assert!(meta.xmp.is_none());
        assert_eq!(meta.cicp, Some(Cicp::SRGB));
        assert_eq!(
            meta.content_light_level.unwrap().max_content_light_level,
            1000
        );
        assert!(meta.mastering_display.is_none());
        assert!(!meta.is_empty());
    }

    #[test]
    fn metadata_empty() {
        let meta = Metadata::none();
        assert!(meta.is_empty());
    }

    #[test]
    fn metadata_with_cicp_not_empty() {
        let meta = Metadata::none().with_cicp(Cicp::SRGB);
        assert!(!meta.is_empty());
    }

    #[test]
    fn metadata_with_hdr_not_empty() {
        let meta = Metadata::none().with_content_light_level(ContentLightLevel {
            max_content_light_level: 1000,
            max_frame_average_light_level: 400,
        });
        assert!(!meta.is_empty());
    }

    #[test]
    fn metadata_orientation_roundtrip() {
        let info = crate::ImageInfo::new(100, 200, ImageFormat::Jpeg)
            .with_orientation(Orientation::Rotate90);
        let meta = info.metadata();
        assert_eq!(meta.orientation, Orientation::Rotate90);
    }

    #[test]
    fn metadata_orientation_default_is_normal() {
        let meta = Metadata::none();
        assert_eq!(meta.orientation, Orientation::Identity);
    }

    #[test]
    fn metadata_with_orientation_builder() {
        let meta = Metadata::none().with_orientation(Orientation::Rotate270);
        assert_eq!(meta.orientation, Orientation::Rotate270);
    }

    #[test]
    fn metadata_orientation_not_empty() {
        let meta = Metadata::none().with_orientation(Orientation::Rotate90);
        assert!(!meta.is_empty());
    }

    #[test]
    fn metadata_identity_orientation_is_empty() {
        let meta = Metadata::none().with_orientation(Orientation::Identity);
        assert!(meta.is_empty());
    }

    #[test]
    fn metadata_transfer_function() {
        let meta = Metadata::none().with_cicp(Cicp::SRGB);
        assert_eq!(meta.transfer_function(), TransferFunction::Srgb);

        let meta = Metadata::none();
        assert_eq!(meta.transfer_function(), TransferFunction::Unknown);
    }

    #[test]
    fn metadata_builder() {
        let meta = Metadata::none()
            .with_icc(alloc::vec![1, 2, 3])
            .with_exif(alloc::vec![4, 5])
            .with_cicp(Cicp::SRGB)
            .with_orientation(Orientation::Rotate90);
        assert!(!meta.is_empty());
        assert_eq!(meta.icc_profile.as_deref(), Some([1, 2, 3].as_slice()));
        assert_eq!(meta.exif.as_deref(), Some([4, 5].as_slice()));
        assert!(meta.xmp.is_none());
        assert_eq!(meta.cicp, Some(Cicp::SRGB));
        assert_eq!(meta.orientation, Orientation::Rotate90);
    }

    #[test]
    fn metadata_from_image_info() {
        let info = crate::ImageInfo::new(100, 200, ImageFormat::Jpeg)
            .with_icc_profile(alloc::vec![10, 20, 30])
            .with_exif(alloc::vec![4, 5])
            .with_cicp(Cicp::SRGB)
            .with_orientation(Orientation::Rotate270);
        let meta = Metadata::from(&info);
        assert_eq!(meta.icc_profile.as_deref(), Some([10, 20, 30].as_slice()));
        assert_eq!(meta.exif.as_deref(), Some([4, 5].as_slice()));
        assert_eq!(meta.cicp, Some(Cicp::SRGB));
        assert_eq!(meta.orientation, Orientation::Rotate270);
    }

    fn build_minimal_exif_with_orientation(value: u16, big_endian: bool) -> alloc::vec::Vec<u8> {
        let mut v = alloc::vec::Vec::new();
        if big_endian {
            v.extend_from_slice(b"MM\x00\x2a");
            v.extend_from_slice(&8u32.to_be_bytes());
            v.extend_from_slice(&1u16.to_be_bytes());
            v.extend_from_slice(&0x0112u16.to_be_bytes());
            v.extend_from_slice(&3u16.to_be_bytes());
            v.extend_from_slice(&1u32.to_be_bytes());
            // SHORT value is padded right within 4-byte value field; for BE
            // the value sits in the FIRST 2 bytes.
            v.extend_from_slice(&value.to_be_bytes());
            v.extend_from_slice(&[0u8, 0]);
            v.extend_from_slice(&0u32.to_be_bytes());
        } else {
            v.extend_from_slice(b"II\x2a\x00");
            v.extend_from_slice(&8u32.to_le_bytes());
            v.extend_from_slice(&1u16.to_le_bytes());
            v.extend_from_slice(&0x0112u16.to_le_bytes());
            v.extend_from_slice(&3u16.to_le_bytes());
            v.extend_from_slice(&1u32.to_le_bytes());
            v.extend_from_slice(&(value as u32).to_le_bytes());
            v.extend_from_slice(&0u32.to_le_bytes());
        }
        v
    }

    #[test]
    fn parse_exif_orientation_le_returns_correct_variant() {
        let blob = build_minimal_exif_with_orientation(6, false);
        assert_eq!(parse_exif_orientation(&blob), Some(Orientation::Rotate90));
    }

    #[test]
    fn parse_exif_orientation_be_returns_correct_variant() {
        let blob = build_minimal_exif_with_orientation(6, true);
        assert_eq!(parse_exif_orientation(&blob), Some(Orientation::Rotate90));
    }

    #[test]
    fn parse_exif_orientation_garbage_returns_none() {
        assert_eq!(parse_exif_orientation(b"garbage"), None);
        assert_eq!(parse_exif_orientation(&[]), None);
        assert_eq!(parse_exif_orientation(&[0u8; 7]), None);
    }

    #[test]
    fn with_exif_auto_parses_orientation_from_blob() {
        let blob = build_minimal_exif_with_orientation(8, false);
        let meta = Metadata::none().with_exif(blob);
        assert_eq!(meta.orientation, Orientation::Rotate270);
    }

    /// Build TIFF with the orientation tag stored as TIFF_LONG (type 4)
    /// instead of SHORT (type 3). The previous loose parser in this file
    /// only read u16 at +8 regardless of type, so for big-endian LONG it
    /// would read the high zero bytes and miss the value. The delegated
    /// helper handles both types correctly.
    fn build_exif_with_long_orientation(value: u32, big_endian: bool) -> alloc::vec::Vec<u8> {
        let mut v = alloc::vec::Vec::new();
        if big_endian {
            v.extend_from_slice(b"MM\x00\x2a");
            v.extend_from_slice(&8u32.to_be_bytes());
            v.extend_from_slice(&1u16.to_be_bytes());
            v.extend_from_slice(&0x0112u16.to_be_bytes());
            v.extend_from_slice(&4u16.to_be_bytes()); // type = LONG
            v.extend_from_slice(&1u32.to_be_bytes());
            v.extend_from_slice(&value.to_be_bytes());
        } else {
            v.extend_from_slice(b"II\x2a\x00");
            v.extend_from_slice(&8u32.to_le_bytes());
            v.extend_from_slice(&1u16.to_le_bytes());
            v.extend_from_slice(&0x0112u16.to_le_bytes());
            v.extend_from_slice(&4u16.to_le_bytes()); // type = LONG
            v.extend_from_slice(&1u32.to_le_bytes());
            v.extend_from_slice(&value.to_le_bytes());
        }
        v
    }

    #[test]
    fn parse_exif_orientation_accepts_long_type_be() {
        let blob = build_exif_with_long_orientation(6, true);
        assert_eq!(parse_exif_orientation(&blob), Some(Orientation::Rotate90));
    }

    #[test]
    fn parse_exif_orientation_accepts_long_type_le() {
        let blob = build_exif_with_long_orientation(8, false);
        assert_eq!(parse_exif_orientation(&blob), Some(Orientation::Rotate270));
    }

    #[test]
    fn with_exif_does_not_override_explicit_orientation() {
        let blob = build_minimal_exif_with_orientation(6, false);
        let meta = Metadata::none()
            .with_orientation(Orientation::FlipH)
            .with_exif(blob);
        // Explicit FlipH must win over the EXIF blob's Rotate90.
        assert_eq!(meta.orientation, Orientation::FlipH);
    }

    // ── MetadataPolicy / filtered ──────────────────────────────────────────

    use crate::exif::Exif;

    /// LE TIFF source: Make (0x010F, camera) + Orientation (0x0112) + Copyright
    /// (0x8298, out-of-line), tag-sorted. `prefix` adds `Exif\0\0` framing.
    fn src_exif(orientation: u16, copyright: &str, prefix: bool) -> alloc::vec::Vec<u8> {
        use alloc::vec::Vec;
        let mut cw = copyright.as_bytes().to_vec();
        cw.push(0); // > 4 bytes → out-of-line
        let n: u16 = 3;
        let ifd_size = 2 + 12 * n as usize + 4;
        let ext_off = 8 + ifd_size;

        let mut t = Vec::new();
        t.extend_from_slice(b"II");
        t.extend_from_slice(&42u16.to_le_bytes());
        t.extend_from_slice(&8u32.to_le_bytes());
        t.extend_from_slice(&n.to_le_bytes());
        // Make 0x010F ASCII "Cam\0" (4 bytes, inline) — camera category.
        t.extend_from_slice(&0x010Fu16.to_le_bytes());
        t.extend_from_slice(&2u16.to_le_bytes());
        t.extend_from_slice(&4u32.to_le_bytes());
        t.extend_from_slice(b"Cam\0");
        // Orientation 0x0112 SHORT (inline).
        t.extend_from_slice(&0x0112u16.to_le_bytes());
        t.extend_from_slice(&3u16.to_le_bytes());
        t.extend_from_slice(&1u32.to_le_bytes());
        t.extend_from_slice(&u32::from(orientation).to_le_bytes());
        // Copyright 0x8298 ASCII (out-of-line).
        t.extend_from_slice(&0x8298u16.to_le_bytes());
        t.extend_from_slice(&2u16.to_le_bytes());
        t.extend_from_slice(&(cw.len() as u32).to_le_bytes());
        t.extend_from_slice(&(ext_off as u32).to_le_bytes());
        t.extend_from_slice(&0u32.to_le_bytes()); // next-IFD offset
        t.extend_from_slice(&cw);

        if prefix {
            let mut out = Vec::with_capacity(6 + t.len());
            out.extend_from_slice(b"Exif\0\0");
            out.extend_from_slice(&t);
            out
        } else {
            t
        }
    }

    /// True if the (little-endian) tag appears in the blob's entry stream.
    fn has_tag(blob: &[u8], tag: u16) -> bool {
        blob.windows(2).any(|w| w == tag.to_le_bytes())
    }

    #[test]
    fn policy_fields_resolution() {
        assert_eq!(
            MetadataPolicy::PreserveExact.fields(),
            MetadataFields::KEEP_ALL
        );
        assert_eq!(
            MetadataPolicy::PreserveExact.fields().icc,
            IccRetention::Keep
        );
        assert_eq!(
            MetadataPolicy::Preserve.fields().icc,
            IccRetention::KeepNonSrgb
        );
        assert_eq!(MetadataPolicy::Preserve.fields().exif, ExifPolicy::KEEP_ALL);

        let web = MetadataPolicy::Web.fields();
        assert_eq!(web.icc, IccRetention::KeepNonSrgb);
        assert_eq!(web.exif, ExifPolicy::ATTRIBUTED_ORIENTATION);
        assert_eq!(web.xmp, Retention::Discard);
        assert_eq!(web.cicp, Retention::Keep);
        assert_eq!(web.hdr, Retention::Keep);

        let car = MetadataPolicy::ColorAndRotation.fields();
        assert_eq!(car.exif, ExifPolicy::ORIENTATION_ONLY);
        assert_eq!(car.cicp, Retention::Keep);

        let custom = MetadataFields {
            xmp: Retention::Keep,
            ..MetadataFields::DISCARD_ALL
        };
        assert_eq!(MetadataPolicy::Custom(custom).fields(), custom);
    }

    #[test]
    fn icc_three_way_retention() {
        let icc = alloc::vec![0xABu8; 256]; // arbitrary → not recognized as sRGB
        let meta = Metadata::none().with_icc(icc.clone());
        // KeepNonSrgb keeps a non-sRGB profile (Web/Preserve).
        assert_eq!(
            meta.filtered(&MetadataPolicy::Web).icc_profile.as_deref(),
            Some(icc.as_slice())
        );
        // Keep keeps it too (PreserveExact).
        assert_eq!(
            meta.filtered(&MetadataPolicy::PreserveExact)
                .icc_profile
                .as_deref(),
            Some(icc.as_slice())
        );
        // Drop removes it.
        let drop = MetadataFields {
            icc: IccRetention::Drop,
            ..MetadataFields::KEEP_ALL
        };
        assert!(
            meta.filtered(&MetadataPolicy::Custom(drop))
                .icc_profile
                .is_none()
        );
    }

    #[test]
    fn web_keeps_orientation_rights_drops_camera_and_xmp() {
        let src = src_exif(6, "(c) 2026 Lilith", false);
        let meta = Metadata::none()
            .with_exif(src.clone())
            .with_xmp(alloc::vec![1, 2, 3])
            .with_cicp(Cicp::SRGB)
            .with_content_light_level(ContentLightLevel {
                max_content_light_level: 1000,
                max_frame_average_light_level: 400,
            });
        assert_eq!(meta.orientation, Orientation::Rotate90);

        let out = meta.filtered(&MetadataPolicy::Web);
        let e = out.exif.as_deref().expect("rewritten EXIF");
        let ex = Exif::parse(e).expect("parses");
        assert_eq!(ex.orientation(), Some(Orientation::Rotate90));
        assert_eq!(ex.copyright().unwrap(), "(c) 2026 Lilith");
        // Camera (Make 0x010F) dropped; output is smaller than the source.
        assert!(!has_tag(e, 0x010F));
        assert!(e.len() < src.len());
        assert_eq!(out.orientation, Orientation::Rotate90);
        assert!(out.xmp.is_none());
        assert_eq!(out.cicp, Some(Cicp::SRGB));
        assert!(out.content_light_level.is_some());
    }

    #[test]
    fn preserve_exact_passes_exif_through_byte_identical() {
        let src = src_exif(6, "(c) Owner", false);
        let meta = Metadata::none()
            .with_exif(src.clone())
            .with_xmp(alloc::vec![9, 9])
            .with_icc(alloc::vec![0xABu8; 200]);
        let out = meta.filtered(&MetadataPolicy::PreserveExact);
        assert_eq!(out.exif.as_deref(), Some(src.as_slice()));
        assert!(has_tag(out.exif.as_deref().unwrap(), 0x010F)); // camera kept
        assert_eq!(out.xmp.as_deref(), Some([9, 9].as_slice()));
        assert!(out.icc_profile.is_some());
    }

    #[test]
    fn color_and_rotation_keeps_orientation_drops_rights() {
        let src = src_exif(8, "(c) Owner", false);
        let meta = Metadata::none().with_exif(src).with_cicp(Cicp::SRGB);
        let out = meta.filtered(&MetadataPolicy::ColorAndRotation);
        let e = out.exif.as_deref().expect("EXIF");
        let ex = Exif::parse(e).expect("parses");
        assert_eq!(ex.orientation(), Some(Orientation::Rotate270));
        assert!(ex.copyright().is_none()); // rights dropped
        assert!(!has_tag(e, 0x010F)); // camera dropped
        assert_eq!(out.cicp, Some(Cicp::SRGB));
    }

    // ── with_copyright / with_artist sugar (build/merge an EXIF blob) ─────────

    #[test]
    fn with_copyright_creates_blob_from_nothing() {
        let meta = Metadata::none().with_copyright("(c) 2026 Lilith");
        let e = meta.exif.as_deref().expect("EXIF created");
        assert_eq!(
            Exif::parse(e).unwrap().copyright().unwrap(),
            "(c) 2026 Lilith"
        );
    }

    #[test]
    fn with_copyright_merges_into_existing() {
        // src carries Make (camera), Orientation=6 (Rotate90), Copyright "old".
        let src = src_exif(6, "old", false);
        let meta = Metadata::none()
            .with_exif(src)
            .with_copyright("(c) New Owner");
        let e = meta.exif.as_deref().expect("EXIF");
        let x = Exif::parse(e).unwrap();
        assert_eq!(x.copyright().unwrap(), "(c) New Owner"); // replaced
        assert_eq!(x.orientation(), Some(Orientation::Rotate90)); // preserved
        assert!(has_tag(e, 0x010F), "Make preserved on merge");
        assert_eq!(meta.orientation, Orientation::Rotate90); // with_exif synced it
    }

    #[test]
    fn with_artist_creates_blob() {
        let meta = Metadata::none().with_artist("Lilith");
        let e = meta.exif.as_deref().expect("EXIF");
        assert_eq!(Exif::parse(e).unwrap().artist().unwrap(), "Lilith");
    }

    #[test]
    fn filtered_reconciles_baked_orientation_tag() {
        // Simulate a decoder that baked orientation upright: the structured field
        // is Identity, but the source EXIF blob still carries Rotate90 (6).
        let blob = src_exif(6, "(c) Owner", false);
        let meta = Metadata::none()
            .with_exif(blob) // parses 6 → field = Rotate90
            .with_orientation(Orientation::Identity); // baked: field reset to Identity
        assert_eq!(meta.orientation, Orientation::Identity);
        // The unfiltered blob still says Rotate90 — the divergence.
        assert_eq!(
            parse_exif_orientation(meta.exif.as_deref().unwrap()),
            Some(Orientation::Rotate90)
        );

        // filtered() rewrites the embedded tag to match the authoritative field,
        // so the emitted metadata is self-consistent (no double-rotation).
        let out = meta.filtered(&MetadataPolicy::PreserveExact);
        assert_eq!(out.orientation, Orientation::Identity);
        assert_eq!(
            parse_exif_orientation(out.exif.as_deref().unwrap()),
            Some(Orientation::Identity),
            "baked-upright blob must be rewritten to Identity, not left at Rotate90"
        );
    }

    #[test]
    fn custom_drop_only_camera_keeps_rest() {
        let src = src_exif(6, "(c) Owner", false);
        let fields = MetadataFields {
            exif: ExifPolicy {
                camera: Retention::Discard,
                ..ExifPolicy::KEEP_ALL
            },
            ..MetadataFields::KEEP_ALL
        };
        let out = Metadata::none()
            .with_exif(src)
            .filtered(&MetadataPolicy::Custom(fields));
        let e = out.exif.as_deref().expect("EXIF");
        let ex = Exif::parse(e).expect("parses");
        assert_eq!(ex.orientation(), Some(Orientation::Rotate90));
        assert_eq!(ex.copyright().unwrap(), "(c) Owner");
        assert!(!has_tag(e, 0x010F)); // only camera dropped
    }

    #[test]
    fn dropping_orientation_resets_field_to_identity() {
        let meta = Metadata::none().with_orientation(Orientation::Rotate90);
        let fields = MetadataFields {
            exif: ExifPolicy {
                orientation: Retention::Discard,
                ..ExifPolicy::KEEP_ALL
            },
            ..MetadataFields::KEEP_ALL
        };
        let out = meta.filtered(&MetadataPolicy::Custom(fields));
        assert_eq!(out.orientation, Orientation::Identity);
    }

    #[test]
    fn exif_prefix_preserved_through_rewrite() {
        let src = src_exif(6, "(c) Owner", true); // Exif\0\0 prefix
        let out = Metadata::none()
            .with_exif(src)
            .filtered(&MetadataPolicy::Web);
        let e = out.exif.as_deref().expect("EXIF");
        assert_eq!(&e[..6], b"Exif\0\0");
        let ex = Exif::parse(e).expect("parses");
        assert_eq!(ex.orientation(), Some(Orientation::Rotate90));
        assert_eq!(ex.copyright().unwrap(), "(c) Owner");
    }

    #[test]
    fn filtered_empty_metadata_is_empty() {
        for p in [
            MetadataPolicy::PreserveExact,
            MetadataPolicy::Preserve,
            MetadataPolicy::Web,
            MetadataPolicy::ColorAndRotation,
        ] {
            assert!(Metadata::none().filtered(&p).is_empty());
        }
    }
}