Skip to main content

zenpixels_convert/
negotiate.rs

1//! Codec format negotiation: select the lowest-loss, lowest-effort supported [`PixelFormat`].
2
3use zenpixels::{ColorSpace, PixelFormat, Primaries, Transfer};
4
5use crate::plan::{
6    color_primaries, color_transfer, preflight_and_classify, same_color_meaning, try_substitute_icc,
7};
8use crate::policy::{ConvertPolicy, DepthPolicy, GamutPolicy};
9
10/// Category of information lost when converting `src` to a candidate format.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12#[non_exhaustive]
13pub enum LossKind {
14    /// Zero information loss (exact or lossless widening/swizzle).
15    None,
16    /// Quantization or bit-depth narrowing (`F32 → U16 → U8`, `RGBA8 → RGB10A2`).
17    Depth,
18    /// Gamut narrowing, signal-range scaling, or HDR → SDR compression.
19    Gamut,
20    /// Dropping color into grayscale (`RGB → Gray`).
21    Chroma,
22    /// Dropping unproven non-opaque alpha.
23    Alpha,
24}
25
26/// Deterministic cost score for comparing candidate encoder formats.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
28pub struct FormatCost {
29    /// Highest severity information loss (lower is better; `0` = lossless).
30    pub loss_rank: u8,
31    /// Secondary bitmask of all active loss axes (breaks ties when two candidates share `loss_rank`).
32    pub loss_mask: u8,
33    /// Conversion effort (`0` = identity zero-copy, `1` = byte/layout swizzle, `2` = color/transfer math).
34    pub effort: u8,
35    /// Bytes per pixel tiebreaker (smaller preferred when loss & effort match).
36    pub bytes_per_pixel: u8,
37}
38
39/// Selected negotiation candidate with its cost breakdown.
40#[derive(Clone, Debug, PartialEq, Eq)]
41#[non_exhaustive]
42pub struct NegotiatedFormat {
43    /// Index into the caller's `supported` slice.
44    index: usize,
45    /// Chosen destination pixel format.
46    format: PixelFormat,
47    /// Worst-case loss category.
48    loss: LossKind,
49    /// Deterministic ranking cost.
50    cost: FormatCost,
51}
52
53impl NegotiatedFormat {
54    /// Index of the selected entry in the candidate slice.
55    #[inline]
56    #[must_use]
57    pub const fn index(&self) -> usize {
58        self.index
59    }
60
61    /// Format at the selected index.
62    #[inline]
63    #[must_use]
64    pub const fn format(&self) -> &PixelFormat {
65        &self.format
66    }
67
68    /// Worst-case loss class of the selected conversion.
69    #[inline]
70    #[must_use]
71    pub const fn loss(&self) -> LossKind {
72        self.loss
73    }
74
75    /// Ordering cost of the selected conversion.
76    #[inline]
77    #[must_use]
78    pub const fn cost(&self) -> FormatCost {
79        self.cost
80    }
81}
82
83/// Format negotiator selecting the best feasible candidate from a codec's supported list.
84pub struct Negotiate;
85
86impl Negotiate {
87    /// Select the best candidate from `supported` that satisfies `policy`.
88    ///
89    /// Shares the planner's deterministic feasibility checks (policy gates,
90    /// `Transfer::Unknown` linear-math guards, PQ/HLG anchor requirements,
91    /// feature gates, and `CmsBackend::supports_formats`) so selected candidates
92    /// do not unexpectedly fail in `RowPlan::build`.
93    #[must_use]
94    pub fn select(
95        src: &PixelFormat,
96        supported: &[PixelFormat],
97        policy: &ConvertPolicy,
98    ) -> Option<NegotiatedFormat> {
99        let mut best: Option<NegotiatedFormat> = None;
100        for (index, cand) in supported.iter().enumerate() {
101            if let Some(scored) = score_candidate(src, cand, index, policy)
102                && best.as_ref().is_none_or(|prev| scored.cost < prev.cost)
103            {
104                best = Some(scored);
105            }
106        }
107        best
108    }
109}
110
111fn score_candidate(
112    src: &PixelFormat,
113    cand: &PixelFormat,
114    index: usize,
115    policy: &ConvertPolicy,
116) -> Option<NegotiatedFormat> {
117    let pre = preflight_and_classify(src, cand, policy).ok()?;
118
119    if !pre.is_identity {
120        // Check CMS substitution vs direct CMS feasibility.
121        let eff_src_owned = if pre.uses_cms {
122            try_substitute_icc(src, policy)
123        } else {
124            None
125        };
126        let eff_dst_owned = if pre.uses_cms {
127            try_substitute_icc(cand, policy)
128        } else {
129            None
130        };
131        let direct_cms = pre.uses_cms && (eff_src_owned.is_none() || eff_dst_owned.is_none());
132
133        if direct_cms {
134            let cms = policy.cms.as_ref()?;
135            if policy.depth == DepthPolicy::OrderedDither
136                || policy.gamut == GamutPolicy::SoftCompress
137            {
138                return None;
139            }
140            if !cms.supports_formats(src, cand) {
141                return None;
142            }
143        } else {
144            let eff_src = eff_src_owned.as_ref().unwrap_or(src);
145            let eff_dst = eff_dst_owned.as_ref().unwrap_or(cand);
146            if !native_route_feasible(eff_src, eff_dst, policy, pre.matte_color.is_some()) {
147                return None;
148            }
149        }
150    }
151
152    let mut loss_mask = 0u8;
153    if pre.depth_reduces {
154        loss_mask |= 1 << 0;
155    }
156    if pre.gamut_narrows || pre.is_hdr_to_sdr || pre.range_change {
157        loss_mask |= 1 << 1;
158    }
159    if pre.drops_chroma && !pre.chroma_proven_gray {
160        loss_mask |= 1 << 2;
161    }
162    if pre.drops_alpha && !pre.alpha_proven_opaque {
163        loss_mask |= 1 << 3;
164    }
165
166    let (loss, loss_rank) = if (loss_mask & (1 << 3)) != 0 {
167        (LossKind::Alpha, 4)
168    } else if (loss_mask & (1 << 2)) != 0 {
169        (LossKind::Chroma, 3)
170    } else if (loss_mask & (1 << 1)) != 0 {
171        (LossKind::Gamut, 2)
172    } else if (loss_mask & (1 << 0)) != 0 {
173        (LossKind::Depth, 1)
174    } else {
175        (LossKind::None, 0)
176    };
177
178    let effort = if pre.is_identity {
179        0
180    } else if same_color_meaning(src.color(), cand.color())
181        && !pre.range_change
182        && src.color().alpha() == cand.color().alpha()
183    {
184        1
185    } else {
186        2
187    };
188
189    let cost = FormatCost {
190        loss_rank,
191        loss_mask,
192        effort,
193        bytes_per_pixel: cand.layout().bytes_per_pixel().min(255) as u8,
194    };
195    Some(NegotiatedFormat {
196        index,
197        format: cand.clone(),
198        loss,
199        cost,
200    })
201}
202
203fn native_route_feasible(
204    src: &PixelFormat,
205    dst: &PixelFormat,
206    policy: &ConvertPolicy,
207    matte_active: bool,
208) -> bool {
209    let st = color_transfer(src.color());
210    let dt = color_transfer(dst.color());
211    let sp = color_primaries(src.color());
212    let dp = color_primaries(dst.color());
213
214    if (st.is_hdr() || dt.is_hdr()) && !cfg!(feature = "hdr-transfers") {
215        return false;
216    }
217    if (matches!(src.color(), ColorSpace::Oklab { .. })
218        || matches!(dst.color(), ColorSpace::Oklab { .. }))
219        && !cfg!(feature = "oklab")
220    {
221        return false;
222    }
223    if (matches!(src.color(), ColorSpace::Perceptual { .. })
224        || matches!(dst.color(), ColorSpace::Perceptual { .. }))
225        && !cfg!(feature = "perceptual")
226    {
227        return false;
228    }
229    if policy.gamut == GamutPolicy::SoftCompress && !cfg!(feature = "oklab") {
230        return false;
231    }
232
233    let src_is_pq = st == Transfer::Pq;
234    let dst_is_pq = dt == Transfer::Pq;
235    if src_is_pq
236        && !dst_is_pq
237        && dst.color().diffuse_white().is_none()
238        && policy.diffuse_white.is_none()
239    {
240        return false;
241    }
242    if !src_is_pq
243        && dst_is_pq
244        && src.color().diffuse_white().is_none()
245        && policy.diffuse_white.is_none()
246    {
247        return false;
248    }
249
250    let gamut_changes = !sp.same_chromaticity(dp) && src.color().is_rgb() && dst.color().is_rgb();
251    if gamut_changes && (sp.is_unknown() || dp.is_unknown()) {
252        return false;
253    }
254
255    // B09: RGB -> Gray requires resolvable luma weights (FromSourcePrimaries on Unknown fails).
256    if src.color().is_rgb()
257        && matches!(dst.color(), ColorSpace::Gray { .. })
258        && crate::strip::resolve_luma_weights(policy.luma, sp).is_none()
259    {
260        return false;
261    }
262
263    // B05 + G14: HDR -> SDR (including unproven scene-linear float -> SDR) with tone
264    // mapping enabled requires a streaming tone mapper (either injected on policy or the
265    // built-in `bt2446a` feature).
266    let is_hdr_to_sdr = (st.is_hdr()
267        && !dt.is_hdr()
268        && matches!(
269            dst.color(),
270            ColorSpace::Rgb { .. } | ColorSpace::RgbCustom { .. } | ColorSpace::Gray { .. }
271        ))
272        || (crate::plan::is_scene_linear_hdr_candidate(src, dst)
273            && !policy.source_claims.float.is_unit_interval());
274    if is_hdr_to_sdr && policy.tone_map_hdr_to_sdr {
275        match crate::plan::resolve_tone_mapper(policy) {
276            Ok(m) if !m.requirements().full_image => {}
277            _ => return false,
278        }
279    }
280
281    let need_linear = !st.same_curve(dt)
282        || gamut_changes
283        || matte_active
284        || matches!(
285            src.color(),
286            ColorSpace::Oklab { .. } | ColorSpace::Perceptual { .. } | ColorSpace::Xyz { .. }
287        )
288        || matches!(
289            dst.color(),
290            ColorSpace::Oklab { .. } | ColorSpace::Perceptual { .. } | ColorSpace::Xyz { .. }
291        )
292        || (src.color().is_rgb()
293            && matches!(dst.color(), ColorSpace::Gray { .. })
294            && policy.luma_domain == crate::policy::LumaDomain::LinearLight)
295        || (src.color().diffuse_white() != dst.color().diffuse_white()
296            && src.color().diffuse_white().is_some()
297            && dst.color().diffuse_white().is_some());
298
299    if (need_linear || !st.same_curve(dt)) && (st == Transfer::Unknown || dt == Transfer::Unknown) {
300        return false;
301    }
302
303    let is_bt2020_full = |cs: &ColorSpace| {
304        matches!(
305            cs,
306            ColorSpace::Rgb {
307                primaries: Primaries::Bt2020,
308                range: zenpixels::SignalRange::Full,
309                ..
310            }
311        )
312    };
313    if matches!(st, Transfer::Hlg(zenpixels::HlgMode::Scene))
314        && !matches!(dt, Transfer::Hlg(zenpixels::HlgMode::Scene))
315        && (policy.hlg_rendering.is_none() || !is_bt2020_full(src.color()))
316    {
317        return false;
318    }
319    if matches!(dt, Transfer::Hlg(zenpixels::HlgMode::Scene))
320        && !matches!(st, Transfer::Hlg(zenpixels::HlgMode::Scene))
321        && (policy.hlg_rendering.is_none() || !is_bt2020_full(dst.color()))
322    {
323        return false;
324    }
325
326    true
327}