Skip to main content

zenpsy_api/
planar.rs

1//! Optional planar ingress and owned preparation with lending comparisons.
2use crate::metric::{admit_geometry, operation, validate_map_views, validate_scores};
3use crate::{
4    ErrorKind, EvalOpts, Evaluation, EvaluationRef, Metric, MetricError, MetricResult, fail,
5};
6use alloc::vec::Vec;
7use whereat::ResultAtExt as _;
8use zenpixels::{AlphaMode, ChromaSiting, ColorSpace, PlanarView, PlaneFormat, SignalRange};
9
10/// Optional native planar input. The packed [`Metric`] contract stays usable
11/// independently; no implicit conversion or packed replay is supplied.
12pub trait PlanarMetric: Metric {
13    /// Score complete color-described planes, preserving native output.
14    fn evaluate_planar(
15        &mut self,
16        reference: &PlanarView<'_>,
17        candidate: &PlanarView<'_>,
18        opts: EvalOpts<'_>,
19    ) -> MetricResult<Self::Output>;
20}
21/// Reusable native planar work owned independently of its factory scorer.
22/// The preparation input and its Pulse are not retained. Configuration borrows
23/// already held by the factory may be carried in the concrete prepared type.
24pub trait PreparePlanarReference: PlanarMetric {
25    /// Actual owned reference work, suitable for storage in an encoder callback.
26    type PlanarPrepared: PlanarWarmReference<Output = Self::Output>;
27    /// Build native reference work. Subsequent calls use fresh controls.
28    fn warm_planar_reference(
29        &mut self,
30        reference: &PlanarView<'_>,
31        opts: EvalOpts<'_>,
32    ) -> MetricResult<Self::PlanarPrepared>;
33}
34/// Prepared native planar scoring. Implementors may override lending to let
35/// consumers inspect native scratch before it is recycled, avoiding map export.
36/// Workers must join before return. After failure, reuse must succeed correctly
37/// or refuse explicitly; stale assessments must never be returned.
38pub trait PlanarWarmReference {
39    /// Complete owned native assessment.
40    type Output: Evaluation;
41    /// Evaluate a candidate using actual prepared reference work.
42    fn evaluate_planar(
43        &mut self,
44        candidate: &PlanarView<'_>,
45        opts: EvalOpts<'_>,
46    ) -> MetricResult<Self::Output>;
47    /// Invoke `consumer` exactly once on success, while all borrowed native
48    /// arrays remain valid. The default borrows an owned result; an override
49    /// can lend scratch directly. A failed operation need not invoke it.
50    fn with_evaluation(
51        &mut self,
52        candidate: &PlanarView<'_>,
53        opts: EvalOpts<'_>,
54        consumer: &mut dyn FnMut(EvaluationRef<'_>),
55    ) -> MetricResult<()> {
56        let output = self.evaluate_planar(candidate, opts)?;
57        consumer(EvaluationRef::new(&output));
58        Ok(())
59    }
60}
61#[derive(Clone, Copy, PartialEq, Eq)]
62struct BoundPlane {
63    format: PlaneFormat,
64    size: (u32, u32),
65    phase: (u8, u8),
66}
67
68fn plane_phase(format: PlaneFormat, crop_origin: (u32, u32)) -> (u8, u8) {
69    let (hx, vy) = format.subsampling_divisors();
70    (
71        (crop_origin.0 % u32::from(hx)) as u8,
72        (crop_origin.1 % u32::from(vy)) as u8,
73    )
74}
75
76/// Checked owned planar work, binding image geometry, per-plane extent and
77/// subsampling phase, plane interpretation, and color/luminance to preparation.
78/// Strides and phase-equivalent crop origins may differ for every candidate.
79pub struct PreparedPlanarReference<P> {
80    inner: P,
81    size: (u32, u32),
82    planes: Vec<BoundPlane>,
83    chroma_siting: ChromaSiting,
84    color: Option<ColorSpace>,
85    matrix_coefficients: Option<zenpixels::MatrixCoefficients>,
86    range: Option<SignalRange>,
87    alpha: Option<AlphaMode>,
88}
89impl<P: PlanarWarmReference> PreparedPlanarReference<P> {
90    fn admit(&self, candidate: &PlanarView<'_>, opts: EvalOpts<'_>) -> MetricResult<()> {
91        admit(candidate, opts)?;
92        if (candidate.width(), candidate.height()) != self.size {
93            return fail(MetricError::new(ErrorKind::DimensionMismatch));
94        }
95        let formats_match = candidate.planes().len() == self.planes.len()
96            && candidate
97                .planes()
98                .iter()
99                .zip(self.planes.iter())
100                .all(|(p, expected)| p.format() == expected.format);
101        if !formats_match
102            || candidate.chroma_siting() != self.chroma_siting
103            || candidate.color() != self.color.as_ref()
104            || candidate.matrix_coefficients() != self.matrix_coefficients
105            || candidate.effective_range() != self.range
106            || candidate.effective_alpha() != self.alpha
107        {
108            return fail(
109                MetricError::new(ErrorKind::UnsupportedInput)
110                    .with_message("prepared planar interpretation changed"),
111            );
112        }
113        let extents_match = candidate
114            .planes()
115            .iter()
116            .zip(self.planes.iter())
117            .all(|(p, expected)| (p.width(), p.height()) == expected.size);
118        if !extents_match {
119            return fail(
120                MetricError::new(ErrorKind::DimensionMismatch)
121                    .with_message("prepared plane extent changed"),
122            );
123        }
124        let origin = candidate.crop_origin();
125        let phases_match = candidate
126            .planes()
127            .iter()
128            .zip(self.planes.iter())
129            .all(|(p, expected)| plane_phase(p.format(), origin) == expected.phase);
130        if !phases_match {
131            return fail(
132                MetricError::new(ErrorKind::UnsupportedInput)
133                    .with_message("prepared planar subsampling phase changed"),
134            );
135        }
136        Ok(())
137    }
138    /// Produce a checked owned native assessment.
139    pub fn score(
140        &mut self,
141        candidate: &PlanarView<'_>,
142        opts: EvalOpts<'_>,
143    ) -> MetricResult<P::Output> {
144        operation(opts, "score prepared planar image", |opts| {
145            self.admit(candidate, opts)?;
146            let output = self.inner.evaluate_planar(candidate, opts).at()?;
147            let view = EvaluationRef::new(&output);
148            validate_scores(view)?;
149            validate_map_views(view, candidate.width(), candidate.height(), opts)?;
150            opts.checkpoint()?;
151            Ok(output)
152        })
153    }
154    /// Consume a checked borrowed assessment before native scratch is recycled.
155    /// Returned `T` cannot borrow the temporary view. The callback is invoked
156    /// once at most; callers commit side effects only after this call succeeds.
157    pub fn with_evaluation<T>(
158        &mut self,
159        candidate: &PlanarView<'_>,
160        opts: EvalOpts<'_>,
161        consume: impl FnOnce(EvaluationRef<'_>) -> MetricResult<T>,
162    ) -> MetricResult<T> {
163        operation(opts, "inspect prepared planar image", |opts| {
164            self.admit(candidate, opts)?;
165            let mut consume = Some(consume);
166            let mut output = None;
167            let mut repeated = false;
168            self.inner
169                .with_evaluation(candidate, opts, &mut |view| {
170                    let Some(consume) = consume.take() else {
171                        repeated = true;
172                        return;
173                    };
174                    output = Some((|| {
175                        validate_scores(view)?;
176                        validate_map_views(view, candidate.width(), candidate.height(), opts)?;
177                        opts.checkpoint()?;
178                        consume(view)
179                    })());
180                })
181                .at()?;
182            if repeated {
183                return fail(
184                    MetricError::new(ErrorKind::Internal).with_message("lending callback repeated"),
185                );
186            }
187            let output = output.ok_or_else(|| {
188                whereat::at(
189                    MetricError::new(ErrorKind::Internal).with_message("lending callback omitted"),
190                )
191            })??;
192            opts.checkpoint()?;
193            Ok(output)
194        })
195    }
196}
197fn admit(image: &PlanarView<'_>, opts: EvalOpts<'_>) -> MetricResult<()> {
198    admit_geometry(image.width(), image.height(), opts)
199}
200/// Checked native planar pair scoring. Color/encoding support is decided by
201/// the metric, which must refuse unsupported interpretation explicitly.
202pub fn score_planar<M: PlanarMetric + ?Sized>(
203    metric: &mut M,
204    reference: &PlanarView<'_>,
205    candidate: &PlanarView<'_>,
206    opts: EvalOpts<'_>,
207) -> MetricResult<M::Output> {
208    operation(opts, "score planar image pair", |opts| {
209        admit(reference, opts)?;
210        admit(candidate, opts)?;
211        if (reference.width(), reference.height()) != (candidate.width(), candidate.height()) {
212            return fail(MetricError::new(ErrorKind::DimensionMismatch));
213        }
214        let output = metric.evaluate_planar(reference, candidate, opts).at()?;
215        let view = EvaluationRef::new(&output);
216        validate_scores(view)?;
217        validate_map_views(view, candidate.width(), candidate.height(), opts)?;
218        opts.checkpoint()?;
219        Ok(output)
220    })
221}
222/// Prepare owned planar work, binding candidate interpretation and geometry.
223pub fn prepare_planar_reference<M: PreparePlanarReference + ?Sized>(
224    metric: &mut M,
225    reference: &PlanarView<'_>,
226    opts: EvalOpts<'_>,
227) -> MetricResult<PreparedPlanarReference<M::PlanarPrepared>> {
228    operation(opts, "prepare planar image reference", |opts| {
229        admit(reference, opts)?;
230        let inner = metric.warm_planar_reference(reference, opts).at()?;
231        opts.checkpoint()?;
232        let origin = reference.crop_origin();
233        let planes = reference
234            .planes()
235            .iter()
236            .map(|p| BoundPlane {
237                format: p.format(),
238                size: (p.width(), p.height()),
239                phase: plane_phase(p.format(), origin),
240            })
241            .collect();
242        Ok(PreparedPlanarReference {
243            inner,
244            size: (reference.width(), reference.height()),
245            planes,
246            chroma_siting: reference.chroma_siting(),
247            color: reference.color().cloned(),
248            matrix_coefficients: reference.matrix_coefficients(),
249            range: reference.effective_range(),
250            alpha: reference.effective_alpha(),
251        })
252    })
253}
254
255impl<P: PlanarWarmReference> PlanarWarmReference for PreparedPlanarReference<P> {
256    type Output = P::Output;
257    fn evaluate_planar(
258        &mut self,
259        candidate: &PlanarView<'_>,
260        opts: EvalOpts<'_>,
261    ) -> MetricResult<Self::Output> {
262        self.score(candidate, opts)
263    }
264    fn with_evaluation(
265        &mut self,
266        candidate: &PlanarView<'_>,
267        opts: EvalOpts<'_>,
268        consume: &mut dyn FnMut(EvaluationRef<'_>),
269    ) -> MetricResult<()> {
270        PreparedPlanarReference::with_evaluation(self, candidate, opts, |view| {
271            consume(view);
272            Ok(())
273        })
274    }
275}