Skip to main content

zenpixels_convert/
output.rs

1//! Atomic encode-ready output planning: converted pixels + matching CICP / ICC metadata.
2//!
3//! [`OutputPlan`] bundles pixel conversion with container color signaling so an
4//! encoder can never accidentally write sRGB pixels alongside a stale Display P3
5//! ICC profile. On identity (`src == dst`), [`OutputPlan::execute_buf`] reuses
6//! the caller's [`PixelBuf`] **zero-copy**!
7
8use alloc::borrow::Cow;
9use alloc::sync::Arc;
10use how_far::Pulse;
11use whereat::At;
12use zenpixels::{
13    Cicp, ColorOrigin, ColorSpace, HdrMetadata, HlgMode, PeakSource, PixelBuf, PixelCow,
14    PixelFormat, PixelView, Primaries, Transfer,
15};
16
17use crate::error::{ConvertError, err_at};
18use crate::icc_profiles::SynthesizedIcc;
19use crate::plan::{ImagePlan, same_color_meaning, same_photometry};
20use crate::policy::ConvertPolicy;
21use crate::pulse::{check_pulse, live_pulse};
22
23/// Requested container color signaling for an encoder (CICP / ICC metadata emission).
24///
25/// Selects **container signaling metadata**, not the target pixel color space (which is
26/// determined by the destination [`PixelFormat`]).
27///
28/// | Mode | CICP emitted | ICC emitted | Behavior on non-CICP / display-HLG / mismatch |
29/// |---|---|---|---|
30/// | `Auto` (default) | Standardized RGB CICP when available | Companion ICC on non-sRGB full-range RGB when available; ICC-only for Adobe RGB, non-sRGB Gray, `ColorSpace::Icc`, `Cmyk(Some)`; `(None, None)` for sRGB Gray and untagged CMYK | Refuses `HlgMode::Display` (no standard CICP/ICC) |
31/// | `PreserveOrigin` | Origin CICP if compatible | Origin ICC if compatible | Errors if destination color semantics differ from origin |
32/// | `CicpOnly` | Explicit CICP | `None` | Errors if destination has no standard CICP (e.g. Adobe RGB, Gray, custom ICC, display-HLG) |
33/// | `IccOnly` | `None` | Synthesized / bundled / embedded ICC | Errors if no ICC profile is available (e.g. default sRGB without explicit ICC, narrow range, HLG, XYZ) |
34/// | `CicpAndIcc` | Explicit CICP | Synthesized / bundled ICC | Errors unless **both** standard CICP and a matching ICC profile are available |
35/// | `ExplicitIcc(bytes)` | `None` | Exact caller bytes | Validates ICC structure and destination color/transform compatibility |
36/// | `Strip` | `None` | `None` | Emits no tags without modifying pixels |
37#[derive(Clone, Debug, Default, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum OutputSignaling {
40    /// Automatic container signaling: emits CICP for standardized RGB (plus a companion ICC
41    /// on non-sRGB full-range RGB when available), ICC-only for Adobe RGB / non-sRGB Gray /
42    /// active `ColorSpace::Icc` / `ColorSpace::Cmyk(Some)`, and `(None, None)` for full-range
43    /// sRGB Gray and untagged CMYK.
44    #[default]
45    Auto,
46    /// Preserve the original file's [`ColorOrigin`] signaling when compatible with `dst`.
47    PreserveOrigin,
48    /// Emit explicit CICP codes only (`cicp = Some`, `icc = None`).
49    CicpOnly,
50    /// Emit an ICC profile only (`cicp = None`, `icc = Some`).
51    IccOnly,
52    /// Require and emit both explicit CICP codes and a matching ICC profile (`cicp = Some`, `icc = Some`).
53    CicpAndIcc,
54    /// Embed an explicit caller-provided ICC profile (`cicp = None`, `icc = Some`) after
55    /// verifying destination compatibility.
56    ExplicitIcc(Arc<[u8]>),
57    /// Strip color metadata (`cicp = None`, `icc = None`; does not alter pixel values).
58    Strip,
59}
60
61/// Validated container color signaling (`cicp` and/or `icc`) resolved for a destination format
62/// and [`OutputSignaling`] mode.
63#[derive(Clone, Debug, Default, PartialEq, Eq)]
64pub struct ResolvedSignaling {
65    cicp: Option<Cicp>,
66    icc: Option<Cow<'static, [u8]>>,
67}
68
69impl ResolvedSignaling {
70    /// CICP signaling for the output pixels, if present.
71    #[must_use]
72    pub const fn cicp(&self) -> Option<Cicp> {
73        self.cicp
74    }
75
76    /// ICC signaling for the output pixels, if present.
77    #[must_use]
78    pub fn icc(&self) -> Option<&[u8]> {
79        self.icc.as_deref()
80    }
81
82    /// Take the CICP and ICC values without copying the profile bytes.
83    #[must_use]
84    pub fn into_parts(self) -> (Option<Cicp>, Option<Cow<'static, [u8]>>) {
85        (self.cicp, self.icc)
86    }
87}
88
89/// Encoder-ready pixels and their matching CICP, ICC, and HDR metadata.
90#[derive(Clone, Debug)]
91pub struct EncodeReady<'a> {
92    pixels: PixelCow<'a>,
93    signaling: ResolvedSignaling,
94    hdr: HdrMetadata,
95}
96
97impl<'a> EncodeReady<'a> {
98    /// Pixels ready for encoding. Identity plans can borrow them or reuse owned storage.
99    #[must_use]
100    pub const fn pixels(&self) -> &PixelCow<'a> {
101        &self.pixels
102    }
103
104    /// CICP signaling for these pixels, if present.
105    #[must_use]
106    pub const fn cicp(&self) -> Option<Cicp> {
107        self.signaling.cicp()
108    }
109
110    /// ICC signaling for these pixels, if present.
111    #[must_use]
112    pub fn icc(&self) -> Option<&[u8]> {
113        self.signaling.icc()
114    }
115
116    /// Container HDR metadata for these pixels. SDR output clears it.
117    #[must_use]
118    pub const fn hdr(&self) -> HdrMetadata {
119        self.hdr
120    }
121
122    /// Take the pixels and their matching signaling and HDR metadata without copying.
123    #[must_use]
124    pub fn into_parts(self) -> (PixelCow<'a>, ResolvedSignaling, HdrMetadata) {
125        (self.pixels, self.signaling, self.hdr)
126    }
127}
128
129/// Atomic encoder preparation plan combining [`ImagePlan`] with [`OutputSignaling`].
130#[derive(Clone, Debug)]
131pub struct OutputPlan {
132    src: PixelFormat,
133    dst: PixelFormat,
134    signaling: OutputSignaling,
135    image_plan: ImagePlan,
136    same_spec: bool,
137    src_opaque_slot: bool,
138    policy_all_opaque: bool,
139    is_identity: bool,
140}
141
142impl OutputPlan {
143    /// Build an encode-ready output plan.
144    ///
145    /// Accepts either borrowed `&PixelFormat` or owned `PixelFormat` at the call site and borrows
146    /// `&ConvertPolicy` (retaining internal clones inside the built plan).
147    ///
148    /// Validates pixel conversion feasibility AND container signaling compatibility
149    /// upfront (for non-origin-dependent signaling modes) so invalid output configurations
150    /// fail before processing any pixels. Note that signaling rules inspect the
151    /// **destination** spec (`dst`) — for example, `OutputSignaling::CicpOnly` and
152    /// `OutputSignaling::Auto` refuse `Transfer::Hlg(HlgMode::Display(_))` when `dst`
153    /// targets display-referred HLG (converting *from* display HLG to sRGB or PQ
154    /// succeeds because the output signaling is sRGB or PQ).
155    #[inline]
156    pub fn build(
157        src: impl AsRef<PixelFormat>,
158        dst: impl AsRef<PixelFormat>,
159        policy: &ConvertPolicy,
160        peak: PeakSource,
161        signaling: OutputSignaling,
162    ) -> Result<Self, At<ConvertError>> {
163        Self::build_inner(src.as_ref(), dst.as_ref(), policy, peak, signaling, None)
164    }
165
166    /// Build an encode-ready output plan with optional cooperative cancellation and progress
167    /// via `pulse` (forwarded to any configured [`CmsBackend`](crate::CmsBackend) or
168    /// [`ToneMapper`](crate::ToneMapper); pass `None` when not needed).
169    #[inline]
170    pub fn build_with_pulse(
171        src: impl AsRef<PixelFormat>,
172        dst: impl AsRef<PixelFormat>,
173        policy: &ConvertPolicy,
174        peak: PeakSource,
175        signaling: OutputSignaling,
176        pulse: Option<&dyn Pulse>,
177    ) -> Result<Self, At<ConvertError>> {
178        Self::build_inner(src.as_ref(), dst.as_ref(), policy, peak, signaling, pulse)
179    }
180
181    #[inline(never)]
182    fn build_inner(
183        src: &PixelFormat,
184        dst: &PixelFormat,
185        policy: &ConvertPolicy,
186        peak: PeakSource,
187        signaling: OutputSignaling,
188        pulse: Option<&dyn Pulse>,
189    ) -> Result<Self, At<ConvertError>> {
190        let same_spec = src == dst;
191        let src_opaque_slot = src.color().alpha() == zenpixels::AlphaMode::Opaque
192            && src.layout().order().has_alpha_slot();
193        let policy_all_opaque = policy.source_claims.all_opaque;
194        let is_identity = same_spec && (!src_opaque_slot || policy_all_opaque);
195        let image_plan = ImagePlan::build_with_pulse(src, dst, policy, peak, pulse)?;
196        // Eagerly validate signaling rules that don't depend on runtime `ColorOrigin`.
197        match &signaling {
198            OutputSignaling::PreserveOrigin => {
199                if !same_color_meaning(src.color(), dst.color()) {
200                    return Err(err_at(ConvertError::OutputSignalingMismatch));
201                }
202            }
203            _ => {
204                let _ = resolve_output_signaling(
205                    src.color(),
206                    dst.color(),
207                    &signaling,
208                    &ColorOrigin::assumed(),
209                )?;
210            }
211        }
212        Ok(Self {
213            src: src.clone(),
214            dst: dst.clone(),
215            signaling,
216            image_plan,
217            same_spec,
218            src_opaque_slot,
219            policy_all_opaque,
220            is_identity,
221        })
222    }
223
224    /// Whether pixel bytes require no conversion under the plan's policy (`src == dst`,
225    /// excluding unverified `AlphaMode::Opaque` buffers that need alpha canonicalization).
226    ///
227    /// Note: even when `is_identity()` is `false` due to an unverified `Opaque` alpha slot,
228    /// [`execute_view`](Self::execute_view) and [`execute_buf`](Self::execute_buf) still take
229    /// the zero-copy path when the runtime input carries `facts().all_opaque == true`.
230    #[inline]
231    #[must_use]
232    pub const fn is_identity(&self) -> bool {
233        self.is_identity
234    }
235
236    /// Execute on a borrowed [`PixelView<'a>`], returning zero-copy [`PixelCow::Borrowed`] on identity.
237    pub fn execute_view<'a>(
238        &self,
239        view: PixelView<'a>,
240        origin: &ColorOrigin,
241    ) -> Result<EncodeReady<'a>, At<ConvertError>> {
242        self.execute_view_with_pulse(view, origin, None)
243    }
244
245    /// Execute on a borrowed [`PixelView<'a>`] with optional cooperative cancellation and
246    /// progress via `pulse` (pass `None` when not needed).
247    pub fn execute_view_with_pulse<'a>(
248        &self,
249        view: PixelView<'a>,
250        origin: &ColorOrigin,
251        pulse: Option<&dyn Pulse>,
252    ) -> Result<EncodeReady<'a>, At<ConvertError>> {
253        let pulse = live_pulse(pulse);
254        check_pulse(pulse)?;
255        if view.format() != &self.src {
256            return Err(err_at(ConvertError::UnsupportedRoute));
257        }
258        let signaling =
259            resolve_output_signaling(self.src.color(), self.dst.color(), &self.signaling, origin)?;
260        let hdr = if self.dst.can_represent_hdr()
261            && same_photometry(self.src.color(), self.dst.color())
262        {
263            view.hdr()
264        } else {
265            HdrMetadata::default()
266        };
267        let runtime_opaque = self.policy_all_opaque || view.attached_claims().all_opaque;
268        if self.same_spec && (!self.src_opaque_slot || runtime_opaque) {
269            return Ok(EncodeReady {
270                pixels: PixelCow::Borrowed(view),
271                signaling,
272                hdr,
273            });
274        }
275        let converted = self.image_plan.execute_with_pulse(&view, pulse)?;
276        Ok(EncodeReady {
277            pixels: PixelCow::Owned(converted),
278            signaling,
279            hdr,
280        })
281    }
282
283    /// Execute on an owned [`PixelBuf`], moving `buf` **zero-copy** on identity!
284    pub fn execute_buf(&self, buf: PixelBuf) -> Result<EncodeReady<'static>, At<ConvertError>> {
285        self.execute_buf_with_pulse(buf, None)
286    }
287
288    /// Execute on an owned [`PixelBuf`] with optional cooperative cancellation and progress via
289    /// `pulse` (pass `None` when not needed).
290    pub fn execute_buf_with_pulse(
291        &self,
292        buf: PixelBuf,
293        pulse: Option<&dyn Pulse>,
294    ) -> Result<EncodeReady<'static>, At<ConvertError>> {
295        let pulse = live_pulse(pulse);
296        check_pulse(pulse)?;
297        if buf.format() != &self.src {
298            return Err(err_at(ConvertError::UnsupportedRoute));
299        }
300        let signaling = resolve_output_signaling(
301            self.src.color(),
302            self.dst.color(),
303            &self.signaling,
304            buf.origin(),
305        )?;
306        let hdr = if self.dst.can_represent_hdr()
307            && same_photometry(self.src.color(), self.dst.color())
308        {
309            buf.hdr()
310        } else {
311            HdrMetadata::default()
312        };
313        let runtime_opaque = self.policy_all_opaque || buf.attached_claims().all_opaque;
314        if self.same_spec && (!self.src_opaque_slot || runtime_opaque) {
315            return Ok(EncodeReady {
316                pixels: PixelCow::Owned(buf),
317                signaling,
318                hdr,
319            });
320        }
321        let converted = self.image_plan.execute_with_pulse(&buf, pulse)?;
322        Ok(EncodeReady {
323            pixels: PixelCow::Owned(converted),
324            signaling,
325            hdr,
326        })
327    }
328
329    /// Source spec.
330    #[inline]
331    #[must_use]
332    pub fn source_format(&self) -> &PixelFormat {
333        &self.src
334    }
335
336    /// Destination spec.
337    #[inline]
338    #[must_use]
339    pub fn destination_format(&self) -> &PixelFormat {
340        &self.dst
341    }
342
343    /// Resolve and validate container color signaling (`cicp` and `icc`) upfront before
344    /// streaming rows into an encoder (avoids materializing a full `EncodeReady` buffer).
345    pub fn resolve_signaling(
346        &self,
347        origin: &ColorOrigin,
348    ) -> Result<ResolvedSignaling, At<ConvertError>> {
349        resolve_output_signaling(self.src.color(), self.dst.color(), &self.signaling, origin)
350    }
351
352    /// Build a streaming [`RowPlan`](crate::RowPlan) matching this output plan so
353    /// row encoders can emit validated headers via [`resolve_signaling`](Self::resolve_signaling)
354    /// and convert scanlines without full-frame allocation.
355    pub fn build_row_plan(
356        &self,
357        resolved_source_peak: Option<zenpixels::Nits>,
358    ) -> Result<crate::plan::RowPlan, At<ConvertError>> {
359        self.build_row_plan_with_pulse(resolved_source_peak, None)
360    }
361
362    /// Build a streaming [`RowPlan`](crate::RowPlan) matching this output plan with optional
363    /// cooperative cancellation and progress via `pulse` (pass `None` when not needed).
364    pub fn build_row_plan_with_pulse(
365        &self,
366        resolved_source_peak: Option<zenpixels::Nits>,
367        pulse: Option<&dyn Pulse>,
368    ) -> Result<crate::plan::RowPlan, At<ConvertError>> {
369        crate::plan::RowPlan::build_with_pulse(
370            &self.src,
371            &self.dst,
372            self.image_plan.policy(),
373            resolved_source_peak,
374            pulse,
375        )
376    }
377
378    /// One-shot encoder preparation: negotiate the lowest-loss, lowest-effort format from
379    /// `supported` under `policy`, convert (or borrow **zero-copy** on identity), and resolve
380    /// guaranteed-matching container color signaling (`cicp`, `icc`, `hdr`).
381    ///
382    /// Thin wrapper combining [`Negotiate::select`](crate::Negotiate::select),
383    /// [`OutputPlan::build`], and [`OutputPlan::execute_view`], automatically merging
384    /// `src.attached_claims()` into `policy.source_claims` before negotiation. Returns
385    /// [`ConvertError::UnsupportedRoute`] if no candidate in `supported` satisfies `policy`.
386    pub fn adapt_for_encode<'a>(
387        src: PixelView<'a>,
388        origin: &ColorOrigin,
389        supported: &[PixelFormat],
390        policy: &ConvertPolicy,
391        peak: PeakSource,
392        signaling: OutputSignaling,
393    ) -> Result<(crate::negotiate::NegotiatedFormat, EncodeReady<'a>), At<ConvertError>> {
394        Self::adapt_for_encode_with_pulse(src, origin, supported, policy, peak, signaling, None)
395    }
396
397    /// One-shot encoder preparation with optional cooperative cancellation and progress via
398    /// `pulse` (pass `None` when not needed).
399    pub fn adapt_for_encode_with_pulse<'a>(
400        src: PixelView<'a>,
401        origin: &ColorOrigin,
402        supported: &[PixelFormat],
403        policy: &ConvertPolicy,
404        peak: PeakSource,
405        signaling: OutputSignaling,
406        pulse: Option<&dyn Pulse>,
407    ) -> Result<(crate::negotiate::NegotiatedFormat, EncodeReady<'a>), At<ConvertError>> {
408        let pulse = live_pulse(pulse);
409        check_pulse(pulse)?;
410        let mut eff_policy = policy.clone();
411        eff_policy.source_claims =
412            crate::plan::merge_facts(policy.source_claims, src.attached_claims());
413        let negotiated = crate::negotiate::Negotiate::select(src.format(), supported, &eff_policy)
414            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
415        let plan = Self::build_with_pulse(
416            src.format(),
417            negotiated.format(),
418            &eff_policy,
419            peak,
420            signaling,
421            pulse,
422        )?;
423        let ready = plan.execute_view_with_pulse(src, origin, pulse)?;
424        Ok((negotiated, ready))
425    }
426}
427
428fn try_clone_bytes(bytes: &[u8]) -> Result<alloc::vec::Vec<u8>, At<ConvertError>> {
429    let mut v = alloc::vec::Vec::new();
430    v.try_reserve_exact(bytes.len())
431        .map_err(|_| err_at(ConvertError::AllocationFailed))?;
432    v.extend_from_slice(bytes);
433    Ok(v)
434}
435
436/// Validate ICC header, declared length, profile class, and tag-table bounds (B10).
437fn validate_icc_structure(bytes: &[u8]) -> Result<(), At<ConvertError>> {
438    zenpixels::validate_icc_structure(bytes)
439        .map_err(|_| err_at(ConvertError::OutputSignalingMismatch))
440}
441
442fn validate_custom_icc_for_dst(
443    bytes: &[u8],
444    dst_color: &ColorSpace,
445) -> Result<(), At<ConvertError>> {
446    validate_icc_structure(bytes)?;
447    let is_narrow = dst_color.range() == Some(zenpixels::SignalRange::Narrow);
448    if is_narrow {
449        return Err(err_at(ConvertError::OutputSignalingMismatch));
450    }
451    let Some(sig) = zenpixels::IccColorSpace::from_icc(bytes) else {
452        return Err(err_at(ConvertError::OutputSignalingMismatch));
453    };
454    let matches_model = match dst_color {
455        ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } => {
456            sig == zenpixels::IccColorSpace::Rgb
457        }
458        ColorSpace::Gray { .. } => sig == zenpixels::IccColorSpace::Gray,
459        ColorSpace::Cmyk { icc: Some(p), .. } => {
460            sig == zenpixels::IccColorSpace::Cmyk && zenpixels::icc::normalized_eq(p, bytes)
461        }
462        ColorSpace::Icc { profile, .. } => {
463            zenpixels::IccColorSpace::from_icc(profile) == Some(sig)
464                && zenpixels::icc::normalized_eq(profile, bytes)
465        }
466        _ => false,
467    };
468    if !matches_model {
469        return Err(err_at(ConvertError::OutputSignalingMismatch));
470    }
471    // Structured RGB/Gray destinations require positive matrix+TRC identification matching
472    // destination primaries & transfer — arbitrary or `MetadataOnly` ICC profiles (such as
473    // non-D65 / Illuminant C historical profiles) must target `ColorSpace::Icc` explicitly
474    // so pixels are converted via CMS rather than mislabeled.
475    match dst_color {
476        ColorSpace::Rgb {
477            primaries,
478            transfer,
479            ..
480        } => {
481            let Some(id) = zenpixels::icc::IccIdentification::from_icc(bytes) else {
482                return Err(err_at(ConvertError::OutputSignalingMismatch));
483            };
484            if id.valid_use() != zenpixels::icc::IdentificationUse::MatrixTrcSubstitution
485                || !id.primaries().same_chromaticity(*primaries)
486                || !id.transfer().same_curve(*transfer)
487            {
488                return Err(err_at(ConvertError::OutputSignalingMismatch));
489            }
490            Ok(())
491        }
492        ColorSpace::RgbCustom {
493            primaries,
494            transfer,
495            ..
496        } => {
497            if let Some(id) = zenpixels::icc::IccIdentification::from_icc(bytes)
498                && id.valid_use() == zenpixels::icc::IdentificationUse::MatrixTrcSubstitution
499                && id
500                    .primaries()
501                    .to_custom()
502                    .is_some_and(|c| c.same_chromaticity(**primaries))
503                && id.transfer().same_curve(*transfer)
504            {
505                return Ok(());
506            }
507            Err(err_at(ConvertError::OutputSignalingMismatch))
508        }
509        ColorSpace::Gray { transfer, .. } => {
510            let Some(id) = zenpixels::icc::IccIdentification::from_icc(bytes) else {
511                return Err(err_at(ConvertError::OutputSignalingMismatch));
512            };
513            if id.valid_use() != zenpixels::icc::IdentificationUse::MatrixTrcSubstitution
514                || !id.transfer().same_curve(*transfer)
515            {
516                return Err(err_at(ConvertError::OutputSignalingMismatch));
517            }
518            Ok(())
519        }
520        ColorSpace::Icc { .. } | ColorSpace::Cmyk { .. } => Ok(()),
521        _ => Err(err_at(ConvertError::OutputSignalingMismatch)),
522    }
523}
524
525/// Semantic CICP equality: allows H.273 chromaticity/transfer aliases that evaluate the exact
526/// same mathematical primaries/curve (e.g. BT.709 / BT.601 / BT.2020 10-bit/12-bit transfer codes
527/// 1, 6, 14, 15, or BT.601 / SMPTE 240M primaries 6 and 7).
528fn cicp_semantically_eq(a: Cicp, b: Cicp) -> bool {
529    if a == b {
530        return true;
531    }
532    let prim_eq = a.color_primaries == b.color_primaries
533        || match (
534            Primaries::from_cicp(a.color_primaries),
535            Primaries::from_cicp(b.color_primaries),
536        ) {
537            (Some(pa), Some(pb)) => pa.same_chromaticity(pb),
538            _ => false,
539        };
540    let tf_eq = a.transfer_characteristics == b.transfer_characteristics
541        || match (
542            Transfer::from_cicp(a.transfer_characteristics),
543            Transfer::from_cicp(b.transfer_characteristics),
544        ) {
545            (Some(ta), Some(tb)) => ta.same_curve(tb),
546            _ => false,
547        };
548    prim_eq
549        && tf_eq
550        && a.matrix_coefficients == b.matrix_coefficients
551        && a.full_range == b.full_range
552}
553
554/// Check whether `orig_cicp` agrees with `dst_color` (including `ColorSpace::Icc` via embedded
555/// `cicp` tag or qualified `IccIdentification` — B12).
556fn origin_cicp_agrees(orig_cicp: Cicp, dst_color: &ColorSpace) -> bool {
557    if let Some(dst_cicp) = dst_color.to_cicp_lossy() {
558        return cicp_semantically_eq(dst_cicp, orig_cicp);
559    }
560    if let ColorSpace::Icc {
561        profile,
562        color_channels: 3,
563        ..
564    } = dst_color
565    {
566        if let Some(tag_cicp) = Cicp::from_icc(profile) {
567            return cicp_semantically_eq(tag_cicp, orig_cicp);
568        }
569        if let Some(id) = zenpixels::icc::IccIdentification::from_icc(profile)
570            && id
571                .to_cicp()
572                .is_some_and(|c| cicp_semantically_eq(c, orig_cicp))
573        {
574            return true;
575        }
576    }
577    false
578}
579
580fn resolve_cicp_for_dst(dst_color: &ColorSpace) -> Result<Cicp, At<ConvertError>> {
581    if matches!(
582        dst_color,
583        ColorSpace::Rgb {
584            transfer: Transfer::Hlg(HlgMode::Display(_)),
585            ..
586        } | ColorSpace::RgbCustom {
587            transfer: Transfer::Hlg(HlgMode::Display(_)),
588            ..
589        }
590    ) {
591        return Err(err_at(ConvertError::OutputSignalingUnavailable));
592    }
593    dst_color
594        .to_cicp_lossy()
595        .ok_or_else(|| err_at(ConvertError::OutputSignalingUnavailable))
596}
597
598fn resolve_icc_for_dst(dst_color: &ColorSpace) -> Result<Cow<'static, [u8]>, At<ConvertError>> {
599    let icc = match dst_color {
600        ColorSpace::Icc { profile, .. } => {
601            validate_custom_icc_for_dst(profile, dst_color)?;
602            Some(Cow::Owned(try_clone_bytes(profile)?))
603        }
604        ColorSpace::Cmyk { icc: Some(b), .. } => {
605            validate_custom_icc_for_dst(b, dst_color)?;
606            Some(Cow::Owned(try_clone_bytes(b)?))
607        }
608        ColorSpace::Rgb {
609            primaries,
610            transfer,
611            range: zenpixels::SignalRange::Full,
612            ..
613        } => bundled_icc_for(*primaries, *transfer).or_else(|| {
614            dst_color
615                .to_cicp_lossy()
616                .and_then(|c| match SynthesizedIcc::for_cicp(c) {
617                    SynthesizedIcc::Profile(b) => Some(b),
618                    _ => None,
619                })
620        }),
621        ColorSpace::Gray {
622            transfer,
623            range: zenpixels::SignalRange::Full,
624            ..
625        } => transfer.to_cicp().and_then(|tc| {
626            let gray_cicp = Cicp::new(1, tc, 0, true);
627            match SynthesizedIcc::for_gray_cicp(gray_cicp) {
628                SynthesizedIcc::Profile(b) => Some(b),
629                _ => None,
630            }
631        }),
632        _ => None,
633    };
634    icc.ok_or_else(|| err_at(ConvertError::OutputSignalingUnavailable))
635}
636
637fn resolve_output_signaling(
638    src_color: &ColorSpace,
639    dst_color: &ColorSpace,
640    signaling: &OutputSignaling,
641    origin: &ColorOrigin,
642) -> Result<ResolvedSignaling, At<ConvertError>> {
643    match signaling {
644        OutputSignaling::Strip => Ok(ResolvedSignaling {
645            cicp: None,
646            icc: None,
647        }),
648        OutputSignaling::ExplicitIcc(bytes) => {
649            validate_custom_icc_for_dst(bytes, dst_color)?;
650            // Do not synthesize a potentially contradicting CICP alongside an explicit ICC.
651            Ok(ResolvedSignaling {
652                cicp: None,
653                icc: Some(Cow::Owned(try_clone_bytes(bytes)?)),
654            })
655        }
656        OutputSignaling::CicpOnly => {
657            let cicp = resolve_cicp_for_dst(dst_color)?;
658            Ok(ResolvedSignaling {
659                cicp: Some(cicp),
660                icc: None,
661            })
662        }
663        OutputSignaling::PreserveOrigin => {
664            if !same_color_meaning(src_color, dst_color) {
665                return Err(err_at(ConvertError::OutputSignalingMismatch));
666            }
667            // Untagged / assumed origin carries no tags — preserve `(None, None)` verbatim
668            // rather than inventing a CICP tuple (B12).
669            if origin.icc().is_none() && origin.cicp().is_none() {
670                return Ok(ResolvedSignaling {
671                    cicp: None,
672                    icc: None,
673                });
674            }
675            let is_narrow = dst_color.range() == Some(zenpixels::SignalRange::Narrow);
676            // Verify that preserved origin ICC and CICP actually agree with `dst_color`
677            // (never leak historical P3/CMYK/YCbCr provenance onto converted sRGB pixels!).
678            let icc = if let Some(orig_icc) = origin.icc().as_ref() {
679                if is_narrow {
680                    return Err(err_at(ConvertError::OutputSignalingMismatch));
681                }
682                validate_custom_icc_for_dst(orig_icc, dst_color)?;
683                Some(Cow::Owned(try_clone_bytes(orig_icc)?))
684            } else {
685                None
686            };
687            let cicp = if let Some(orig_cicp) = origin.cicp() {
688                if !origin_cicp_agrees(orig_cicp, dst_color) {
689                    return Err(err_at(ConvertError::OutputSignalingMismatch));
690                }
691                Some(orig_cicp)
692            } else {
693                None
694            };
695            Ok(ResolvedSignaling { cicp, icc })
696        }
697        OutputSignaling::IccOnly => {
698            let icc_bytes = resolve_icc_for_dst(dst_color)?;
699            Ok(ResolvedSignaling {
700                cicp: None,
701                icc: Some(icc_bytes),
702            })
703        }
704        OutputSignaling::CicpAndIcc => {
705            let cicp = resolve_cicp_for_dst(dst_color)?;
706            let icc_bytes = resolve_icc_for_dst(dst_color)?;
707            Ok(ResolvedSignaling {
708                cicp: Some(cicp),
709                icc: Some(icc_bytes),
710            })
711        }
712        OutputSignaling::Auto => match dst_color {
713            ColorSpace::Icc { profile, .. } => {
714                validate_custom_icc_for_dst(profile, dst_color)?;
715                Ok(ResolvedSignaling {
716                    cicp: None,
717                    icc: Some(Cow::Owned(try_clone_bytes(profile)?)),
718                })
719            }
720            ColorSpace::Cmyk { icc: Some(b), .. } => {
721                validate_custom_icc_for_dst(b, dst_color)?;
722                Ok(ResolvedSignaling {
723                    cicp: None,
724                    icc: Some(Cow::Owned(try_clone_bytes(b)?)),
725                })
726            }
727            ColorSpace::Cmyk { icc: None, .. } => Ok(ResolvedSignaling {
728                cicp: None,
729                icc: None,
730            }),
731            ColorSpace::Rgb {
732                primaries,
733                transfer,
734                range,
735                ..
736            } => {
737                // CICP TC=18 carries scene-referred HLG syntax only; display-rendered HLG
738                // parameters (`peak`, `black_nits`, `system_gamma`) cannot be represented in CICP
739                // or ICC without explicit conversion.
740                if matches!(transfer, Transfer::Hlg(HlgMode::Display(_))) {
741                    return Err(err_at(ConvertError::OutputSignalingUnavailable));
742                }
743                let cicp = dst_color.to_cicp_lossy();
744                // ICC RGB profiles describe full-range sample codes; never attach them to narrow-range outputs.
745                let is_default_srgb = *primaries == Primaries::Bt709
746                    && *transfer == Transfer::Srgb
747                    && *range == zenpixels::SignalRange::Full;
748                let icc = if *range != zenpixels::SignalRange::Full || is_default_srgb {
749                    None
750                } else {
751                    bundled_icc_for(*primaries, *transfer).or_else(|| {
752                        cicp.and_then(|c| match SynthesizedIcc::for_cicp(c) {
753                            SynthesizedIcc::Profile(b) => Some(b),
754                            _ => None,
755                        })
756                    })
757                };
758                if cicp.is_none() && icc.is_none() && !is_default_srgb {
759                    return Err(err_at(ConvertError::OutputSignalingUnavailable));
760                }
761                Ok(ResolvedSignaling { cicp, icc })
762            }
763            ColorSpace::Gray {
764                transfer, range, ..
765            } => {
766                // Default full-range sRGB Gray needs no ICC tag (universally assumed default).
767                if *transfer == Transfer::Srgb && *range == zenpixels::SignalRange::Full {
768                    return Ok(ResolvedSignaling {
769                        cicp: None,
770                        icc: None,
771                    });
772                }
773                if *range != zenpixels::SignalRange::Full {
774                    return Err(err_at(ConvertError::OutputSignalingUnavailable));
775                }
776                let icc = transfer.to_cicp().and_then(|tc| {
777                    match SynthesizedIcc::for_gray_cicp(Cicp::new(1, tc, 0, true)) {
778                        SynthesizedIcc::Profile(b) => Some(b),
779                        _ => None,
780                    }
781                });
782                let Some(icc_bytes) = icc else {
783                    return Err(err_at(ConvertError::OutputSignalingUnavailable));
784                };
785                Ok(ResolvedSignaling {
786                    cicp: None,
787                    icc: Some(icc_bytes),
788                })
789            }
790            _ => match dst_color.to_cicp_lossy() {
791                Some(c) => Ok(ResolvedSignaling {
792                    cicp: Some(c),
793                    icc: None,
794                }),
795                None => Err(err_at(ConvertError::OutputSignalingUnavailable)),
796            },
797        },
798    }
799}
800
801fn bundled_icc_for(primaries: Primaries, transfer: Transfer) -> Option<Cow<'static, [u8]>> {
802    crate::icc_profiles::bundled_icc_profile(primaries, transfer).map(Cow::Borrowed)
803}