Skip to main content

zenpixels_convert/
gainmap.rs

1//! ISO 21496-1 / UltraHDR dual-layer gain-map reconstruction, resampling, orientation,
2//! and extraction.
3//!
4//! Subsumes pure ISO 21496-1 pixel math in `no_std + alloc`, `#![forbid(unsafe_code)]`
5//! with **0-bit `Accelerators::ALL == Accelerators::SCALAR` parity** and
6//! O(width) streaming memory:
7//!
8//! - **Direction-complete ISO 21496-1:** exact `i128` rational headroom ordering supports
9//!   both **Forward** (SDR base → HDR alternate, `H_alt > H_base`) and **Reverse** (HDR base →
10//!   SDR alternate, `H_base > H_alt`) with signed weight, exact [`GainMapTarget::AlternateRendition`]
11//!   / [`GainMapTarget::BaseRendition`] endpoints, and zero-weight identity bypass.
12//! - **Multiple orientation models:**
13//!   - O(1) EXIF passthrough metadata compose via [`DualLayerHdrBuf::compose_orientation`] /
14//!     [`DualLayerHdrView::compose_orientation`] (zero pixel rebake, both layers kept aligned).
15//!   - Whole-image apply policy [`GainMapOrientation`] (`Bake` to upright display pixels,
16//!     `Passthrough` returning `(PixelBuf, Orientation)` with zero transpose via
17//!     [`apply_gain_map_oriented`], or `RequireIdentity`).
18//!   - Coordinated pixel-level dual-layer baking via [`bake_dual_layer_orientation`]
19//!     and [`bake_dual_layer_orientation_after`] keeping `base` and `gain_map` strictly registered.
20//! - **Separable resampling (`zenresize` center-sited math):** [`GainMapResample::Bilinear`],
21//!   [`GainMapResample::Bicubic`], [`GainMapResample::Mitchell`], and [`GainMapResample::Nearest`],
22//!   with cached horizontally-upsampled gain rows and 8-element padded scratch rows so SIMD
23//!   kernels execute **pure SIMD-only loops** with zero scalar tails.
24//! - **Streaming row workers & extraction:** [`GainMapApplier`] for pull/streaming decode
25//!   with fallible row providers, [`GainMapRowExtractor`] for fused row-level encode, and
26//!   [`extract_gain_map_only`] supporting `Box` / `Bilinear` / `Point` downsampling,
27//!   2-pass `content_fit`, 1-ch/3-ch, U8/U16/10-bit/12-bit maps, and optional [`how_far::Pulse`].
28
29use alloc::vec::Vec;
30use core::num::NonZeroU32;
31use how_far::{Complete, PhaseSpec, Pulse, Stages, Total};
32use whereat::At;
33use zenpixels::{
34    AlphaMode, BitPacking, ChannelOrder, ColorSpace, DiffuseWhite, DualLayerHdrBuf,
35    DualLayerHdrView, GainMapChannels, GainMapColorSpace, GainMapComponent, GainMapDirection,
36    GainMapMetadata, HdrMetadata, Orientation, PixelBuf, PixelFormat, PixelSink, PixelSource,
37    PixelView, Primaries, SampleClaims, SampleLayout, SampleType, SignalRange, SignedFraction,
38    Transfer, UnsignedFraction,
39};
40
41use crate::accelerators::{self, Accelerators};
42use crate::error::{ConvertError, err_at};
43use crate::gainmap_simd::{
44    MAX_LOG2_GAIN, blend_rows_2_scalar, blend_rows_4_scalar, combine_linear_f32_scalar,
45    decode_gain_1ch_scalar, exp2_gain_scalar,
46};
47use crate::orient;
48use crate::plan::RowPlan;
49use crate::policy::{AlphaPolicy, ConvertPolicy};
50use crate::pulse::{check_pulse, is_stop_at, live_pulse, step_pulse};
51
52/// Minimum log₂ span (`1/16` stop) enforced by content-fitted extraction grids so uniform
53/// images never degenerate to a zero-width quantization range.
54pub const CONTENT_FIT_MIN_SPAN_STOPS: f32 = 1.0 / 16.0;
55
56/// Maximum resampling kernel taps allowed in [`GainMapApplier`] (covers unlimited upscaling
57/// and up to 32× Bilinear / 16× Bicubic gain-map downscaling while preventing cache DoS).
58const MAX_APPLY_RESAMPLE_TAPS: usize = 64;
59
60/// Maximum resampling kernel taps allowed in [`extract_gain_map_only`] (`GainMapDownsample::Bilinear`,
61/// covering every valid `scale_factor: u8` `1..=255`).
62const MAX_EXTRACT_RESAMPLE_TAPS: usize = 512;
63
64const INV_255: f32 = 1.0 / 255.0;
65
66// ---------------------------------------------------------------------------
67// Public math, target, orientation & boost helpers
68// ---------------------------------------------------------------------------
69
70/// Target display headroom or explicit rendition endpoint for ISO 21496-1 reconstruction.
71#[derive(Clone, Copy, Debug, PartialEq)]
72#[non_exhaustive]
73pub enum GainMapTarget {
74    /// Target display HDR headroom in log₂ stops (`0.0` = SDR, `2.0` = 4× HDR, `2.32` ≈ 5×).
75    HeadroomStops(f32),
76    /// Exact full alternate rendition (`signed_weight = +1.0` for Forward, `-1.0` for Reverse),
77    /// immune to floating-point rounding of `metadata.alternate_hdr_headroom()`.
78    AlternateRendition,
79    /// Exact base rendition (`signed_weight = 0.0` identity bypass, skipping gain-map sampling
80    /// and additive offsets completely).
81    BaseRendition,
82}
83
84impl GainMapTarget {
85    /// Compute the signed application weight for this target.
86    ///
87    /// Exact rendition endpoints retain weights of zero (base) and ±1 (alternate).
88    /// Returns `None` when the metadata does not establish a gain-map direction
89    /// or the requested headroom is non-finite.
90    #[inline]
91    #[must_use]
92    pub fn signed_weight(self, metadata: &GainMapMetadata) -> Option<f32> {
93        match self {
94            Self::HeadroomStops(stops) => signed_weight(metadata, stops),
95            Self::BaseRendition => {
96                metadata.direction()?;
97                Some(0.0)
98            }
99            Self::AlternateRendition => Some(match metadata.direction()? {
100                GainMapDirection::Forward => 1.0,
101                GainMapDirection::Reverse => -1.0,
102            }),
103        }
104    }
105}
106
107/// Policy controlling how pending EXIF [`Orientation`] on a [`DualLayerHdrBuf`] /
108/// [`DualLayerHdrView`] is handled during whole-image gain-map reconstruction.
109#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
110#[non_exhaustive]
111pub enum GainMapOrientation {
112    /// Reconstruct in stored-frame coordinates (preserving exact subsampled gain-map alignment),
113    /// then physically apply `dual.orientation()` so the returned pixels are display-oriented
114    /// (`Orientation::Identity`). Default.
115    #[default]
116    Bake,
117    /// Reconstruct in stored-frame coordinates with **zero pixel transpose cost**, returning
118    /// the pending `dual.orientation()` alongside the buffer via [`apply_gain_map_oriented`]
119    /// for EXIF passthrough or GPU UV orientation.
120    Passthrough,
121    /// Refuse inputs whose pending orientation is not [`Orientation::Identity`]
122    /// (`ConvertError::UnsupportedRoute`).
123    RequireIdentity,
124}
125
126/// Convert a linear display boost ratio (e.g. `1.0` = SDR, `4.0` = 4× HDR) into
127/// ISO 21496-1 log₂ headroom stops (`0.0` for `<= 1.0` or non-finite).
128#[inline]
129#[must_use]
130pub fn display_boost_to_headroom_stops(display_boost: f32) -> f32 {
131    if !display_boost.is_finite() || display_boost <= 1.0 {
132        0.0
133    } else {
134        libm::log2f(display_boost)
135    }
136}
137
138/// Full-reconstruction display headroom in log₂ stops (`metadata.alternate_hdr_headroom()`).
139///
140/// Note: for guaranteed exact full alternate reconstruction (`|weight| == 1.0`) even when
141/// `alternate_hdr_headroom` is not exactly representable in `f32`, prefer
142/// [`GainMapApplyConfig::alternate_rendition`] / [`GainMapTarget::AlternateRendition`].
143#[inline]
144#[must_use]
145pub fn full_reconstruction_headroom_stops(metadata: &GainMapMetadata) -> f32 {
146    metadata.alternate_hdr_headroom().to_f32()
147}
148
149/// Compute the ISO 21496-1 signed application weight for `display_headroom_stops` using
150/// exact `i128` rational cross-products (never divides by zero or yields `NaN` on close
151/// valid rationals):
152///
153/// - Returns `None` if `display_headroom_stops` is non-finite or `H_base == H_alt`.
154/// - Returns `0.0` at or beyond the base endpoint (`amount == 0.0`), signaling exact
155///   base-rendition identity bypass.
156/// - Returns `sign(H_alt - H_base) * clamp((H - H_base) / (H_alt - H_base), 0, 1)`
157///   (`+amount` for Forward SDR→HDR, `-amount` for Reverse HDR→SDR).
158#[inline]
159#[must_use]
160pub fn signed_weight(metadata: &GainMapMetadata, display_headroom_stops: f32) -> Option<f32> {
161    if !display_headroom_stops.is_finite() {
162        return None;
163    }
164    let direction = metadata.direction()?;
165    let base = metadata.base_hdr_headroom();
166    let alternate = metadata.alternate_hdr_headroom();
167    let hb_n = i128::from(base.numerator);
168    let hb_d = i128::from(base.denominator.get());
169    let ha_n = i128::from(alternate.numerator);
170    let ha_d = i128::from(alternate.denominator.get());
171
172    // Exact non-zero numerator of (H_alt - H_base) * (hb_d * ha_d):
173    //   (H - hb_n/hb_d) / (ha_n/ha_d - hb_n/hb_d)
174    // = ((H * hb_d - hb_n) * ha_d) / (ha_n * hb_d - hb_n * ha_d)
175    let span_num = ha_n * hb_d - hb_n * ha_d;
176    if span_num == 0 {
177        return None;
178    }
179    let num = (f64::from(display_headroom_stops) * (hb_d as f64) - (hb_n as f64)) * (ha_d as f64);
180    let amount = (num / (span_num as f64)).clamp(0.0, 1.0) as f32;
181    if amount == 0.0 {
182        return Some(0.0);
183    }
184    Some(match direction {
185        GainMapDirection::Forward => amount,
186        GainMapDirection::Reverse => -amount,
187    })
188}
189
190/// Compute a target's signed application weight. See [`GainMapTarget::signed_weight`].
191#[inline]
192#[must_use]
193pub fn signed_weight_for_target(metadata: &GainMapMetadata, target: GainMapTarget) -> Option<f32> {
194    target.signed_weight(metadata)
195}
196
197// ---------------------------------------------------------------------------
198// Exact rational encoding helpers (dynamic denominator, zero silent clamp)
199// ---------------------------------------------------------------------------
200
201#[inline(never)]
202fn signed_fraction_from_f32(v: f32) -> SignedFraction {
203    let v = if v.is_finite() { v } else { 0.0 };
204    if v == 0.0 {
205        return SignedFraction::ZERO;
206    }
207    let vf = f64::from(v);
208    for den in [1u32, 2, 4, 8, 16, 32, 64, 128, 256, 1024] {
209        let scaled = vf * f64::from(den);
210        let rounded = libm::round(scaled);
211        if (scaled - rounded).abs() <= 1e-7
212            && rounded >= f64::from(i32::MIN)
213            && rounded <= f64::from(i32::MAX)
214        {
215            return SignedFraction::new(rounded as i32, NonZeroU32::new(den).unwrap());
216        }
217    }
218    for den in [1_000_000u32, 100_000, 10_000, 1_000, 100, 10, 1] {
219        let max_abs = (i32::MAX as f64) / f64::from(den);
220        if vf.abs() <= max_abs || den == 1 {
221            let clamped = vf.clamp(-max_abs, max_abs);
222            return SignedFraction::new(
223                libm::round(clamped * f64::from(den)) as i32,
224                NonZeroU32::new(den).unwrap(),
225            );
226        }
227    }
228    SignedFraction::ZERO
229}
230
231#[inline(never)]
232fn unsigned_fraction_from_f32(v: f32) -> UnsignedFraction {
233    let v = if v.is_finite() && v > 0.0 { v } else { 0.0 };
234    if v == 0.0 {
235        return UnsignedFraction::ZERO;
236    }
237    let vf = f64::from(v);
238    for den in [1u32, 2, 4, 8, 16, 32, 64, 128, 256, 1024] {
239        let scaled = vf * f64::from(den);
240        let rounded = libm::round(scaled);
241        if (scaled - rounded).abs() <= 1e-7 && rounded >= 0.0 && rounded <= f64::from(u32::MAX) {
242            return UnsignedFraction::new(rounded as u32, NonZeroU32::new(den).unwrap());
243        }
244    }
245    for den in [1_000_000u32, 100_000, 10_000, 1_000, 100, 10, 1] {
246        let max_val = (u32::MAX as f64) / f64::from(den);
247        if vf <= max_val || den == 1 {
248            let clamped = vf.clamp(0.0, max_val);
249            return UnsignedFraction::new(
250                libm::round(clamped * f64::from(den)) as u32,
251                NonZeroU32::new(den).unwrap(),
252            );
253        }
254    }
255    UnsignedFraction::ZERO
256}
257
258#[inline(never)]
259fn alloc_f32(n: usize) -> Result<Vec<f32>, At<ConvertError>> {
260    let mut v = Vec::new();
261    v.try_reserve_exact(n)
262        .map_err(|_| err_at(ConvertError::AllocationFailed))?;
263    v.resize(n, 0.0f32);
264    Ok(v)
265}
266
267#[inline]
268fn color_alpha_mode(color: &ColorSpace) -> AlphaMode {
269    match *color {
270        ColorSpace::Rgb { alpha, .. }
271        | ColorSpace::RgbCustom { alpha, .. }
272        | ColorSpace::Gray { alpha, .. }
273        | ColorSpace::Icc { alpha, .. } => alpha,
274        _ => AlphaMode::None,
275    }
276}
277
278#[inline]
279fn is_valid_gain_map_order(order: ChannelOrder) -> bool {
280    matches!(
281        order,
282        ChannelOrder::Gray
283            | ChannelOrder::Rgb
284            | ChannelOrder::Generic(1)
285            | ChannelOrder::Generic(3)
286    )
287}
288
289// ---------------------------------------------------------------------------
290// Separable 1D resampling weight table (zenresize pixel-center siting)
291// ---------------------------------------------------------------------------
292
293/// Resampling filter used when the gain map resolution differs from the base image.
294///
295/// Resampling is performed on **encoded gain-map samples `[0, 1]`** before applying
296/// `gamma` and `exp2`, matching ISO 21496-1 / Android Ultra HDR / `libavif`.
297#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
298#[non_exhaustive]
299pub enum GainMapResample {
300    /// Nearest-neighbor (1-tap box). Fastest; useful for preview/diagnostics or 1:1 maps.
301    Nearest,
302    /// Separable bilinear / triangle filter (2-tap upsample). ISO 21496-1 & Android Ultra HDR
303    /// baseline; zero overshoot.
304    #[default]
305    Bilinear,
306    /// Separable Catmull-Rom bicubic spline (`B=0, C=0.5`, 4-tap upsample, clamped to `[0, 1]`).
307    /// Sharper transition edges on subsampled gain maps.
308    Bicubic,
309    /// Separable Mitchell-Netravali cubic (`B=1/3, C=1/3`, 4-tap upsample, clamped to `[0, 1]`).
310    /// Balanced sharpness with minimal ringing (~1.3% negative lobe vs ~6.5% for Catmull-Rom).
311    Mitchell,
312}
313
314#[inline]
315fn eval_cubic(x: f64, b: f64, c: f64) -> f64 {
316    let ax = if x < 0.0 { -x } else { x };
317    if ax < 1.0 {
318        let p3 = (12.0 - 9.0 * b - 6.0 * c) / 6.0;
319        let p2 = (-18.0 + 12.0 * b + 6.0 * c) / 6.0;
320        let p0 = (6.0 - 2.0 * b) / 6.0;
321        (p3 * ax + p2) * ax * ax + p0
322    } else if ax < 2.0 {
323        let q3 = (-b - 6.0 * c) / 6.0;
324        let q2 = (6.0 * b + 30.0 * c) / 6.0;
325        let q1 = (-12.0 * b - 48.0 * c) / 6.0;
326        let q0 = (8.0 * b + 24.0 * c) / 6.0;
327        ((q3 * ax + q2) * ax + q1) * ax + q0
328    } else {
329        0.0
330    }
331}
332
333#[inline]
334fn eval_resample_kernel(mode: GainMapResample, x: f64) -> f64 {
335    match mode {
336        GainMapResample::Nearest => {
337            let ax = if x < 0.0 { -x } else { x };
338            if ax <= 0.5 { 1.0 } else { 0.0 }
339        }
340        GainMapResample::Bilinear => {
341            let ax = if x < 0.0 { -x } else { x };
342            if ax < 1.0 { 1.0 - ax } else { 0.0 }
343        }
344        GainMapResample::Bicubic => eval_cubic(x, 0.0, 0.5),
345        GainMapResample::Mitchell => eval_cubic(x, 1.0 / 3.0, 1.0 / 3.0),
346    }
347}
348
349/// Precomputed 1D separable resampling weights using `zenresize` pixel-center siting:
350/// `center = (out + 0.5) / scale - 0.5`, edge-clamped before kernel evaluation and
351/// normalized to exact unit sum. Single flat `weights_flat` allocation (zero `Vec<Vec<_>>`).
352#[derive(Clone, Debug)]
353struct AxisWeights {
354    left: Vec<u32>,
355    tap_counts: Vec<u16>,
356    weights_flat: Vec<f32>,
357    weights_stride: usize,
358    max_taps: usize,
359}
360
361/// Compute exact trimmed nonzero resampling taps for a single output coordinate `o` on stack
362/// (`0` heap allocations). Only rejects with `UnsupportedRoute` if the **actual** trimmed nonzero
363/// tap count exceeds `max_allowed_taps` (fixes B30: 128→4 bilinear has 64 actual taps and succeeds!).
364#[inline]
365fn compute_axis_taps_stack(
366    in_size: u32,
367    out_size: u32,
368    mode: GainMapResample,
369    o: u32,
370    max_allowed_taps: usize,
371    out_weights: &mut [f32; MAX_APPLY_RESAMPLE_TAPS],
372) -> Result<(u32, usize), ConvertError> {
373    const WEIGHT_EPS: f64 = 2e-8;
374    if in_size == 0 || out_size == 0 {
375        return Err(ConvertError::DimensionMismatch);
376    }
377    let max_in = i64::from(in_size - 1);
378    if mode == GainMapResample::Nearest {
379        let ratio = f64::from(in_size) / f64::from(out_size);
380        let idx = (libm::floor((f64::from(o) + 0.5) * ratio) as i64).clamp(0, max_in) as u32;
381        out_weights[0] = 1.0;
382        return Ok((idx, 1));
383    }
384
385    let scale = f64::from(out_size) / f64::from(in_size);
386    let downscale = scale.min(1.0);
387    let base_win = match mode {
388        GainMapResample::Bilinear => 1.0,
389        GainMapResample::Bicubic | GainMapResample::Mitchell => 2.0,
390        GainMapResample::Nearest => 0.5,
391    };
392    let eff_window = base_win / downscale;
393    // Fast conservative reject only when even the strict interior support exceeds budget.
394    if (2.0 * eff_window) > (max_allowed_taps as f64) + 2.0
395        && u64::from(in_size) > max_allowed_taps as u64
396    {
397        return Err(ConvertError::UnsupportedRoute);
398    }
399
400    let center = (f64::from(o) + 0.5) / scale - 0.5;
401    let lp = (libm::ceil(center - eff_window - 1e-4) as i64).max(0);
402    let rp = (libm::floor(center + eff_window + 1e-4) as i64).min(max_in);
403
404    // Collect nonzero weights on stack, trimming leading/trailing exact zeros before checking count.
405    let mut tmp = [0.0f64; MAX_APPLY_RESAMPLE_TAPS + 6];
406    let mut len = 0usize;
407    let mut total = 0.0f64;
408    let mut trimmed_left = lp.min(max_in) as u32;
409    let mut seen_nonzero = false;
410
411    if lp <= rp {
412        let mut inp = lp;
413        while inp <= rp {
414            let x = downscale * ((inp as f64) - center);
415            let mut w = eval_resample_kernel(mode, x);
416            if w.abs() <= WEIGHT_EPS {
417                w = 0.0;
418            }
419            if !seen_nonzero {
420                if w == 0.0 {
421                    trimmed_left += 1;
422                    inp += 1;
423                    continue;
424                }
425                seen_nonzero = true;
426            }
427            if len >= tmp.len() {
428                return Err(ConvertError::UnsupportedRoute);
429            }
430            tmp[len] = w;
431            len += 1;
432            total += w;
433            inp += 1;
434        }
435        while len > 0 && tmp[len - 1] == 0.0 {
436            len -= 1;
437        }
438        if total != 0.0 && len > 0 {
439            let inv = 1.0 / total;
440            for w in &mut tmp[..len] {
441                *w *= inv;
442            }
443        } else {
444            len = 0;
445        }
446    }
447
448    if len == 0 {
449        let nearest = (libm::round(center) as i64).clamp(0, max_in) as u32;
450        out_weights[0] = 1.0;
451        return Ok((nearest, 1));
452    }
453    if len > max_allowed_taps {
454        return Err(ConvertError::UnsupportedRoute);
455    }
456    let mut sum = 0.0f32;
457    for j in 0..len {
458        let wf = tmp[j] as f32;
459        out_weights[j] = wf;
460        sum += wf;
461    }
462    if sum != 0.0 {
463        let inv = 1.0f32 / sum;
464        for v in &mut out_weights[..len] {
465            *v *= inv;
466        }
467    }
468    Ok((trimmed_left, len))
469}
470
471/// Probe exact maximum vertical tap count across `0..out_size` in **O(1) stack memory**
472/// (zero heap allocation, independent of image height — B30).
473fn probe_max_axis_taps(
474    in_size: u32,
475    out_size: u32,
476    mode: GainMapResample,
477    max_allowed_taps: usize,
478) -> Result<usize, ConvertError> {
479    if in_size == 0 || out_size == 0 {
480        return Err(ConvertError::DimensionMismatch);
481    }
482    if mode == GainMapResample::Nearest {
483        return Ok(1);
484    }
485    let mut ws = [0.0f32; MAX_APPLY_RESAMPLE_TAPS];
486    let mut max_taps = 1usize;
487    for o in 0..out_size {
488        let (_, count) =
489            compute_axis_taps_stack(in_size, out_size, mode, o, max_allowed_taps, &mut ws)?;
490        max_taps = max_taps.max(count);
491    }
492    Ok(max_taps)
493}
494
495impl AxisWeights {
496    #[inline(never)]
497    fn try_new(
498        in_size: u32,
499        out_size: u32,
500        mode: GainMapResample,
501        max_allowed_taps: usize,
502    ) -> Result<Self, ConvertError> {
503        if in_size == 0 || out_size == 0 {
504            return Err(ConvertError::DimensionMismatch);
505        }
506        let out_n = out_size as usize;
507
508        let mut left = Vec::new();
509        left.try_reserve_exact(out_n)
510            .map_err(|_| ConvertError::AllocationFailed)?;
511
512        if mode == GainMapResample::Nearest {
513            let ratio = f64::from(in_size) / f64::from(out_size);
514            let max_in = i64::from(in_size - 1);
515            for o in 0..out_size {
516                let idx =
517                    (libm::floor((f64::from(o) + 0.5) * ratio) as i64).clamp(0, max_in) as u32;
518                left.push(idx);
519            }
520            return Ok(Self {
521                left,
522                tap_counts: Vec::new(),
523                weights_flat: Vec::new(),
524                weights_stride: 1,
525                max_taps: 1,
526            });
527        }
528
529        // First pass (zero heap alloc): measure exact max_taps and reject only if actual > max_allowed_taps!
530        let max_taps = probe_max_axis_taps(in_size, out_size, mode, max_allowed_taps)?;
531        let weights_stride = max_taps.max(1);
532
533        let mut tap_counts = Vec::new();
534        tap_counts
535            .try_reserve_exact(out_n)
536            .map_err(|_| ConvertError::AllocationFailed)?;
537        let flat_len = out_n
538            .checked_mul(weights_stride)
539            .ok_or(ConvertError::AllocationFailed)?;
540        let mut weights_flat = Vec::new();
541        weights_flat
542            .try_reserve_exact(flat_len)
543            .map_err(|_| ConvertError::AllocationFailed)?;
544        weights_flat.resize(flat_len, 0.0f32);
545
546        let mut ws = [0.0f32; MAX_APPLY_RESAMPLE_TAPS];
547        for o in 0..out_size {
548            let (l, count) =
549                compute_axis_taps_stack(in_size, out_size, mode, o, max_allowed_taps, &mut ws)?;
550            left.push(l);
551            tap_counts.push(count as u16);
552            let off = (o as usize) * weights_stride;
553            weights_flat[off..off + count].copy_from_slice(&ws[..count]);
554        }
555
556        Ok(Self {
557            left,
558            tap_counts,
559            weights_flat,
560            weights_stride,
561            max_taps,
562        })
563    }
564
565    #[inline(always)]
566    fn taps(&self, out_idx: usize) -> (u32, &[f32]) {
567        if self.tap_counts.is_empty() {
568            static ONE: [f32; 1] = [1.0];
569            return (self.left[out_idx], &ONE);
570        }
571        let count = usize::from(self.tap_counts[out_idx]);
572        let off = out_idx * self.weights_stride;
573        (self.left[out_idx], &self.weights_flat[off..off + count])
574    }
575}
576
577// ---------------------------------------------------------------------------
578// Apply configuration & streaming GainMapApplier
579// ---------------------------------------------------------------------------
580
581/// Configuration for ISO 21496-1 gain-map reconstruction via [`GainMapApplier`],
582/// [`apply_gain_map_oriented`], or [`apply_gain_map_with`].
583#[derive(Clone, Debug)]
584#[non_exhaustive]
585pub struct GainMapApplyConfig {
586    /// Target display HDR headroom in log₂ stops or explicit rendition endpoint.
587    pub target: GainMapTarget,
588    /// Resampling kernel used when gain-map dimensions differ from base dimensions.
589    pub resample: GainMapResample,
590    /// Pending EXIF orientation policy (`Bake`, `Passthrough`, or `RequireIdentity`).
591    pub orientation: GainMapOrientation,
592    /// Conversion policy controlling SIMD [`Accelerators`], `diffuse_white`, and CMS backends.
593    ///
594    /// Defaults to [`ConvertPolicy::working_linear`] (`accelerators: None`, respecting the
595    /// process-wide `accel::enable*` registry or scalar fallback for dead-stripping); override
596    /// via [`with_policy`](Self::with_policy) (e.g. `Accelerators::ALL.with_gainmap()` or
597    /// `Accelerators::WEB_SDR.with_gainmap()`).
598    pub policy: ConvertPolicy,
599    /// Optional target output [`PixelFormat`].
600    ///
601    /// - `None`: outputs relative-linear `RGBF32` (or `RGBAF32` when base has alpha) in the
602    ///   resolved gain-map application primaries.
603    /// - `Some(spec)`: fuses conversion directly to `spec` (e.g. `RGBAF16`, `RGB16` PQ,
604    ///   `RGB16` HLG, `RGBA8` sRGB, `DisplayP3`) in O(width) row memory with zero full-frame
605    ///   intermediate buffer.
606    pub destination_format: Option<PixelFormat>,
607}
608
609impl GainMapApplyConfig {
610    /// Create a default configuration for `display_headroom_stops` (log₂ stops, e.g. `2.0` = 4× display boost).
611    #[inline(always)]
612    #[must_use]
613    pub fn from_headroom_stops(display_headroom_stops: f32) -> Self {
614        Self::with_target_default(GainMapTarget::HeadroomStops(display_headroom_stops))
615    }
616
617    /// Create a configuration from a **linear** display boost multiplier (e.g. `4.0` → `2.0` stops).
618    #[inline(always)]
619    #[must_use]
620    pub fn from_display_boost_linear(display_boost: f32) -> Self {
621        Self::from_headroom_stops(display_boost_to_headroom_stops(display_boost))
622    }
623
624    /// Create a configuration targeting exact full alternate reconstruction (`|weight| == 1.0`).
625    #[inline(always)]
626    #[must_use]
627    pub fn alternate_rendition() -> Self {
628        Self::with_target_default(GainMapTarget::AlternateRendition)
629    }
630
631    /// Create a configuration targeting exact base rendition bypass (`weight == 0.0`).
632    #[inline(always)]
633    #[must_use]
634    pub fn base_rendition() -> Self {
635        Self::with_target_default(GainMapTarget::BaseRendition)
636    }
637
638    #[inline(always)]
639    fn with_target_default(target: GainMapTarget) -> Self {
640        Self {
641            target,
642            resample: GainMapResample::Bilinear,
643            orientation: GainMapOrientation::Bake,
644            policy: ConvertPolicy::working_linear(),
645            destination_format: None,
646        }
647    }
648
649    /// Replace the target headroom / rendition endpoint.
650    #[inline(always)]
651    #[must_use]
652    pub fn with_target(mut self, target: GainMapTarget) -> Self {
653        self.target = target;
654        self
655    }
656
657    /// Select the gain-map resampling filter (`Bilinear`, `Bicubic`, `Mitchell`, `Nearest`).
658    #[inline(always)]
659    #[must_use]
660    pub fn with_resample(mut self, resample: GainMapResample) -> Self {
661        self.resample = resample;
662        self
663    }
664
665    /// Select how pending EXIF orientation on [`DualLayerHdrBuf`] / [`DualLayerHdrView`] is handled.
666    #[inline(always)]
667    #[must_use]
668    pub fn with_orientation(mut self, orientation: GainMapOrientation) -> Self {
669        self.orientation = orientation;
670        self
671    }
672
673    /// Set the conversion policy (accelerators, `diffuse_white`, CMS backend, HLG rendering).
674    #[inline(always)]
675    #[must_use]
676    pub fn with_policy(mut self, policy: ConvertPolicy) -> Self {
677        self.policy = policy;
678        self
679    }
680
681    /// Fuse row conversion straight into `destination_format` (e.g. `RGBAF16`, `RGB16` PQ, `RGBA8` sRGB).
682    #[inline(always)]
683    #[must_use]
684    pub fn with_destination_format(mut self, destination_format: PixelFormat) -> Self {
685        self.destination_format = Some(destination_format);
686        self
687    }
688}
689
690/// Reusable, O(width)-memory, row-streaming ISO 21496-1 gain-map reconstructor.
691///
692/// Operates in stored-frame coordinates (`base_w × base_h`) and exposes [`pending_orientation`](Self::pending_orientation)
693/// so streaming callers can pass pending EXIF orientation through or bake it after decode.
694/// All internal scratch rows are padded to a multiple of 8 (`w_pad`), allowing SIMD vertical
695/// blend, `exp2` gain decode, and linear RGB(A) combine kernels to run **pure SIMD-only loops**.
696#[derive(Clone, Debug)]
697pub struct GainMapApplier {
698    base_spec: PixelFormat,
699    base_w: u32,
700    base_h: u32,
701    w_pad: usize,
702    base_row_bytes: usize,
703    gm_w: u32,
704    gm_h: u32,
705    gm_spec: PixelFormat,
706    gm_row_bytes: usize,
707    gm_ch: usize,
708    gm_max: [f32; 3],
709    has_alpha: bool,
710    destination_format: PixelFormat,
711    dst_row_bytes: usize,
712    orientation: Orientation,
713    accel: Accelerators,
714
715    signed_weight: f32,
716    is_zero_weight: bool,
717    same_size: bool,
718    resample: GainMapResample,
719    shared_meta: bool,
720
721    base_w_g: [f32; 3],
722    slope_w_g: [f32; 3],
723    inv_gamma: [f32; 3],
724    k_base: [f32; 3],
725    k_alt: [f32; 3],
726
727    /// Exact 256-entry gain LUT used when gain map is full-packing U8 and 1:1 or `Nearest`.
728    u8_gain_lut: Option<[[f32; 256]; 3]>,
729
730    base_to_app: RowPlan,
731    app_to_dst: Option<RowPlan>,
732    zero_weight_direct: Option<RowPlan>,
733
734    h_weights: Option<AxisWeights>,
735    /// Cached gain-map row index per slot (`u32::MAX` = empty/invalid).
736    cache_gm_y: Vec<u32>,
737    /// Flat cache storage: `[slot * gm_ch * w_pad + c * w_pad .. +w_pad]`, lanes `w..w_pad` zeroed.
738    cache_planes: Vec<f32>,
739    cache_cursor: usize,
740    v_slot_indices: Vec<usize>,
741
742    // Flat O(w_pad) row scratch buffers (all multiples of 8 elements)
743    base_lin_row: Vec<f32>,
744    out_lin_row: Vec<f32>,
745    gm_decode_scratch: Vec<f32>,
746    /// Flat vertically-blended gain samples: `[c * w_pad .. (c + 1) * w_pad]`.
747    v_blend: Vec<f32>,
748    /// Padded scratch for SIMD `gamma_pow` when `inv_gamma != 1.0` (`0` bytes when `gamma == 1.0`).
749    gamma_tmp: Vec<f32>,
750    /// Flat linear gain multipliers: `[c * w_pad .. (c + 1) * w_pad]`.
751    gains: Vec<f32>,
752}
753
754#[inline(never)]
755fn build_u8_gain_lut(
756    base_w_g: [f32; 3],
757    slope_w_g: [f32; 3],
758    inv_gamma: [f32; 3],
759) -> [[f32; 256]; 3] {
760    let mut lut = [[1.0f32; 256]; 3];
761    for c in 0..3 {
762        let unit_gamma = (inv_gamma[c] - 1.0).abs() < 1e-7;
763        for (i, slot) in lut[c].iter_mut().enumerate() {
764            let s = f32::from(i as u8) * INV_255;
765            let g = if unit_gamma || i == 0 || i == 255 {
766                s
767            } else {
768                libm::powf(s, inv_gamma[c])
769            };
770            let lg = base_w_g[c] + slope_w_g[c] * g;
771            *slot = exp2_gain_scalar(lg);
772        }
773    }
774    lut
775}
776
777#[cold]
778#[inline(never)]
779fn decode_gain_gamma_scalar(
780    samples: &[f32],
781    w: usize,
782    inv_gamma: f32,
783    base_w: f32,
784    slope_w: f32,
785    out_gains: &mut [f32],
786) {
787    for i in 0..w {
788        let raw = samples[i];
789        let s = if raw > 0.0 {
790            if raw < 1.0 { raw } else { 1.0 }
791        } else {
792            0.0
793        };
794        let g = if s == 0.0 || s == 1.0 {
795            s
796        } else {
797            libm::powf(s, inv_gamma)
798        };
799        out_gains[i] = exp2_gain_scalar(base_w + slope_w * g);
800    }
801}
802
803#[cold]
804#[inline(never)]
805fn blend_rows_general(
806    cache_planes: &[f32],
807    slot_stride: usize,
808    ch_off: usize,
809    slots: &[usize],
810    ws: &[f32],
811    w: usize,
812    dst: &mut [f32],
813) {
814    dst[..w].fill(0.0);
815    for (t, &wt) in ws.iter().enumerate() {
816        let base = slots[t] * slot_stride + ch_off;
817        let sr = &cache_planes[base..base + w];
818        for (o, &v) in dst[..w].iter_mut().zip(sr.iter()) {
819            *o += v * wt;
820        }
821    }
822    for o in &mut dst[..w] {
823        *o = if *o > 0.0 {
824            if *o < 1.0 { *o } else { 1.0 }
825        } else {
826            0.0
827        };
828    }
829}
830
831struct ApplierScratch {
832    cache_gm_y: Vec<u32>,
833    cache_planes: Vec<f32>,
834    v_slot_indices: Vec<usize>,
835    base_lin_row: Vec<f32>,
836    out_lin_row: Vec<f32>,
837    gm_decode_scratch: Vec<f32>,
838    v_blend: Vec<f32>,
839    gains: Vec<f32>,
840}
841
842#[inline(never)]
843#[allow(clippy::too_many_arguments)]
844fn alloc_applier_scratch(
845    w_pad: usize,
846    ch: usize,
847    gm_w: usize,
848    gm_ch: usize,
849    gains_ch: usize,
850    cache_slots: usize,
851    need_base_lin: bool,
852    need_out_lin: bool,
853    need_gm_decode: bool,
854    need_v_blend: bool,
855    need_gains: bool,
856) -> Result<ApplierScratch, At<ConvertError>> {
857    let row_floats_pad = w_pad
858        .checked_mul(ch)
859        .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
860    let base_lin_row = if need_base_lin {
861        alloc_f32(row_floats_pad)?
862    } else {
863        Vec::new()
864    };
865    let out_lin_row = if need_out_lin {
866        alloc_f32(row_floats_pad)?
867    } else {
868        Vec::new()
869    };
870    let gm_decode_scratch = if need_gm_decode {
871        let len = gm_w
872            .checked_mul(gm_ch)
873            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
874        alloc_f32(len)?
875    } else {
876        Vec::new()
877    };
878
879    let mut cache_gm_y = Vec::new();
880    let mut cache_planes = Vec::new();
881    let mut v_slot_indices = Vec::new();
882    if cache_slots > 0 {
883        let total = cache_slots
884            .checked_mul(gm_ch)
885            .and_then(|v| v.checked_mul(w_pad))
886            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
887        cache_gm_y
888            .try_reserve_exact(cache_slots)
889            .map_err(|_| err_at(ConvertError::AllocationFailed))?;
890        cache_gm_y.resize(cache_slots, u32::MAX);
891        cache_planes = alloc_f32(total)?;
892        v_slot_indices
893            .try_reserve_exact(cache_slots)
894            .map_err(|_| err_at(ConvertError::AllocationFailed))?;
895        v_slot_indices.resize(cache_slots, 0);
896    }
897
898    let v_blend = if need_v_blend {
899        let len = gm_ch
900            .checked_mul(w_pad)
901            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
902        alloc_f32(len)?
903    } else {
904        Vec::new()
905    };
906    let gains = if need_gains {
907        let len = gains_ch
908            .checked_mul(w_pad)
909            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
910        alloc_f32(len)?
911    } else {
912        Vec::new()
913    };
914
915    Ok(ApplierScratch {
916        cache_gm_y,
917        cache_planes,
918        v_slot_indices,
919        base_lin_row,
920        out_lin_row,
921        gm_decode_scratch,
922        v_blend,
923        gains,
924    })
925}
926
927/// Layer format and stored pixel dimensions passed to [`GainMapApplier::new`].
928#[derive(Clone, Debug, PartialEq, Eq)]
929pub struct GainMapLayer {
930    /// Pixel format of this layer (`layout` + `color`).
931    pub format: PixelFormat,
932    /// Layer width in pixels.
933    pub width: u32,
934    /// Layer height in rows.
935    pub height: u32,
936}
937
938impl GainMapLayer {
939    /// Construct a layer descriptor from `(format, width, height)`.
940    #[inline]
941    #[must_use]
942    pub const fn new(format: PixelFormat, width: u32, height: u32) -> Self {
943        Self {
944            format,
945            width,
946            height,
947        }
948    }
949}
950
951impl GainMapApplier {
952    /// Construct a streaming applier directly from a validated [`DualLayerHdrView`].
953    ///
954    /// Rejects non-`Identity` orientation when `config.orientation == GainMapOrientation::RequireIdentity`.
955    pub fn for_view(
956        dual: &DualLayerHdrView<'_>,
957        config: &GainMapApplyConfig,
958    ) -> Result<Self, At<ConvertError>> {
959        if config.orientation == GainMapOrientation::RequireIdentity
960            && dual.orientation() != Orientation::Identity
961        {
962            return Err(err_at(ConvertError::UnsupportedRoute));
963        }
964        let mut applier = Self::new(
965            GainMapLayer::new(
966                dual.base().format().clone(),
967                dual.base().width(),
968                dual.base().height(),
969            ),
970            GainMapLayer::new(
971                dual.gain_map().format().clone(),
972                dual.gain_map().width(),
973                dual.gain_map().height(),
974            ),
975            dual.metadata(),
976            dual.alternate_color_space(),
977            config,
978        )?;
979        applier.orientation = dual.orientation();
980        Ok(applier)
981    }
982
983    /// Construct a streaming applier from explicit base and gain-map layer descriptors and metadata.
984    #[inline(never)]
985    pub fn new(
986        base: GainMapLayer,
987        gain_map: GainMapLayer,
988        metadata: GainMapMetadata,
989        alternate_color_space: Option<&ColorSpace>,
990        config: &GainMapApplyConfig,
991    ) -> Result<Self, At<ConvertError>> {
992        let GainMapLayer {
993            format: base_spec,
994            width: base_w,
995            height: base_h,
996        } = base;
997        let GainMapLayer {
998            format: gm_spec,
999            width: gm_w,
1000            height: gm_h,
1001        } = gain_map;
1002        // Phase 1: Pure validation & scalar math BEFORE allocating any `Vec` or `RowPlan`
1003        // (eliminates per-`?` drop-glue ladders for `RowPlan` & scratch vectors).
1004        if base_w == 0 || base_h == 0 || gm_w == 0 || gm_h == 0 {
1005            return Err(err_at(ConvertError::DimensionMismatch));
1006        }
1007        if !metadata.is_valid() {
1008            return Err(err_at(ConvertError::UnsupportedRoute));
1009        }
1010        let sw = config
1011            .target
1012            .signed_weight(&metadata)
1013            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
1014        validate_gain_map_spec(&gm_spec)?;
1015
1016        let (_, base_white_opt) = resolve_linear_rgb_primaries(base_spec.color())
1017            .unwrap_or((crate::plan::RgbPrimaries::BT709, None));
1018        let base_white = base_white_opt
1019            .or(config.policy.diffuse_white)
1020            .unwrap_or(DiffuseWhite::BT2408);
1021
1022        let app_primaries = if sw == 0.0 {
1023            resolve_linear_rgb_primaries(base_spec.color())
1024                .map(|(p, _)| p)
1025                .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?
1026        } else {
1027            match metadata.application_space() {
1028                GainMapColorSpace::Base => resolve_linear_rgb_primaries(base_spec.color())
1029                    .map(|(p, _)| p)
1030                    .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?,
1031                GainMapColorSpace::Alternate => {
1032                    let alt = alternate_color_space
1033                        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
1034                    resolve_linear_rgb_primaries(alt)
1035                        .map(|(p, _)| p)
1036                        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?
1037                }
1038            }
1039        };
1040
1041        let mut base_w_g = [0.0f32; 3];
1042        let mut slope_w_g = [0.0f32; 3];
1043        let mut inv_gamma = [1.0f32; 3];
1044        let mut k_base = [0.0f32; 3];
1045        let mut k_alt = [0.0f32; 3];
1046        for c in 0..3 {
1047            let comp = metadata.channel(c);
1048            let min_g = comp.min_gain_stops().to_f32();
1049            let span_g = comp.max_gain_stops().to_f32() - min_g;
1050            base_w_g[c] = min_g * sw;
1051            slope_w_g[c] = span_g * sw;
1052            inv_gamma[c] = 1.0 / comp.gamma().to_f32();
1053            k_base[c] = comp.base_offset().to_f32();
1054            k_alt[c] = comp.alternate_offset().to_f32();
1055            if !base_w_g[c].is_finite()
1056                || !slope_w_g[c].is_finite()
1057                || !inv_gamma[c].is_finite()
1058                || !k_base[c].is_finite()
1059                || !k_alt[c].is_finite()
1060            {
1061                return Err(err_at(ConvertError::UnsupportedRoute));
1062            }
1063        }
1064
1065        let has_alpha = base_spec.layout().order().has_alpha_slot();
1066        let ch = if has_alpha { 4usize } else { 3usize };
1067        let w_usize = base_w as usize;
1068        let w_pad = w_usize
1069            .checked_next_multiple_of(8)
1070            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
1071        let base_row_bytes = w_usize
1072            .checked_mul(base_spec.layout().bytes_per_pixel())
1073            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
1074        let gm_row_bytes = (gm_w as usize)
1075            .checked_mul(gm_spec.layout().bytes_per_pixel())
1076            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
1077        let dst_bpp = config
1078            .destination_format
1079            .as_ref()
1080            .map_or(ch * 4, |t| t.layout().bytes_per_pixel());
1081        let dst_row_bytes = w_usize
1082            .checked_mul(dst_bpp)
1083            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
1084
1085        let gm_layout = gm_spec.layout();
1086        let gm_ch = gm_layout.channels();
1087        let gm_max = [
1088            gm_layout.packing().max_code(gm_layout.sample(), 0).max(1) as f32,
1089            gm_layout.packing().max_code(gm_layout.sample(), 1).max(1) as f32,
1090            gm_layout.packing().max_code(gm_layout.sample(), 2).max(1) as f32,
1091        ];
1092        let shared_meta = matches!(metadata.channels(), GainMapChannels::Shared(_));
1093        let same_size = base_w == gm_w && base_h == gm_h;
1094        let is_zero_weight = sw == 0.0;
1095        let use_u8_lut = !is_zero_weight
1096            && gm_layout.sample() == SampleType::U8
1097            && gm_layout.packing().is_full()
1098            && (same_size || config.resample == GainMapResample::Nearest);
1099
1100        // Phase 2: Build horizontal resampling weights (O(width)) and probe vertical max taps
1101        // in O(1) stack memory (zero O(height * taps) heap allocation — B30!).
1102        let (h_weights, cache_slots) = if is_zero_weight || same_size {
1103            (None, 0usize)
1104        } else {
1105            let mode = if use_u8_lut {
1106                GainMapResample::Nearest
1107            } else {
1108                config.resample
1109            };
1110            let hw = AxisWeights::try_new(gm_w, base_w, mode, MAX_APPLY_RESAMPLE_TAPS)
1111                .map_err(err_at)?;
1112            let v_max_taps =
1113                probe_max_axis_taps(gm_h, base_h, mode, MAX_APPLY_RESAMPLE_TAPS).map_err(err_at)?;
1114            let slots = if use_u8_lut { 0 } else { v_max_taps.max(1) };
1115            (Some(hw), slots)
1116        };
1117
1118        // Phase 3: Build conversion row plans.
1119        let app_alpha = if !has_alpha {
1120            AlphaMode::None
1121        } else if color_alpha_mode(base_spec.color()) == AlphaMode::Opaque {
1122            AlphaMode::Opaque
1123        } else {
1124            AlphaMode::Straight
1125        };
1126        let app_spec = PixelFormat::new(
1127            if has_alpha {
1128                SampleLayout::RGBAF32
1129            } else {
1130                SampleLayout::RGBF32
1131            },
1132            app_primaries.to_color_space(
1133                Transfer::Linear,
1134                SignalRange::Full,
1135                app_alpha,
1136                Some(base_white),
1137            ),
1138        )
1139        .map_err(|e| err_at((*e.error()).into()))?;
1140        let mut row_pol = config.policy.clone();
1141        row_pol.diffuse_white = Some(base_white);
1142        let accel = accelerators::resolve(row_pol.accelerators);
1143
1144        let base_to_app = RowPlan::build(base_spec.clone(), app_spec.clone(), &row_pol, None)?;
1145        let (destination_format, app_to_dst, zero_weight_direct) =
1146            if let Some(target) = &config.destination_format {
1147                let a2d = RowPlan::build(app_spec, target.clone(), &row_pol, None)?;
1148                let direct = if is_zero_weight {
1149                    RowPlan::build(base_spec.clone(), target.clone(), &row_pol, None).ok()
1150                } else {
1151                    None
1152                };
1153                (target.clone(), Some(a2d), direct)
1154            } else {
1155                (app_spec, None, None)
1156            };
1157
1158        // Phase 4: Single out-of-line flat scratch allocation + optional U8 LUT.
1159        let gains_ch = if gm_ch == 3 || !shared_meta { 3 } else { 1 };
1160        let scratch = alloc_applier_scratch(
1161            w_pad,
1162            ch,
1163            gm_w as usize,
1164            gm_ch,
1165            gains_ch,
1166            cache_slots,
1167            !(is_zero_weight && zero_weight_direct.is_some()),
1168            !is_zero_weight && (app_to_dst.is_some() || w_pad != w_usize),
1169            !is_zero_weight && !use_u8_lut,
1170            !is_zero_weight && !use_u8_lut,
1171            !is_zero_weight,
1172        )?;
1173        let need_gamma_tmp = !is_zero_weight
1174            && !use_u8_lut
1175            && inv_gamma
1176                .iter()
1177                .any(|&g| (g - 1.0).abs() >= 1e-7 && (0.25..=3.0).contains(&g));
1178        let gamma_tmp = if need_gamma_tmp {
1179            alloc_f32(w_pad)?
1180        } else {
1181            Vec::new()
1182        };
1183        let u8_gain_lut = if use_u8_lut {
1184            Some(build_u8_gain_lut(base_w_g, slope_w_g, inv_gamma))
1185        } else {
1186            None
1187        };
1188
1189        Ok(Self {
1190            base_spec,
1191            base_w,
1192            base_h,
1193            w_pad,
1194            base_row_bytes,
1195            gm_w,
1196            gm_h,
1197            gm_spec,
1198            gm_row_bytes,
1199            gm_ch,
1200            gm_max,
1201            has_alpha,
1202            destination_format,
1203            dst_row_bytes,
1204            orientation: Orientation::Identity,
1205            accel,
1206            signed_weight: sw,
1207            is_zero_weight,
1208            same_size,
1209            resample: config.resample,
1210            shared_meta,
1211            base_w_g,
1212            slope_w_g,
1213            inv_gamma,
1214            k_base,
1215            k_alt,
1216            u8_gain_lut,
1217            base_to_app,
1218            app_to_dst,
1219            zero_weight_direct,
1220            h_weights,
1221            cache_gm_y: scratch.cache_gm_y,
1222            cache_planes: scratch.cache_planes,
1223            cache_cursor: 0,
1224            v_slot_indices: scratch.v_slot_indices,
1225            base_lin_row: scratch.base_lin_row,
1226            out_lin_row: scratch.out_lin_row,
1227            gm_decode_scratch: scratch.gm_decode_scratch,
1228            v_blend: scratch.v_blend,
1229            gamma_tmp,
1230            gains: scratch.gains,
1231        })
1232    }
1233
1234    /// Output [`PixelFormat`] produced by this applier (in stored-frame coordinates).
1235    #[inline]
1236    #[must_use]
1237    pub fn destination_format(&self) -> &PixelFormat {
1238        &self.destination_format
1239    }
1240
1241    /// Pending EXIF [`Orientation`] captured from [`DualLayerHdrView`] (`Orientation::Identity`
1242    /// when constructed directly via [`GainMapApplier::new`]).
1243    #[inline]
1244    #[must_use]
1245    #[doc(alias = "orientation")]
1246    pub const fn pending_orientation(&self) -> Orientation {
1247        self.orientation
1248    }
1249
1250    /// Signed ISO 21496-1 application weight (`0.0` = exact base bypass, `>0` = Forward, `<0` = Reverse).
1251    #[inline]
1252    #[must_use]
1253    pub const fn signed_weight(&self) -> f32 {
1254        self.signed_weight
1255    }
1256
1257    /// Whether gain-map sampling and additive offsets are bypassed completely (`signed_weight == 0.0`).
1258    #[inline]
1259    #[must_use]
1260    pub const fn is_zero_weight(&self) -> bool {
1261        self.is_zero_weight
1262    }
1263
1264    /// Clear cached horizontally-upsampled gain rows (call before reusing on a different gain map).
1265    pub fn reset_cache(&mut self) {
1266        self.cache_gm_y.fill(u32::MAX);
1267        self.cache_cursor = 0;
1268    }
1269
1270    /// Reconstruct row `row_index` from `base_row` and a borrowed decoded `gain_map` view into `dst_row`.
1271    pub fn apply_row(
1272        &mut self,
1273        row_index: u32,
1274        base_row: &[u8],
1275        gain_map: &PixelView<'_>,
1276        dst_row: &mut [u8],
1277    ) -> Result<(), At<ConvertError>> {
1278        if gain_map.width() != self.gm_w
1279            || gain_map.height() != self.gm_h
1280            || gain_map.format() != &self.gm_spec
1281        {
1282            return Err(err_at(ConvertError::DimensionMismatch));
1283        }
1284        self.apply_row_dyn(row_index, base_row, &mut |gy| Ok(gain_map.row(gy)), dst_row)
1285    }
1286
1287    /// Reconstruct row `row_index` while lazily pulling gain-map rows `gy` on demand via a fallible
1288    /// `fetch_gm_row` provider.
1289    ///
1290    /// On resampled paths (`Bilinear`, `Bicubic`, `Mitchell`), horizontally-upsampled gain rows
1291    /// are cached across consecutive `row_index` so `fetch_gm_row` is invoked at most once per unique
1292    /// gain-map row during sequential top-to-bottom decode. Short provider rows return
1293    /// `Err(ConvertError::DimensionMismatch)` rather than panicking.
1294    #[inline]
1295    pub fn apply_row_with_provider<'a, F>(
1296        &mut self,
1297        row_index: u32,
1298        base_row: &[u8],
1299        mut fetch_gm_row: F,
1300        dst_row: &mut [u8],
1301    ) -> Result<(), At<ConvertError>>
1302    where
1303        F: FnMut(u32) -> Result<&'a [u8], At<ConvertError>>,
1304    {
1305        self.apply_row_dyn(row_index, base_row, &mut fetch_gm_row, dst_row)
1306    }
1307
1308    #[inline(never)]
1309    fn apply_row_dyn<'a>(
1310        &mut self,
1311        y: u32,
1312        base_row: &[u8],
1313        fetch_gm_row: &mut dyn FnMut(u32) -> Result<&'a [u8], At<ConvertError>>,
1314        dst_row: &mut [u8],
1315    ) -> Result<(), At<ConvertError>> {
1316        if y >= self.base_h
1317            || base_row.len() < self.base_row_bytes
1318            || dst_row.len() < self.dst_row_bytes
1319        {
1320            return Err(err_at(ConvertError::DimensionMismatch));
1321        }
1322        let w = self.base_w;
1323        let w_u = w as usize;
1324        let ch = if self.has_alpha { 4usize } else { 3usize };
1325        let active_lin_bytes = w_u * ch * 4;
1326
1327        // Fast exact identity bypass at zero weight: no gain-map fetch, no offset drift!
1328        if self.is_zero_weight {
1329            if let Some(direct) = &self.zero_weight_direct {
1330                return direct.convert_row_at(y, base_row, dst_row, w);
1331            }
1332            if let Some(a2d) = &self.app_to_dst {
1333                let lin_bytes = &mut bytemuck::cast_slice_mut::<f32, u8>(&mut self.base_lin_row)
1334                    [..active_lin_bytes];
1335                self.base_to_app.convert_row_at(y, base_row, lin_bytes, w)?;
1336                return a2d.convert_row_at(
1337                    y,
1338                    &bytemuck::cast_slice(&self.base_lin_row)[..active_lin_bytes],
1339                    dst_row,
1340                    w,
1341                );
1342            }
1343            return self.base_to_app.convert_row_at(y, base_row, dst_row, w);
1344        }
1345
1346        // 1. Decode base row into linear RGB(A) in application primaries (padding lanes stay 0.0).
1347        {
1348            let lin_bytes = &mut bytemuck::cast_slice_mut::<f32, u8>(&mut self.base_lin_row)
1349                [..active_lin_bytes];
1350            self.base_to_app.convert_row_at(y, base_row, lin_bytes, w)?;
1351        }
1352
1353        // 2. Obtain linear gain multipliers into `self.gains` (padded to `w_pad`).
1354        if let Some(lut) = self.u8_gain_lut {
1355            self.fill_gains_u8_lut(y, &lut, fetch_gm_row)?;
1356        } else {
1357            self.fill_samples_for_row(y, fetch_gm_row)?;
1358            self.decode_samples_to_gains();
1359        }
1360
1361        // 3. Apply ISO 21496-1 gain formula `(base + k_base) * gain - k_alt` on padded `w_pad`.
1362        let w_pad = self.w_pad;
1363        let need_3 = self.gm_ch == 3 || !self.shared_meta;
1364        let gr = &self.gains[0..w_pad];
1365        let gg = if need_3 {
1366            &self.gains[w_pad..2 * w_pad]
1367        } else {
1368            gr
1369        };
1370        let gb = if need_3 {
1371            &self.gains[2 * w_pad..3 * w_pad]
1372        } else {
1373            gr
1374        };
1375
1376        let combine_fn = self
1377            .accel
1378            .gainmap_combine
1379            .unwrap_or(combine_linear_f32_scalar);
1380
1381        if let Some(a2d) = &self.app_to_dst {
1382            combine_fn(
1383                &self.base_lin_row,
1384                gr,
1385                gg,
1386                gb,
1387                self.k_base,
1388                self.k_alt,
1389                self.has_alpha,
1390                &mut self.out_lin_row,
1391            );
1392            a2d.convert_row_at(
1393                y,
1394                &bytemuck::cast_slice(&self.out_lin_row)[..active_lin_bytes],
1395                dst_row,
1396                w,
1397            )?;
1398        } else if w_u == w_pad
1399            && let Ok(dst_f32) =
1400                bytemuck::try_cast_slice_mut::<u8, f32>(&mut dst_row[..self.dst_row_bytes])
1401        {
1402            // Zero-copy aligned fast path (e.g. 4K UHD width 3840 % 8 == 0)!
1403            combine_fn(
1404                &self.base_lin_row,
1405                gr,
1406                gg,
1407                gb,
1408                self.k_base,
1409                self.k_alt,
1410                self.has_alpha,
1411                dst_f32,
1412            );
1413        } else {
1414            // Odd width (w != w_pad) or unaligned dst_row: combine into padded `out_lin_row`.
1415            if self.out_lin_row.len() < self.base_lin_row.len() {
1416                self.out_lin_row = alloc_f32(self.base_lin_row.len())?;
1417            }
1418            combine_fn(
1419                &self.base_lin_row,
1420                gr,
1421                gg,
1422                gb,
1423                self.k_base,
1424                self.k_alt,
1425                self.has_alpha,
1426                &mut self.out_lin_row,
1427            );
1428            dst_row[..self.dst_row_bytes]
1429                .copy_from_slice(&bytemuck::cast_slice(&self.out_lin_row)[..self.dst_row_bytes]);
1430        }
1431
1432        Ok(())
1433    }
1434
1435    /// Stream an entire image from any [`PixelSource`] + borrowed `gain_map` into any
1436    /// [`PixelSink`] (`PixelBuf`, `PixelViewMut`, `BandedBuf`) in stored-frame coordinates
1437    /// using O(width) scratch memory, observing optional cooperative cancellation and
1438    /// row progress via `pulse` (pass `None` when not needed).
1439    #[inline]
1440    pub fn apply_into<S: PixelSource + ?Sized, D: PixelSink + ?Sized>(
1441        &mut self,
1442        base: &S,
1443        gain_map: &PixelView<'_>,
1444        dst: &mut D,
1445        pulse: Option<&dyn Pulse>,
1446    ) -> Result<(), At<ConvertError>> {
1447        self.apply_into_dyn(
1448            &crate::plan::RefSource(base),
1449            gain_map,
1450            &mut crate::plan::RefSink(dst),
1451            pulse,
1452        )
1453    }
1454
1455    #[inline(never)]
1456    fn apply_into_dyn(
1457        &mut self,
1458        base: &dyn PixelSource,
1459        gain_map: &PixelView<'_>,
1460        dst: &mut dyn PixelSink,
1461        pulse: Option<&dyn Pulse>,
1462    ) -> Result<(), At<ConvertError>> {
1463        let pulse = live_pulse(pulse);
1464        check_pulse(pulse)?;
1465        if base.source_width() != self.base_w
1466            || base.source_height() != self.base_h
1467            || base.source_format() != &self.base_spec
1468            || gain_map.width() != self.gm_w
1469            || gain_map.height() != self.gm_h
1470            || gain_map.format() != &self.gm_spec
1471            || dst.sink_width() != self.base_w
1472            || dst.sink_height() != self.base_h
1473            || dst.sink_format() != &self.destination_format
1474        {
1475            return Err(err_at(ConvertError::DimensionMismatch));
1476        }
1477        self.reset_cache();
1478        for y in 0..self.base_h {
1479            let dst_row = dst
1480                .sink_row_mut(y)
1481                .map_err(|e| err_at((*e.error()).into()))?;
1482            self.apply_row_dyn(
1483                y,
1484                base.source_row(y),
1485                &mut |gy| Ok(gain_map.row(gy)),
1486                dst_row,
1487            )?;
1488            step_pulse(pulse, 1)?;
1489        }
1490        dst.sink_finish(SampleClaims::NONE, HdrMetadata::default());
1491        Ok(())
1492    }
1493
1494    #[inline(never)]
1495    fn fill_gains_u8_lut<'a>(
1496        &mut self,
1497        y: u32,
1498        lut: &[[f32; 256]; 3],
1499        fetch_gm_row: &mut dyn FnMut(u32) -> Result<&'a [u8], At<ConvertError>>,
1500    ) -> Result<(), At<ConvertError>> {
1501        let gy = if self.same_size {
1502            y
1503        } else {
1504            let ratio = f64::from(self.gm_h) / f64::from(self.base_h);
1505            let max_in = i64::from(self.gm_h - 1);
1506            (libm::floor((f64::from(y) + 0.5) * ratio) as i64).clamp(0, max_in) as u32
1507        };
1508        let row = fetch_gm_row(gy)?;
1509        if row.len() < self.gm_row_bytes {
1510            return Err(err_at(ConvertError::DimensionMismatch));
1511        }
1512        let w = self.base_w as usize;
1513        let w_pad = self.w_pad;
1514        let need_3 = self.gm_ch == 3 || !self.shared_meta;
1515
1516        if self.same_size && self.gm_ch == 1 && !need_3 {
1517            // Hot 1:1 1-channel shared UltraHDR LUT path (branch-free tight loop).
1518            for (out, &b) in self.gains[..w].iter_mut().zip(row[..w].iter()) {
1519                *out = lut[0][usize::from(b)];
1520            }
1521            return Ok(());
1522        }
1523
1524        let hw_left = self.h_weights.as_ref().map(|hw| hw.left.as_slice());
1525        if self.gm_ch == 1 {
1526            for x in 0..w {
1527                let sx = hw_left.map_or(x, |l| l[x] as usize);
1528                let b = usize::from(row[sx]);
1529                self.gains[x] = lut[0][b];
1530                if need_3 {
1531                    self.gains[w_pad + x] = lut[1][b];
1532                    self.gains[2 * w_pad + x] = lut[2][b];
1533                }
1534            }
1535        } else {
1536            for x in 0..w {
1537                let o = hw_left.map_or(x, |l| l[x] as usize) * 3;
1538                self.gains[x] = lut[0][usize::from(row[o])];
1539                self.gains[w_pad + x] = lut[1][usize::from(row[o + 1])];
1540                self.gains[2 * w_pad + x] = lut[2][usize::from(row[o + 2])];
1541            }
1542        }
1543        Ok(())
1544    }
1545
1546    #[inline(never)]
1547    fn ensure_horiz_row<'a>(
1548        &mut self,
1549        gm_y: u32,
1550        keep_start: u32,
1551        keep_end: u32,
1552        fetch_gm_row: &mut dyn FnMut(u32) -> Result<&'a [u8], At<ConvertError>>,
1553    ) -> Result<usize, At<ConvertError>> {
1554        if let Some(idx) = self.cache_gm_y.iter().position(|&gy| gy == gm_y) {
1555            return Ok(idx);
1556        }
1557        let n_slots = self.cache_gm_y.len();
1558        let mut slot_idx = self.cache_cursor;
1559        if let Some(empty) = self.cache_gm_y.iter().position(|&gy| gy == u32::MAX) {
1560            slot_idx = empty;
1561        } else {
1562            for step in 0..n_slots {
1563                let cand = (self.cache_cursor + step) % n_slots;
1564                let gy = self.cache_gm_y[cand];
1565                if gy < keep_start || gy >= keep_end {
1566                    slot_idx = cand;
1567                    break;
1568                }
1569            }
1570        }
1571        self.cache_cursor = (slot_idx + 1) % n_slots;
1572
1573        let raw_row = fetch_gm_row(gm_y)?;
1574        if raw_row.len() < self.gm_row_bytes {
1575            return Err(err_at(ConvertError::DimensionMismatch));
1576        }
1577        decode_gm_row_planar(
1578            raw_row,
1579            self.gm_w as usize,
1580            self.gm_spec.layout(),
1581            self.gm_max,
1582            &mut self.gm_decode_scratch,
1583        );
1584
1585        let w = self.base_w as usize;
1586        let w_pad = self.w_pad;
1587        let gm_w = self.gm_w as usize;
1588        let slot_stride = self.gm_ch * w_pad;
1589        let hw = self.h_weights.as_ref().unwrap();
1590        let dst_slot = &mut self.cache_planes[slot_idx * slot_stride..(slot_idx + 1) * slot_stride];
1591
1592        for c in 0..self.gm_ch {
1593            let src_plane = &self.gm_decode_scratch[c * gm_w..(c + 1) * gm_w];
1594            let dst_plane = &mut dst_slot[c * w_pad..c * w_pad + w];
1595            if self.resample == GainMapResample::Nearest {
1596                for (x, out) in dst_plane.iter_mut().enumerate() {
1597                    *out = src_plane[hw.left[x] as usize];
1598                }
1599            } else if hw.max_taps == 2 {
1600                // Fast unrolled 2-tap horizontal bilinear loop (eliminates inner slice/loop overhead).
1601                let lefts = hw.left.as_slice();
1602                let counts = hw.tap_counts.as_slice();
1603                let wflat = hw.weights_flat.as_slice();
1604                for x in 0..w {
1605                    let l = lefts[x] as usize;
1606                    let off = x * 2;
1607                    dst_plane[x] = if counts[x] == 2 {
1608                        src_plane[l] * wflat[off] + src_plane[l + 1] * wflat[off + 1]
1609                    } else {
1610                        src_plane[l] * wflat[off]
1611                    };
1612                }
1613            } else {
1614                for (x, out) in dst_plane.iter_mut().enumerate() {
1615                    let (left, ws) = hw.taps(x);
1616                    let l = left as usize;
1617                    let mut sum = 0.0f32;
1618                    for (t, &wt) in ws.iter().enumerate() {
1619                        sum += src_plane[l + t] * wt;
1620                    }
1621                    *out = sum;
1622                }
1623            }
1624        }
1625        self.cache_gm_y[slot_idx] = gm_y;
1626        Ok(slot_idx)
1627    }
1628
1629    #[inline(never)]
1630    fn fill_samples_for_row<'a>(
1631        &mut self,
1632        y: u32,
1633        fetch_gm_row: &mut dyn FnMut(u32) -> Result<&'a [u8], At<ConvertError>>,
1634    ) -> Result<(), At<ConvertError>> {
1635        let w = self.base_w as usize;
1636        let w_pad = self.w_pad;
1637        if self.same_size {
1638            let raw = fetch_gm_row(y)?;
1639            if raw.len() < self.gm_row_bytes {
1640                return Err(err_at(ConvertError::DimensionMismatch));
1641            }
1642            decode_gm_row_planar(
1643                raw,
1644                w,
1645                self.gm_spec.layout(),
1646                self.gm_max,
1647                &mut self.gm_decode_scratch,
1648            );
1649            for c in 0..self.gm_ch {
1650                self.v_blend[c * w_pad..c * w_pad + w]
1651                    .copy_from_slice(&self.gm_decode_scratch[c * w..(c + 1) * w]);
1652            }
1653            return Ok(());
1654        }
1655
1656        let mut v_ws_buf = [0.0f32; MAX_APPLY_RESAMPLE_TAPS];
1657        let (v_left, v_count) = compute_axis_taps_stack(
1658            self.gm_h,
1659            self.base_h,
1660            self.resample,
1661            y,
1662            MAX_APPLY_RESAMPLE_TAPS,
1663            &mut v_ws_buf,
1664        )
1665        .map_err(err_at)?;
1666        let keep_end = v_left + v_count as u32;
1667
1668        for t in 0..v_count {
1669            let idx = self.ensure_horiz_row(v_left + t as u32, v_left, keep_end, fetch_gm_row)?;
1670            self.v_slot_indices[t] = idx;
1671        }
1672
1673        let ws = &v_ws_buf[..v_count];
1674        let blend2 = self.accel.gainmap_blend_2.unwrap_or(blend_rows_2_scalar);
1675        let blend4 = self.accel.gainmap_blend_4.unwrap_or(blend_rows_4_scalar);
1676        let slot_stride = self.gm_ch * w_pad;
1677
1678        for c in 0..self.gm_ch {
1679            let co = c * w_pad;
1680            let dst = &mut self.v_blend[co..co + w_pad];
1681            match v_count {
1682                1 => {
1683                    let b0 = self.v_slot_indices[0] * slot_stride + co;
1684                    let s0 = &self.cache_planes[b0..b0 + w_pad];
1685                    blend2(s0, s0, 1.0, 0.0, dst);
1686                }
1687                2 => {
1688                    let b0 = self.v_slot_indices[0] * slot_stride + co;
1689                    let b1 = self.v_slot_indices[1] * slot_stride + co;
1690                    blend2(
1691                        &self.cache_planes[b0..b0 + w_pad],
1692                        &self.cache_planes[b1..b1 + w_pad],
1693                        ws[0],
1694                        ws[1],
1695                        dst,
1696                    );
1697                }
1698                4 => {
1699                    let b0 = self.v_slot_indices[0] * slot_stride + co;
1700                    let b1 = self.v_slot_indices[1] * slot_stride + co;
1701                    let b2 = self.v_slot_indices[2] * slot_stride + co;
1702                    let b3 = self.v_slot_indices[3] * slot_stride + co;
1703                    blend4(
1704                        &self.cache_planes[b0..b0 + w_pad],
1705                        &self.cache_planes[b1..b1 + w_pad],
1706                        &self.cache_planes[b2..b2 + w_pad],
1707                        &self.cache_planes[b3..b3 + w_pad],
1708                        [ws[0], ws[1], ws[2], ws[3]],
1709                        dst,
1710                    );
1711                }
1712                _ => {
1713                    blend_rows_general(
1714                        &self.cache_planes,
1715                        slot_stride,
1716                        co,
1717                        &self.v_slot_indices,
1718                        ws,
1719                        w,
1720                        dst,
1721                    );
1722                }
1723            }
1724        }
1725        Ok(())
1726    }
1727
1728    #[inline(never)]
1729    fn decode_samples_to_gains(&mut self) {
1730        let w = self.base_w as usize;
1731        let w_pad = self.w_pad;
1732        let decode_fn = self.accel.gainmap_decode.unwrap_or(decode_gain_1ch_scalar);
1733        let pow_fn = self
1734            .accel
1735            .gamma_pow
1736            .unwrap_or(crate::transfers::gamma_pow_scalar_slice);
1737        let channels = if self.gm_ch == 3 || !self.shared_meta {
1738            3usize
1739        } else {
1740            1usize
1741        };
1742        for c in 0..channels {
1743            let src_off = if self.gm_ch == 3 { c * w_pad } else { 0 };
1744            let samples = &self.v_blend[src_off..src_off + w_pad];
1745            let dst = &mut self.gains[c * w_pad..(c + 1) * w_pad];
1746            let inv_g = self.inv_gamma[c];
1747            if (inv_g - 1.0).abs() < 1e-7 {
1748                decode_fn(samples, self.base_w_g[c], self.slope_w_g[c], dst);
1749            } else if (0.25..=3.0).contains(&inv_g) && self.gamma_tmp.len() >= w_pad {
1750                // Vectorized zero-codegen-overhead `powf` reusing `transfers::TRANSFER_POW`
1751                // (`gamma_pow_simd_slice` / `gamma_pow_scalar_slice` with 0-bit parity!).
1752                let tmp = &mut self.gamma_tmp[..w_pad];
1753                for i in 0..w_pad {
1754                    let raw = samples[i];
1755                    tmp[i] = if raw > 0.0 {
1756                        if raw < 1.0 { raw } else { 1.0 }
1757                    } else {
1758                        0.0
1759                    };
1760                }
1761                pow_fn(tmp, inv_g, f64::from(inv_g));
1762                decode_fn(tmp, self.base_w_g[c], self.slope_w_g[c], dst);
1763            } else {
1764                decode_gain_gamma_scalar(
1765                    samples,
1766                    w,
1767                    inv_g,
1768                    self.base_w_g[c],
1769                    self.slope_w_g[c],
1770                    dst,
1771                );
1772            }
1773        }
1774    }
1775}
1776
1777/// Decode one gain-map scanline (`U8` / `U16` / `F32`, full or `Lsb`/`Msb` bit-packed,
1778/// 1-ch or 3-ch) into planar `[0, 1]` f32 channels inside `dst_planar` (`ch * width`).
1779#[inline(never)]
1780fn decode_gm_row_planar(
1781    row: &[u8],
1782    width: usize,
1783    layout: SampleLayout,
1784    max_code: [f32; 3],
1785    dst_planar: &mut [f32],
1786) {
1787    let ch = layout.channels();
1788    let inv = [1.0 / max_code[0], 1.0 / max_code[1], 1.0 / max_code[2]];
1789    let full = layout.packing().is_full();
1790
1791    // Fast path for the dominant UltraHDR 1-ch full-packing U8 gain map.
1792    if layout.sample() == SampleType::U8 && full && ch == 1 {
1793        let inv0 = inv[0];
1794        for (dst, &b) in dst_planar[..width].iter_mut().zip(row[..width].iter()) {
1795            *dst = f32::from(b) * inv0;
1796        }
1797        return;
1798    }
1799
1800    // Compact unified decoder for 3-ch U8, bit-packed U8/U16 (10/12-bit), full U16, and F32.
1801    let bps = match layout.sample() {
1802        SampleType::U8 => 1usize,
1803        SampleType::U16 => 2usize,
1804        SampleType::F32 => 4usize,
1805        _ => return,
1806    };
1807    for x in 0..width {
1808        for c in 0..ch {
1809            let elem = x * ch + c;
1810            let o = elem * bps;
1811            let v = match layout.sample() {
1812                SampleType::U8 => {
1813                    let raw = u32::from(row[o]);
1814                    let code = if full {
1815                        raw
1816                    } else {
1817                        layout.packing().extract_code(SampleType::U8, c, raw)
1818                    };
1819                    (code as f32) * inv[c]
1820                }
1821                SampleType::U16 => {
1822                    let raw = u32::from(u16::from_ne_bytes([row[o], row[o + 1]]));
1823                    let code = if full {
1824                        raw
1825                    } else {
1826                        layout.packing().extract_code(SampleType::U16, c, raw)
1827                    };
1828                    (code as f32) * inv[c]
1829                }
1830                SampleType::F32 => {
1831                    let f = f32::from_ne_bytes([row[o], row[o + 1], row[o + 2], row[o + 3]]);
1832                    if f.is_finite() { f } else { 0.0 }
1833                }
1834                _ => 0.0,
1835            };
1836            dst_planar[c * width + x] = v;
1837        }
1838    }
1839}
1840
1841fn validate_gain_map_spec(spec: &PixelFormat) -> Result<(), At<ConvertError>> {
1842    let ok_color = matches!(
1843        spec.color(),
1844        ColorSpace::Untagged {
1845            total_channels: 1 | 3,
1846            alpha: AlphaMode::None,
1847        }
1848    );
1849    let ok_sample = matches!(
1850        spec.layout().sample(),
1851        SampleType::U8 | SampleType::U16 | SampleType::F32
1852    );
1853    let ok_packing = matches!(
1854        spec.layout().packing(),
1855        BitPacking::Full | BitPacking::Lsb { .. } | BitPacking::Msb { .. }
1856    );
1857    let ok_order = is_valid_gain_map_order(spec.layout().order());
1858    let ok_ch = matches!(spec.layout().channels(), 1 | 3);
1859    if !ok_color || !ok_sample || !ok_packing || !ok_order || !ok_ch {
1860        return Err(err_at(ConvertError::UnsupportedRoute));
1861    }
1862    Ok(())
1863}
1864
1865// ---------------------------------------------------------------------------
1866// High-level apply & dual-layer orientation functions
1867// ---------------------------------------------------------------------------
1868
1869#[inline(never)]
1870fn apply_gain_map_stored(
1871    dual: &DualLayerHdrView<'_>,
1872    config: &GainMapApplyConfig,
1873    pulse: Option<&dyn Pulse>,
1874) -> Result<PixelBuf, At<ConvertError>> {
1875    let pulse = live_pulse(pulse);
1876    check_pulse(pulse)?;
1877    let mut applier = GainMapApplier::for_view(dual, config)?;
1878    let mut out = PixelBuf::new(
1879        dual.base().width(),
1880        dual.base().height(),
1881        applier.destination_format().clone(),
1882    )
1883    .map_err(|e| err_at((*e.error()).into()))?;
1884    applier.apply_into(dual.base(), dual.gain_map(), &mut out, pulse)?;
1885    Ok(out)
1886}
1887
1888/// Reconstruct a [`PixelBuf`] and its resulting pending [`Orientation`] from a zero-copy
1889/// [`DualLayerHdrView`] according to `config.orientation`, with optional cooperative
1890/// cancellation and progress via `pulse` (pass `None` when not needed):
1891///
1892/// - [`GainMapOrientation::Bake`] (default): reconstructs in stored coordinates, then
1893///   physically applies `dual.orientation()`, returning `(display_buf, Orientation::Identity)`
1894///   with `display_buf.orientation() == Orientation::Identity`.
1895/// - [`GainMapOrientation::Passthrough`]: reconstructs in stored coordinates with zero
1896///   transpose cost, returning `(stored_buf, dual.orientation())` with
1897///   `stored_buf.orientation() == dual.orientation()` for EXIF passthrough or GPU UV rotation.
1898/// - [`GainMapOrientation::RequireIdentity`]: returns `Err(ConvertError::UnsupportedRoute)`
1899///   if `dual.orientation() != Orientation::Identity`.
1900#[inline]
1901pub fn apply_gain_map_oriented(
1902    dual: &DualLayerHdrView<'_>,
1903    config: &GainMapApplyConfig,
1904    pulse: Option<&dyn Pulse>,
1905) -> Result<(PixelBuf, Orientation), At<ConvertError>> {
1906    let pulse = live_pulse(pulse);
1907    check_pulse(pulse)?;
1908    let orient = dual.orientation();
1909    if config.orientation == GainMapOrientation::RequireIdentity && orient != Orientation::Identity
1910    {
1911        return Err(err_at(ConvertError::UnsupportedRoute));
1912    }
1913    if config.orientation == GainMapOrientation::Bake && orient != Orientation::Identity {
1914        if let Some(p) = pulse {
1915            let rows = u64::from(dual.base().height());
1916            return Stages::new(
1917                p,
1918                &[
1919                    PhaseSpec::new("gainmap-apply", 3, Total::Exact(rows)).units("rows"),
1920                    PhaseSpec::new("orient", 1, Total::Exact(rows)).units("rows"),
1921                ],
1922            )
1923            .complete_with_classified(is_stop_at, |stages| {
1924                let out = stages.run_classified(is_stop_at, |st| {
1925                    apply_gain_map_stored(dual, config, Some(st))
1926                })?;
1927                let baked = stages.run_classified(is_stop_at, |st| {
1928                    orient::apply_orientation_with_pulse(&out.as_view(), orient, Some(st))
1929                })?;
1930                Ok((baked, Orientation::Identity))
1931            });
1932        }
1933        let out = apply_gain_map_stored(dual, config, None)?;
1934        let baked = orient::apply_orientation(&out.as_view(), orient)?;
1935        Ok((baked, Orientation::Identity))
1936    } else {
1937        let out = apply_gain_map_stored(dual, config, pulse)?;
1938        Ok((out.with_orientation(orient), orient))
1939    }
1940}
1941
1942/// Reconstruct a [`PixelBuf`] from a zero-copy [`DualLayerHdrView`] with full control over
1943/// target headroom/rendition ([`GainMapApplyConfig::from_headroom_stops`] or
1944/// [`GainMapApplyConfig::from_display_boost_linear`]), resampling kernel, orientation policy,
1945/// conversion policy, optional target [`PixelFormat`], and optional cooperative [`Pulse`]
1946/// cancellation/progress (pass `None` when not needed).
1947///
1948/// Refuses [`GainMapOrientation::Passthrough`] when `dual.orientation() != Orientation::Identity`
1949/// so a pending rotation is never silently discarded (use [`apply_gain_map_oriented`] when you
1950/// want the stored-coordinate buffer paired with its pending [`Orientation`]).
1951#[inline]
1952pub fn apply_gain_map_with(
1953    dual: &DualLayerHdrView<'_>,
1954    config: &GainMapApplyConfig,
1955    pulse: Option<&dyn Pulse>,
1956) -> Result<PixelBuf, At<ConvertError>> {
1957    if config.orientation == GainMapOrientation::Passthrough
1958        && dual.orientation() != Orientation::Identity
1959    {
1960        return Err(err_at(ConvertError::UnsupportedRoute));
1961    }
1962    let (buf, _) = apply_gain_map_oriented(dual, config, pulse)?;
1963    Ok(buf)
1964}
1965
1966/// Physically bake `dual.orientation()` into both `base` and `gain_map`, returning an owned
1967/// aligned [`DualLayerHdrBuf`] with [`Orientation::Identity`].
1968///
1969/// Both layers receive the exact same dihedral transform so their stored-frame coordinates
1970/// stay registered (including subsampled ¼-res gain maps under pixel-center siting).
1971/// For O(1) lossless EXIF passthrough without rebaking pixels, use
1972/// [`DualLayerHdrBuf::compose_orientation`] instead.
1973#[inline(never)]
1974pub fn bake_dual_layer_orientation(
1975    dual: &DualLayerHdrView<'_>,
1976) -> Result<DualLayerHdrBuf, At<ConvertError>> {
1977    bake_dual_layer_orientation_after_with_pulse(dual, Orientation::Identity, None)
1978}
1979
1980/// Physically bake `dual.orientation()` into both `base` and `gain_map` with optional
1981/// cooperative cancellation and progress via `pulse` (pass `None` when not needed).
1982#[inline(never)]
1983pub fn bake_dual_layer_orientation_with_pulse(
1984    dual: &DualLayerHdrView<'_>,
1985    pulse: Option<&dyn Pulse>,
1986) -> Result<DualLayerHdrBuf, At<ConvertError>> {
1987    bake_dual_layer_orientation_after_with_pulse(dual, Orientation::Identity, pulse)
1988}
1989
1990/// Physically bake `dual.orientation().then(delta)` into both `base` and `gain_map`, keeping
1991/// both layers strictly registered and returning an owned [`DualLayerHdrBuf`] with
1992/// [`Orientation::Identity`].
1993///
1994/// Preserves `metadata`, `alternate_color_space`, and per-layer `HdrMetadata` / `SampleClaims`.
1995/// For O(1) EXIF passthrough metadata composition without pixel rebake, use
1996/// [`DualLayerHdrBuf::compose_orientation`] / [`DualLayerHdrView::compose_orientation`].
1997#[inline(never)]
1998pub fn bake_dual_layer_orientation_after(
1999    dual: &DualLayerHdrView<'_>,
2000    delta: Orientation,
2001) -> Result<DualLayerHdrBuf, At<ConvertError>> {
2002    bake_dual_layer_orientation_after_with_pulse(dual, delta, None)
2003}
2004
2005/// Physically bake `dual.orientation().then(delta)` into both `base` and `gain_map` with
2006/// optional cooperative cancellation and progress via `pulse` (pass `None` when not needed).
2007#[inline(never)]
2008pub fn bake_dual_layer_orientation_after_with_pulse(
2009    dual: &DualLayerHdrView<'_>,
2010    delta: Orientation,
2011    pulse: Option<&dyn Pulse>,
2012) -> Result<DualLayerHdrBuf, At<ConvertError>> {
2013    let pulse = live_pulse(pulse);
2014    check_pulse(pulse)?;
2015    let total = dual.orientation().then(delta);
2016    let (base, gain_map) = if let Some(p) = pulse {
2017        let base_w = u64::from(dual.base().width())
2018            .saturating_mul(u64::from(dual.base().height()))
2019            .max(1);
2020        let gm_w = u64::from(dual.gain_map().width())
2021            .saturating_mul(u64::from(dual.gain_map().height()))
2022            .max(1);
2023        Stages::new(
2024            p,
2025            &[
2026                PhaseSpec::new(
2027                    "orient-base",
2028                    base_w,
2029                    Total::Exact(u64::from(dual.base().height())),
2030                )
2031                .units("rows"),
2032                PhaseSpec::new(
2033                    "orient-gainmap",
2034                    gm_w,
2035                    Total::Exact(u64::from(dual.gain_map().height())),
2036                )
2037                .units("rows"),
2038            ],
2039        )
2040        .complete_with_classified(is_stop_at, |stages| {
2041            let base = stages.run_classified(is_stop_at, |st| {
2042                orient::apply_orientation_with_pulse(dual.base(), total, Some(st))
2043            })?;
2044            let gain_map = stages.run_classified(is_stop_at, |st| {
2045                orient::apply_orientation_with_pulse(dual.gain_map(), total, Some(st))
2046            })?;
2047            Ok((base, gain_map))
2048        })?
2049    } else {
2050        let base = orient::apply_orientation(dual.base(), total)?;
2051        let gain_map = orient::apply_orientation(dual.gain_map(), total)?;
2052        (base, gain_map)
2053    };
2054    match dual.alternate_color_space().cloned() {
2055        Some(alt) => {
2056            DualLayerHdrBuf::new_with_alternate_color(base, gain_map, dual.metadata(), alt)
2057        }
2058        None => DualLayerHdrBuf::new(base, gain_map, dual.metadata()),
2059    }
2060    .map_err(|e| err_at((*e.error()).into()))
2061}
2062
2063// ---------------------------------------------------------------------------
2064// Extraction: downsampling modes, configuration, streaming row extractor
2065// ---------------------------------------------------------------------------
2066
2067/// Downsampling filter used during gain-map extraction when `scale_factor > 1`.
2068#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
2069#[non_exhaustive]
2070pub enum GainMapDownsample {
2071    /// Area-averaging box filter over each `scale × scale` block in linear light (default).
2072    /// Prevents aliasing and single-pixel highlight sparkle on subsampled gain maps.
2073    #[default]
2074    Box,
2075    /// Separable center-sited triangle/bilinear filter in linear light.
2076    Bilinear,
2077    /// Center-pixel point sampling `(gx * scale + scale / 2).min(w - 1)`, matching legacy
2078    /// `ultrahdr-core` / `zenjpeg` subsampling.
2079    Point,
2080}
2081
2082/// Configuration for ISO 21496-1 gain-map extraction ([`extract_gain_map_only`],
2083/// [`GainMapRowExtractor`]).
2084#[derive(Clone, Debug)]
2085#[non_exhaustive]
2086pub struct GainMapExtractConfig {
2087    /// Subsampling divisor for the output gain map (`1` = full resolution, `4` = ¼-res
2088    /// UltraHDR standard; output dimensions are `div_ceil(scale_factor)`).
2089    pub scale_factor: u8,
2090    /// Downsampling filter applied when `scale_factor > 1`.
2091    pub downsample: GainMapDownsample,
2092    /// `false` = 1-channel luminance gain map (`GainMapChannels::Shared`);
2093    /// `true` = 3-channel RGB gain map (`GainMapChannels::PerChannel`).
2094    pub multi_channel: bool,
2095    /// Sample storage type (`U8` default, or `U16` for 10/12/16-bit AVIF/JXL maps).
2096    pub sample_type: SampleType,
2097    /// Bit packing for integer gain-map samples (`BitPacking::Full` default; e.g.
2098    /// `BitPacking::Lsb { bits: 10 }` for 10-bit AVIF/JXL maps).
2099    pub packing: BitPacking,
2100    /// Minimum encoded log₂ gain stop (code `0`).
2101    pub min_gain_stops: f32,
2102    /// Maximum encoded log₂ gain stop (code `max_code`).
2103    pub max_gain_stops: f32,
2104    /// Gain-map gamma (`> 0.0`, default `1.0`).
2105    pub gamma: f32,
2106    /// Linear base offset (`k_base`, default `1/64`).
2107    pub base_offset: f32,
2108    /// Linear alternate offset (`k_alt`, default `1/64`).
2109    pub alternate_offset: f32,
2110    /// Base rendition HDR headroom in log₂ stops (`0.0` = SDR base).
2111    pub base_hdr_headroom_stops: f32,
2112    /// Alternate rendition HDR headroom in log₂ stops (`> base` = Forward, `< base` = Reverse).
2113    pub alternate_hdr_headroom_stops: f32,
2114    /// Primaries in which channelwise gain is computed (`Base` or `Alternate`).
2115    pub application_space: GainMapColorSpace,
2116    /// When `true`, performs a 2-pass content-fit scan that narrows the quantization grid
2117    /// to the content's observed gain range within `[min_gain_stops, max_gain_stops]`
2118    /// (minimum span [`CONTENT_FIT_MIN_SPAN_STOPS`]).
2119    pub content_fit: bool,
2120    /// Conversion policy used to linearize base and alternate inputs.
2121    pub policy: ConvertPolicy,
2122}
2123
2124impl Default for GainMapExtractConfig {
2125    fn default() -> Self {
2126        Self {
2127            scale_factor: 1,
2128            downsample: GainMapDownsample::Box,
2129            multi_channel: false,
2130            sample_type: SampleType::U8,
2131            packing: BitPacking::Full,
2132            min_gain_stops: 0.0,
2133            max_gain_stops: 2.5,
2134            gamma: 1.0,
2135            base_offset: 1.0 / 64.0,
2136            alternate_offset: 1.0 / 64.0,
2137            base_hdr_headroom_stops: 0.0,
2138            alternate_hdr_headroom_stops: 2.5,
2139            application_space: GainMapColorSpace::Base,
2140            content_fit: false,
2141            policy: ConvertPolicy::working_linear(),
2142        }
2143    }
2144}
2145
2146impl GainMapExtractConfig {
2147    /// Standard UltraHDR preset (¼-res `scale_factor = 4`, 1-ch U8, `[0, ~2.58]` stops =
2148    /// `1×..=6×` linear boost, `1/64` offsets, `Box` area downsampling).
2149    #[must_use]
2150    pub fn ultrahdr() -> Self {
2151        Self::default()
2152            .with_scale_factor(4)
2153            .with_boost_range_linear(1.0, 6.0)
2154            .with_headroom_boost_linear(1.0, 6.0)
2155    }
2156
2157    /// Set gain-map subsampling divisor (`>= 1`).
2158    #[inline]
2159    #[must_use]
2160    pub fn with_scale_factor(mut self, scale_factor: u8) -> Self {
2161        self.scale_factor = scale_factor.max(1);
2162        self
2163    }
2164
2165    /// Set downsampling filter when `scale_factor > 1`.
2166    #[inline]
2167    #[must_use]
2168    pub fn with_downsample(mut self, downsample: GainMapDownsample) -> Self {
2169        self.downsample = downsample;
2170        self
2171    }
2172
2173    /// Select 1-channel (`false`) vs 3-channel RGB (`true`) gain map.
2174    #[inline]
2175    #[must_use]
2176    pub fn with_multi_channel(mut self, multi_channel: bool) -> Self {
2177        self.multi_channel = multi_channel;
2178        self
2179    }
2180
2181    /// Select integer storage type & packing (e.g. `(SampleType::U16, BitPacking::Lsb { bits: 10 })`).
2182    #[inline]
2183    #[must_use]
2184    pub fn with_sample_storage(mut self, sample_type: SampleType, packing: BitPacking) -> Self {
2185        self.sample_type = sample_type;
2186        self.packing = packing;
2187        self
2188    }
2189
2190    /// Set quantization grid in log₂ stops.
2191    #[inline]
2192    #[must_use]
2193    pub fn with_gain_range_stops(mut self, min_stops: f32, max_stops: f32) -> Self {
2194        self.min_gain_stops = min_stops;
2195        self.max_gain_stops = max_stops;
2196        self
2197    }
2198
2199    /// Set quantization grid from positive linear boost ratios (e.g. `1.0`, `6.0`).
2200    #[inline]
2201    #[must_use]
2202    pub fn with_boost_range_linear(mut self, min_boost: f32, max_boost: f32) -> Self {
2203        self.min_gain_stops = libm::log2f(min_boost.max(1e-6));
2204        self.max_gain_stops = libm::log2f(max_boost.max(1e-6));
2205        self
2206    }
2207
2208    /// Set gain-map encoding gamma (`> 0.0`).
2209    #[inline]
2210    #[must_use]
2211    pub fn with_gamma(mut self, gamma: f32) -> Self {
2212        self.gamma = gamma;
2213        self
2214    }
2215
2216    /// Set linear base & alternate offsets.
2217    #[inline]
2218    #[must_use]
2219    pub fn with_offsets(mut self, base_offset: f32, alternate_offset: f32) -> Self {
2220        self.base_offset = base_offset;
2221        self.alternate_offset = alternate_offset;
2222        self
2223    }
2224
2225    /// Set base and alternate HDR headrooms in log₂ stops.
2226    #[inline]
2227    #[must_use]
2228    pub fn with_headroom_stops(mut self, base_stops: f32, alternate_stops: f32) -> Self {
2229        self.base_hdr_headroom_stops = base_stops;
2230        self.alternate_hdr_headroom_stops = alternate_stops;
2231        self
2232    }
2233
2234    /// Set base and alternate HDR headrooms from linear boost ratios (`1.0` → `0.0` stops).
2235    #[inline]
2236    #[must_use]
2237    pub fn with_headroom_boost_linear(mut self, base_boost: f32, alternate_boost: f32) -> Self {
2238        self.base_hdr_headroom_stops = display_boost_to_headroom_stops(base_boost);
2239        self.alternate_hdr_headroom_stops = display_boost_to_headroom_stops(alternate_boost);
2240        self
2241    }
2242
2243    /// Choose whether gain is computed in `Base` or `Alternate` linear primaries.
2244    #[inline]
2245    #[must_use]
2246    pub fn with_application_space(mut self, space: GainMapColorSpace) -> Self {
2247        self.application_space = space;
2248        self
2249    }
2250
2251    /// Enable 2-pass content-fit grid narrowing to the observed content gain range.
2252    #[inline]
2253    #[must_use]
2254    pub fn with_content_fit(mut self, content_fit: bool) -> Self {
2255        self.content_fit = content_fit;
2256        self
2257    }
2258
2259    /// Set conversion policy used to linearize base and alternate images.
2260    #[inline]
2261    #[must_use]
2262    pub fn with_policy(mut self, policy: ConvertPolicy) -> Self {
2263        self.policy = policy;
2264        self
2265    }
2266
2267    /// Build the exact [`GainMapMetadata`] matching this configuration's quantization grid.
2268    #[inline(never)]
2269    pub fn to_metadata(&self) -> Result<GainMapMetadata, At<ConvertError>> {
2270        if !self.min_gain_stops.is_finite()
2271            || !self.max_gain_stops.is_finite()
2272            || self.max_gain_stops < self.min_gain_stops
2273            || !self.gamma.is_finite()
2274            || self.gamma <= 0.0
2275            || !self.base_offset.is_finite()
2276            || !self.alternate_offset.is_finite()
2277            || !self.base_hdr_headroom_stops.is_finite()
2278            || !self.alternate_hdr_headroom_stops.is_finite()
2279            || self.base_hdr_headroom_stops < 0.0
2280            || self.alternate_hdr_headroom_stops < 0.0
2281        {
2282            return Err(err_at(ConvertError::UnsupportedRoute));
2283        }
2284        let comp = GainMapComponent::new(
2285            signed_fraction_from_f32(self.min_gain_stops),
2286            signed_fraction_from_f32(self.max_gain_stops),
2287            unsigned_fraction_from_f32(self.gamma),
2288            signed_fraction_from_f32(self.base_offset),
2289            signed_fraction_from_f32(self.alternate_offset),
2290        )
2291        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
2292        let channels = if self.multi_channel {
2293            GainMapChannels::PerChannel([comp; 3])
2294        } else {
2295            GainMapChannels::Shared(comp)
2296        };
2297        let h_base = unsigned_fraction_from_f32(self.base_hdr_headroom_stops);
2298        let h_alt = unsigned_fraction_from_f32(self.alternate_hdr_headroom_stops);
2299        GainMapMetadata::new(channels, h_base, h_alt, self.application_space)
2300            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))
2301    }
2302
2303    fn gain_map_spec(&self) -> Result<PixelFormat, At<ConvertError>> {
2304        let layout = match (self.sample_type, self.multi_channel) {
2305            (SampleType::U8, false) => SampleLayout::GRAY8,
2306            (SampleType::U8, true) => SampleLayout::RGB8,
2307            (SampleType::U16, false) => SampleLayout::GRAY16,
2308            (SampleType::U16, true) => SampleLayout::RGB16,
2309            _ => return Err(err_at(ConvertError::UnsupportedRoute)),
2310        }
2311        .try_with_packing(self.packing)
2312        .map_err(|e| err_at(zenpixels::ColorError::Layout(e).into()))?;
2313        let spec = PixelFormat::new(
2314            layout,
2315            ColorSpace::Untagged {
2316                total_channels: if self.multi_channel { 3 } else { 1 },
2317                alpha: AlphaMode::None,
2318            },
2319        )
2320        .map_err(|e| err_at((*e.error()).into()))?;
2321        validate_gain_map_spec(&spec)?;
2322        Ok(spec)
2323    }
2324}
2325
2326/// Interleaved channel layout for linear `f32` row buffers passed to
2327/// [`GainMapRowExtractor::encode_row_linear_f32`].
2328#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
2329pub enum LinearInputChannels {
2330    /// 3-channel packed linear RGB (`[R, G, B, ...]`).
2331    Rgb = 3,
2332    /// 4-channel packed linear RGBA (`[R, G, B, A, ...]`; alpha lane is ignored).
2333    Rgba = 4,
2334}
2335
2336impl LinearInputChannels {
2337    /// Number of `f32` elements per pixel (`3` or `4`).
2338    #[inline]
2339    #[must_use]
2340    pub const fn stride(self) -> usize {
2341        self as usize
2342    }
2343}
2344
2345/// Row-streaming linear-f32 ISO 21496-1 gain-map encoder.
2346#[derive(Clone, Debug)]
2347pub struct GainMapRowExtractor {
2348    metadata: GainMapMetadata,
2349    multichannel: bool,
2350    sign: f32,
2351    luma: [f32; 3],
2352    min_g: [f32; 3],
2353    span_g: [f32; 3],
2354    gamma: [f32; 3],
2355    k_base: [f32; 3],
2356    k_alt: [f32; 3],
2357    observed_min_stops: f32,
2358    observed_max_stops: f32,
2359}
2360
2361impl GainMapRowExtractor {
2362    /// Construct a row extractor using exact [`GainMapMetadata`] and custom primaries.
2363    #[inline(never)]
2364    pub fn new_custom(
2365        metadata: GainMapMetadata,
2366        app_primaries: zenpixels::CustomPrimaries,
2367    ) -> Result<Self, At<ConvertError>> {
2368        Self::new_with_luma(metadata, app_primaries.luma_weights())
2369    }
2370
2371    /// Construct a row extractor using exact [`GainMapMetadata`] and application primaries.
2372    #[inline(never)]
2373    pub fn new(
2374        metadata: GainMapMetadata,
2375        app_primaries: Primaries,
2376    ) -> Result<Self, At<ConvertError>> {
2377        Self::new_with_luma(metadata, app_primaries.luma_weights())
2378    }
2379
2380    fn new_with_luma(metadata: GainMapMetadata, luma: [f32; 3]) -> Result<Self, At<ConvertError>> {
2381        if !metadata.is_valid() {
2382            return Err(err_at(ConvertError::UnsupportedRoute));
2383        }
2384        let direction = metadata
2385            .direction()
2386            .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
2387        let sign = match direction {
2388            GainMapDirection::Forward => 1.0_f32,
2389            GainMapDirection::Reverse => -1.0_f32,
2390        };
2391        let mut min_g = [0.0f32; 3];
2392        let mut span_g = [0.0f32; 3];
2393        let mut gamma = [1.0f32; 3];
2394        let mut k_base = [0.0f32; 3];
2395        let mut k_alt = [0.0f32; 3];
2396        for c in 0..3 {
2397            let comp = metadata.channel(c);
2398            min_g[c] = comp.min_gain_stops().to_f32();
2399            span_g[c] = comp.max_gain_stops().to_f32() - min_g[c];
2400            gamma[c] = comp.gamma().to_f32();
2401            k_base[c] = comp.base_offset().to_f32();
2402            k_alt[c] = comp.alternate_offset().to_f32();
2403        }
2404        Ok(Self {
2405            multichannel: metadata.channels().is_multichannel(),
2406            metadata,
2407            sign,
2408            luma,
2409            min_g,
2410            span_g,
2411            gamma,
2412            k_base,
2413            k_alt,
2414            observed_min_stops: f32::INFINITY,
2415            observed_max_stops: f32::NEG_INFINITY,
2416        })
2417    }
2418
2419    /// Construct a row extractor from a [`GainMapExtractConfig`] and application primaries.
2420    pub fn from_config(
2421        config: &GainMapExtractConfig,
2422        app_primaries: Primaries,
2423    ) -> Result<Self, At<ConvertError>> {
2424        Self::new(config.to_metadata()?, app_primaries)
2425    }
2426
2427    /// Quantize one row of paired linear RGB(A) `f32` pixels (`input_channels`:
2428    /// [`LinearInputChannels::Rgb`] or [`LinearInputChannels::Rgba`])
2429    /// into packed gain-map sample bytes matching `gain_map_layout` (`U8` or `U16`,
2430    /// `Full`/`Lsb`/`Msb`, `Gray`/`Rgb`/`Generic(1|3)`).
2431    ///
2432    /// Computes exact `f64` signed-offset ratios `(alt + k_alt) / (base + k_base)` without
2433    /// near-black floor clamping.
2434    #[inline(never)]
2435    pub fn encode_row_linear_f32(
2436        &mut self,
2437        base_linear: &[f32],
2438        alt_linear: &[f32],
2439        input_channels: LinearInputChannels,
2440        gain_map_layout: SampleLayout,
2441        dst_row: &mut [u8],
2442    ) -> Result<(), At<ConvertError>> {
2443        let channels = input_channels.stride();
2444        let gm_layout = gain_map_layout;
2445        #[allow(clippy::manual_is_multiple_of)]
2446        if base_linear.len() != alt_linear.len() || base_linear.len() % channels != 0 {
2447            return Err(err_at(ConvertError::DimensionMismatch));
2448        }
2449        let gm_ch = gm_layout.channels();
2450        if !matches!(gm_layout.sample(), SampleType::U8 | SampleType::U16)
2451            || !matches!(
2452                gm_layout.packing(),
2453                BitPacking::Full | BitPacking::Lsb { .. } | BitPacking::Msb { .. }
2454            )
2455            || !is_valid_gain_map_order(gm_layout.order())
2456            || !matches!(gm_ch, 1 | 3)
2457        {
2458            return Err(err_at(ConvertError::UnsupportedRoute));
2459        }
2460        // Per-channel ISO 21496-1 metadata requires a 3-channel gain map; shared 1-record
2461        // metadata is valid for BOTH 1-channel and 3-channel gain maps!
2462        if self.multichannel && gm_ch != 3 {
2463            return Err(err_at(ConvertError::UnsupportedRoute));
2464        }
2465        PixelFormat::new(
2466            gm_layout,
2467            ColorSpace::Untagged {
2468                total_channels: gm_ch as u8,
2469                alpha: AlphaMode::None,
2470            },
2471        )
2472        .map_err(|e| err_at((*e.error()).into()))?;
2473
2474        let pixels = base_linear.len() / channels;
2475        let need_bytes = pixels
2476            .checked_mul(gm_layout.bytes_per_pixel())
2477            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
2478        if dst_row.len() < need_bytes {
2479            return Err(err_at(ConvertError::DimensionMismatch));
2480        }
2481
2482        let max_code = gm_layout.packing().max_code(gm_layout.sample(), 0).max(1);
2483        let max_f = max_code as f32;
2484
2485        if gm_ch == 3 {
2486            for x in 0..pixels {
2487                let o = x * channels;
2488                for c in 0..3 {
2489                    let log2_r = compute_log2_ratio(
2490                        self.sign,
2491                        base_linear[o + c],
2492                        alt_linear[o + c],
2493                        self.k_base[c],
2494                        self.k_alt[c],
2495                        self.min_g[c],
2496                        self.min_g[c] + self.span_g[c],
2497                    );
2498                    self.observed_min_stops = self.observed_min_stops.min(log2_r);
2499                    self.observed_max_stops = self.observed_max_stops.max(log2_r);
2500                    let code = quantize_log2_gain(
2501                        log2_r,
2502                        self.min_g[c],
2503                        self.span_g[c],
2504                        self.gamma[c],
2505                        max_code,
2506                        max_f,
2507                    );
2508                    write_gm_code(gm_layout, dst_row, x * 3 + c, c, code);
2509                }
2510            }
2511        } else {
2512            let [yr, yg, yb] = self.luma;
2513            let max_g0 = self.min_g[0] + self.span_g[0];
2514            for x in 0..pixels {
2515                let o = x * channels;
2516                let lb = yr * base_linear[o] + yg * base_linear[o + 1] + yb * base_linear[o + 2];
2517                let la = yr * alt_linear[o] + yg * alt_linear[o + 1] + yb * alt_linear[o + 2];
2518                let log2_r = compute_log2_ratio(
2519                    self.sign,
2520                    lb,
2521                    la,
2522                    self.k_base[0],
2523                    self.k_alt[0],
2524                    self.min_g[0],
2525                    max_g0,
2526                );
2527                self.observed_min_stops = self.observed_min_stops.min(log2_r);
2528                self.observed_max_stops = self.observed_max_stops.max(log2_r);
2529                let code = quantize_log2_gain(
2530                    log2_r,
2531                    self.min_g[0],
2532                    self.span_g[0],
2533                    self.gamma[0],
2534                    max_code,
2535                    max_f,
2536                );
2537                write_gm_code(gm_layout, dst_row, x, 0, code);
2538            }
2539        }
2540
2541        Ok(())
2542    }
2543
2544    /// Observe the `(min_log2_stops, max_log2_stops)` gain range accumulated across all
2545    /// rows encoded so far (`None` if zero pixels were processed).
2546    #[inline]
2547    #[must_use]
2548    pub fn observed_gain_stops(&self) -> Option<(f32, f32)> {
2549        if self.observed_min_stops.is_finite() && self.observed_max_stops.is_finite() {
2550            Some((self.observed_min_stops, self.observed_max_stops))
2551        } else {
2552            None
2553        }
2554    }
2555
2556    /// Return the exact [`GainMapMetadata`] matching the encoded bytes.
2557    #[inline]
2558    #[must_use]
2559    pub fn metadata(&self) -> GainMapMetadata {
2560        self.metadata
2561    }
2562
2563    /// Build [`GainMapMetadata`] for the encoded bytes, optionally widening
2564    /// `alternate_hdr_headroom` (in Forward mode) if observed content gain exceeded the
2565    /// configured alternate headroom (matching `ultrahdr-core`'s contract `#33`).
2566    #[must_use]
2567    pub fn build_metadata_widening_headroom(&self) -> GainMapMetadata {
2568        let mut out = self.metadata;
2569        if self.sign > 0.0
2570            && self.observed_max_stops.is_finite()
2571            && self.observed_max_stops > out.alternate_hdr_headroom().to_f32()
2572        {
2573            let grid_lo = self.min_g[0].min(self.min_g[1]).min(self.min_g[2]);
2574            let grid_hi = (self.min_g[0] + self.span_g[0])
2575                .max(self.min_g[1] + self.span_g[1])
2576                .max(self.min_g[2] + self.span_g[2]);
2577            let clamped = self.observed_max_stops.clamp(grid_lo, grid_hi);
2578            if clamped > out.alternate_hdr_headroom().to_f32() {
2579                let candidate = unsigned_fraction_from_f32(clamped);
2580                if let Some(updated) = out.with_headrooms(out.base_hdr_headroom(), candidate) {
2581                    out = updated;
2582                }
2583            }
2584        }
2585        out
2586    }
2587}
2588
2589#[inline]
2590fn compute_log2_ratio(
2591    sign: f32,
2592    base_val: f32,
2593    alt_val: f32,
2594    k_base: f32,
2595    k_alt: f32,
2596    min_g: f32,
2597    max_g: f32,
2598) -> f32 {
2599    let num = f64::from(alt_val) + f64::from(k_alt);
2600    let den = f64::from(base_val) + f64::from(k_base);
2601    if !num.is_finite() || !den.is_finite() {
2602        return 0.0;
2603    }
2604    if (num > 0.0 && den > 0.0) || (num < 0.0 && den < 0.0) {
2605        let lg = (f64::from(sign) * libm::log2(num / den)) as f32;
2606        if lg.is_finite() {
2607            return lg.clamp(-MAX_LOG2_GAIN, MAX_LOG2_GAIN);
2608        }
2609    }
2610    if num == den {
2611        0.0
2612    } else if num > den {
2613        if sign > 0.0 { max_g } else { min_g }
2614    } else if sign > 0.0 {
2615        min_g
2616    } else {
2617        max_g
2618    }
2619}
2620
2621#[inline(always)]
2622fn quantize_log2_gain(
2623    log2_r: f32,
2624    min_g: f32,
2625    span_g: f32,
2626    gamma: f32,
2627    max_code: u32,
2628    max_f: f32,
2629) -> u32 {
2630    let norm = if span_g.abs() < 1e-12 {
2631        0.0
2632    } else {
2633        ((log2_r - min_g) / span_g).clamp(0.0, 1.0)
2634    };
2635    let encoded = if (gamma - 1.0).abs() < 1e-7 {
2636        norm
2637    } else {
2638        libm::powf(norm, gamma)
2639    };
2640    ((encoded * max_f + 0.5) as u32).min(max_code)
2641}
2642
2643#[inline(always)]
2644fn write_gm_code(layout: SampleLayout, dst: &mut [u8], elem_idx: usize, comp: usize, code: u32) {
2645    let packed = layout.packing().pack_code(layout.sample(), comp, code);
2646    match layout.sample() {
2647        SampleType::U8 => dst[elem_idx] = packed as u8,
2648        SampleType::U16 => {
2649            let o = elem_idx * 2;
2650            dst[o..o + 2].copy_from_slice(&(packed as u16).to_ne_bytes());
2651        }
2652        _ => {}
2653    }
2654}
2655
2656// ---------------------------------------------------------------------------
2657// Whole-image extraction (zero base copy + subsampling + 2-pass content-fit)
2658// ---------------------------------------------------------------------------
2659
2660/// Extract only the numeric gain-map [`PixelBuf`] and exact [`GainMapMetadata`] from
2661/// borrowed `base_src` and `alternate_src` views without duplicating the base raster,
2662/// observing optional cooperative cancellation and progress via `pulse` (pass `None`
2663/// when not needed).
2664pub fn extract_gain_map_only(
2665    base_src: &PixelView<'_>,
2666    alternate_src: &PixelView<'_>,
2667    config: &GainMapExtractConfig,
2668    pulse: Option<&dyn Pulse>,
2669) -> Result<(PixelBuf, GainMapMetadata), At<ConvertError>> {
2670    let pulse = live_pulse(pulse);
2671    check_pulse(pulse)?;
2672    let scale = config.scale_factor.max(1);
2673    if config.content_fit {
2674        let initial_meta = config.to_metadata()?;
2675        let gm_spec = config.gain_map_spec()?;
2676        if let Some(p) = pulse {
2677            let out_rows = u64::from(base_src.height().div_ceil(u32::from(scale)));
2678            return Stages::new(
2679                p,
2680                &[
2681                    PhaseSpec::new("gainmap-measure", 1, Total::Exact(out_rows)).units("rows"),
2682                    PhaseSpec::new("gainmap-encode", 1, Total::Exact(out_rows)).units("rows"),
2683                ],
2684            )
2685            .complete_with_classified(is_stop_at, |stages| {
2686                let (_, observed) = stages.run_classified(is_stop_at, |st| {
2687                    extract_gain_map_internal(
2688                        base_src,
2689                        alternate_src,
2690                        initial_meta,
2691                        scale,
2692                        config.downsample,
2693                        gm_spec.clone(),
2694                        &config.policy,
2695                        Some(st),
2696                        true,
2697                    )
2698                })?;
2699                let fitted = content_fit_config(config, observed);
2700                let fitted_meta = fitted.to_metadata()?;
2701                let fitted_spec = fitted.gain_map_spec()?;
2702                let (buf, _) = stages.run_classified(is_stop_at, |st| {
2703                    extract_gain_map_internal(
2704                        base_src,
2705                        alternate_src,
2706                        fitted_meta,
2707                        fitted.scale_factor.max(1),
2708                        fitted.downsample,
2709                        fitted_spec,
2710                        &fitted.policy,
2711                        Some(st),
2712                        false,
2713                    )
2714                })?;
2715                Ok((buf, fitted_meta))
2716            });
2717        }
2718        let (_, observed) = extract_gain_map_internal(
2719            base_src,
2720            alternate_src,
2721            initial_meta,
2722            scale,
2723            config.downsample,
2724            gm_spec,
2725            &config.policy,
2726            None,
2727            true,
2728        )?;
2729        let fitted = content_fit_config(config, observed);
2730        let fitted_meta = fitted.to_metadata()?;
2731        let (buf, _) = extract_gain_map_internal(
2732            base_src,
2733            alternate_src,
2734            fitted_meta,
2735            fitted.scale_factor.max(1),
2736            fitted.downsample,
2737            fitted.gain_map_spec()?,
2738            &fitted.policy,
2739            None,
2740            false,
2741        )?;
2742        return Ok((buf, fitted_meta));
2743    }
2744
2745    let meta = config.to_metadata()?;
2746    let (buf, _) = extract_gain_map_internal(
2747        base_src,
2748        alternate_src,
2749        meta,
2750        scale,
2751        config.downsample,
2752        config.gain_map_spec()?,
2753        &config.policy,
2754        pulse,
2755        false,
2756    )?;
2757    Ok((buf, meta))
2758}
2759
2760fn content_fit_config(
2761    config: &GainMapExtractConfig,
2762    observed: Option<(f32, f32)>,
2763) -> GainMapExtractConfig {
2764    let mut out = config.clone();
2765    let Some((obs_min, obs_max)) = observed else {
2766        return out;
2767    };
2768    if !obs_min.is_finite() || !obs_max.is_finite() {
2769        return out;
2770    }
2771    let hi_bound = config.max_gain_stops;
2772    let lo_bound = config.min_gain_stops;
2773    let top = obs_max.clamp(lo_bound, hi_bound);
2774    let bottom = obs_min.clamp(lo_bound, top);
2775    let (bottom, top) = if top - bottom < CONTENT_FIT_MIN_SPAN_STOPS {
2776        let widened_top = (bottom + CONTENT_FIT_MIN_SPAN_STOPS).min(hi_bound);
2777        if widened_top - bottom >= CONTENT_FIT_MIN_SPAN_STOPS - 1e-6 {
2778            (bottom, widened_top)
2779        } else {
2780            (
2781                (widened_top - CONTENT_FIT_MIN_SPAN_STOPS).max(lo_bound),
2782                widened_top,
2783            )
2784        }
2785    } else {
2786        (bottom, top)
2787    };
2788    out.min_gain_stops = bottom;
2789    out.max_gain_stops = top;
2790    out
2791}
2792
2793/// Extract an ISO 21496-1 [`DualLayerHdrBuf`] at 1:1 resolution from `base_src` and
2794/// `alternate_src` using exact caller-supplied `metadata` verbatim.
2795///
2796/// For subsampled maps, content-fit grids, 10/12-bit maps, or avoiding a base buffer copy,
2797/// use [`extract_gain_map_only`].
2798pub fn extract_gain_map(
2799    base_src: &PixelView<'_>,
2800    alternate_src: &PixelView<'_>,
2801    metadata: GainMapMetadata,
2802) -> Result<DualLayerHdrBuf, At<ConvertError>> {
2803    extract_gain_map_with_pulse(base_src, alternate_src, metadata, None)
2804}
2805
2806/// Extract an ISO 21496-1 [`DualLayerHdrBuf`] at 1:1 resolution with optional cooperative
2807/// cancellation and progress via `pulse` (pass `None` when not needed).
2808pub fn extract_gain_map_with_pulse(
2809    base_src: &PixelView<'_>,
2810    alternate_src: &PixelView<'_>,
2811    metadata: GainMapMetadata,
2812    pulse: Option<&dyn Pulse>,
2813) -> Result<DualLayerHdrBuf, At<ConvertError>> {
2814    let pulse = live_pulse(pulse);
2815    check_pulse(pulse)?;
2816    let gm_spec = if metadata.channels().is_multichannel() {
2817        PixelFormat::new(
2818            SampleLayout::RGB8,
2819            ColorSpace::Untagged {
2820                total_channels: 3,
2821                alpha: AlphaMode::None,
2822            },
2823        )
2824        .map_err(|e| err_at((*e.error()).into()))?
2825    } else {
2826        PixelFormat::new(
2827            SampleLayout::GRAY8,
2828            ColorSpace::Untagged {
2829                total_channels: 1,
2830                alpha: AlphaMode::None,
2831            },
2832        )
2833        .map_err(|e| err_at((*e.error()).into()))?
2834    };
2835    let (mut gain_buf, _) = extract_gain_map_internal(
2836        base_src,
2837        alternate_src,
2838        metadata,
2839        1,
2840        GainMapDownsample::Point,
2841        gm_spec,
2842        &ConvertPolicy::working_linear(),
2843        pulse,
2844        false,
2845    )?;
2846
2847    let base_owned = base_src
2848        .to_tight_buf()
2849        .map_err(|e| err_at((*e.error()).into()))?;
2850    gain_buf.set_orientation(base_src.orientation());
2851    let alt_color = if metadata.application_space() == GainMapColorSpace::Alternate
2852        || alternate_src.format().color() != base_src.format().color()
2853    {
2854        Some(alternate_src.format().color().clone())
2855    } else {
2856        None
2857    };
2858    match alt_color {
2859        Some(alt) => DualLayerHdrBuf::new_with_alternate_color(base_owned, gain_buf, metadata, alt),
2860        None => DualLayerHdrBuf::new(base_owned, gain_buf, metadata),
2861    }
2862    .map_err(|e| err_at((*e.error()).into()))
2863}
2864
2865type ObservedGainRange = Option<(f32, f32)>;
2866
2867#[inline(never)]
2868#[allow(clippy::too_many_arguments)]
2869fn extract_gain_map_internal(
2870    base_src: &PixelView<'_>,
2871    alternate_src: &PixelView<'_>,
2872    metadata: GainMapMetadata,
2873    scale_factor: u8,
2874    downsample: GainMapDownsample,
2875    gm_spec: PixelFormat,
2876    base_policy: &ConvertPolicy,
2877    pulse: Option<&dyn Pulse>,
2878    measure_only: bool,
2879) -> Result<(PixelBuf, ObservedGainRange), At<ConvertError>> {
2880    let pulse = live_pulse(pulse);
2881    check_pulse(pulse)?;
2882    let w = base_src.width();
2883    let h = base_src.height();
2884    if w == 0 || h == 0 || alternate_src.width() != w || alternate_src.height() != h {
2885        return Err(err_at(ConvertError::DimensionMismatch));
2886    }
2887    if base_src.orientation() != alternate_src.orientation() {
2888        return Err(err_at(ConvertError::UnsupportedRoute));
2889    }
2890    if !metadata.is_valid() {
2891        return Err(err_at(ConvertError::UnsupportedRoute));
2892    }
2893    let _ = metadata
2894        .direction()
2895        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
2896
2897    let (base_primaries, base_white_opt) = resolve_linear_rgb_primaries(base_src.format().color())
2898        .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?;
2899    let base_white = base_white_opt
2900        .or(base_policy.diffuse_white)
2901        .unwrap_or(DiffuseWhite::BT2408);
2902
2903    let app_primaries = match metadata.application_space() {
2904        GainMapColorSpace::Base => base_primaries,
2905        GainMapColorSpace::Alternate => {
2906            resolve_linear_rgb_primaries(alternate_src.format().color())
2907                .map(|(p, _)| p)
2908                .ok_or_else(|| err_at(ConvertError::UnsupportedRoute))?
2909        }
2910    };
2911
2912    let linear_rgb = PixelFormat::new(
2913        SampleLayout::RGBF32,
2914        app_primaries.to_color_space(
2915            Transfer::Linear,
2916            SignalRange::Full,
2917            AlphaMode::None,
2918            Some(base_white),
2919        ),
2920    )
2921    .map_err(|e| err_at((*e.error()).into()))?;
2922    let policy = base_policy
2923        .clone()
2924        .with_diffuse_white(base_white)
2925        .with_alpha(AlphaPolicy::DiscardUnchecked);
2926    let base_plan =
2927        RowPlan::build_with_pulse(base_src.format(), &linear_rgb, &policy, None, pulse)?;
2928    let alt_plan =
2929        RowPlan::build_with_pulse(alternate_src.format(), &linear_rgb, &policy, None, pulse)?;
2930
2931    let scale = u32::from(scale_factor.max(1));
2932    let gm_w = w.div_ceil(scale);
2933    let gm_h = h.div_ceil(scale);
2934
2935    let mut extractor = GainMapRowExtractor::new_with_luma(metadata, app_primaries.luma_weights())?;
2936    let mut gain_buf = if measure_only {
2937        PixelBuf::new(1, 1, gm_spec.clone()).map_err(|e| err_at((*e.error()).into()))?
2938    } else {
2939        PixelBuf::new(gm_w, gm_h, gm_spec.clone())
2940            .map_err(|e| err_at((*e.error()).into()))?
2941            .with_orientation(base_src.orientation())
2942    };
2943
2944    let row_floats = (w as usize)
2945        .checked_mul(3)
2946        .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
2947    let gm_floats = (gm_w as usize)
2948        .checked_mul(3)
2949        .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
2950    let mut base_row = alloc_f32(row_floats)?;
2951    let mut alt_row = alloc_f32(row_floats)?;
2952
2953    let mut dummy_row = Vec::new();
2954    if measure_only {
2955        let b = (gm_w as usize)
2956            .checked_mul(gm_spec.layout().bytes_per_pixel())
2957            .ok_or_else(|| err_at(ConvertError::DimensionMismatch))?;
2958        dummy_row
2959            .try_reserve_exact(b)
2960            .map_err(|_| err_at(ConvertError::AllocationFailed))?;
2961        dummy_row.resize(b, 0u8);
2962    }
2963
2964    if scale == 1 {
2965        let mut gm_v = gain_buf.as_view_mut();
2966        for y in 0..h {
2967            base_plan.convert_row_at(
2968                y,
2969                base_src.row(y),
2970                bytemuck::cast_slice_mut(&mut base_row),
2971                w,
2972            )?;
2973            alt_plan.convert_row_at(
2974                y,
2975                alternate_src.row(y),
2976                bytemuck::cast_slice_mut(&mut alt_row),
2977                w,
2978            )?;
2979            let dst_slice = if measure_only {
2980                &mut dummy_row[..]
2981            } else {
2982                gm_v.row_mut(y)
2983            };
2984            extractor.encode_row_linear_f32(
2985                &base_row,
2986                &alt_row,
2987                LinearInputChannels::Rgb,
2988                gm_spec.layout(),
2989                dst_slice,
2990            )?;
2991            step_pulse(pulse, 1)?;
2992        }
2993        return Ok((gain_buf, extractor.observed_gain_stops()));
2994    }
2995
2996    // Subsampled extraction (scale > 1)
2997    let mut gm_base_row = alloc_f32(gm_floats)?;
2998    let mut gm_alt_row = alloc_f32(gm_floats)?;
2999    let mut gm_v = gain_buf.as_view_mut();
3000
3001    match downsample {
3002        GainMapDownsample::Point => {
3003            for gy in 0..gm_h {
3004                let y = (gy * scale + scale / 2).min(h - 1);
3005                base_plan.convert_row_at(
3006                    y,
3007                    base_src.row(y),
3008                    bytemuck::cast_slice_mut(&mut base_row),
3009                    w,
3010                )?;
3011                alt_plan.convert_row_at(
3012                    y,
3013                    alternate_src.row(y),
3014                    bytemuck::cast_slice_mut(&mut alt_row),
3015                    w,
3016                )?;
3017                for gx in 0..gm_w as usize {
3018                    let sx = ((gx as u32 * scale + scale / 2).min(w - 1)) as usize * 3;
3019                    let dx = gx * 3;
3020                    gm_base_row[dx..dx + 3].copy_from_slice(&base_row[sx..sx + 3]);
3021                    gm_alt_row[dx..dx + 3].copy_from_slice(&alt_row[sx..sx + 3]);
3022                }
3023                let dst_slice = if measure_only {
3024                    &mut dummy_row[..]
3025                } else {
3026                    gm_v.row_mut(gy)
3027                };
3028                extractor.encode_row_linear_f32(
3029                    &gm_base_row,
3030                    &gm_alt_row,
3031                    LinearInputChannels::Rgb,
3032                    gm_spec.layout(),
3033                    dst_slice,
3034                )?;
3035                step_pulse(pulse, 1)?;
3036            }
3037        }
3038        GainMapDownsample::Box => {
3039            for gy in 0..gm_h {
3040                let y0 = gy * scale;
3041                let y1 = (y0 + scale).min(h);
3042                let rows_in_box = (y1 - y0).max(1) as f32;
3043                gm_base_row.fill(0.0);
3044                gm_alt_row.fill(0.0);
3045                for y in y0..y1 {
3046                    base_plan.convert_row_at(
3047                        y,
3048                        base_src.row(y),
3049                        bytemuck::cast_slice_mut(&mut base_row),
3050                        w,
3051                    )?;
3052                    alt_plan.convert_row_at(
3053                        y,
3054                        alternate_src.row(y),
3055                        bytemuck::cast_slice_mut(&mut alt_row),
3056                        w,
3057                    )?;
3058                    for gx in 0..gm_w {
3059                        let x0 = gx * scale;
3060                        let x1 = (x0 + scale).min(w);
3061                        let inv_x = 1.0 / ((x1 - x0).max(1) as f32);
3062                        let mut br = 0.0f32;
3063                        let mut bg = 0.0f32;
3064                        let mut bb = 0.0f32;
3065                        let mut ar = 0.0f32;
3066                        let mut ag = 0.0f32;
3067                        let mut ab = 0.0f32;
3068                        for x in x0..x1 {
3069                            let o = (x as usize) * 3;
3070                            br += base_row[o];
3071                            bg += base_row[o + 1];
3072                            bb += base_row[o + 2];
3073                            ar += alt_row[o];
3074                            ag += alt_row[o + 1];
3075                            ab += alt_row[o + 2];
3076                        }
3077                        let d = (gx as usize) * 3;
3078                        gm_base_row[d] += br * inv_x;
3079                        gm_base_row[d + 1] += bg * inv_x;
3080                        gm_base_row[d + 2] += bb * inv_x;
3081                        gm_alt_row[d] += ar * inv_x;
3082                        gm_alt_row[d + 1] += ag * inv_x;
3083                        gm_alt_row[d + 2] += ab * inv_x;
3084                    }
3085                }
3086                let inv_y = 1.0 / rows_in_box;
3087                for v in &mut gm_base_row {
3088                    *v *= inv_y;
3089                }
3090                for v in &mut gm_alt_row {
3091                    *v *= inv_y;
3092                }
3093                let dst_slice = if measure_only {
3094                    &mut dummy_row[..]
3095                } else {
3096                    gm_v.row_mut(gy)
3097                };
3098                extractor.encode_row_linear_f32(
3099                    &gm_base_row,
3100                    &gm_alt_row,
3101                    LinearInputChannels::Rgb,
3102                    gm_spec.layout(),
3103                    dst_slice,
3104                )?;
3105                step_pulse(pulse, 1)?;
3106            }
3107        }
3108        GainMapDownsample::Bilinear => {
3109            let hw = AxisWeights::try_new(
3110                w,
3111                gm_w,
3112                GainMapResample::Bilinear,
3113                MAX_EXTRACT_RESAMPLE_TAPS,
3114            )
3115            .map_err(err_at)?;
3116            let vw = AxisWeights::try_new(
3117                h,
3118                gm_h,
3119                GainMapResample::Bilinear,
3120                MAX_EXTRACT_RESAMPLE_TAPS,
3121            )
3122            .map_err(err_at)?;
3123            for gy in 0..gm_h {
3124                let (y_left, y_ws) = vw.taps(gy as usize);
3125                gm_base_row.fill(0.0);
3126                gm_alt_row.fill(0.0);
3127                for (yt, &wy) in y_ws.iter().enumerate() {
3128                    let y = y_left + yt as u32;
3129                    base_plan.convert_row_at(
3130                        y,
3131                        base_src.row(y),
3132                        bytemuck::cast_slice_mut(&mut base_row),
3133                        w,
3134                    )?;
3135                    alt_plan.convert_row_at(
3136                        y,
3137                        alternate_src.row(y),
3138                        bytemuck::cast_slice_mut(&mut alt_row),
3139                        w,
3140                    )?;
3141                    for gx in 0..gm_w as usize {
3142                        let (x_left, x_ws) = hw.taps(gx);
3143                        let xl = x_left as usize;
3144                        let mut br = 0.0f32;
3145                        let mut bg = 0.0f32;
3146                        let mut bb = 0.0f32;
3147                        let mut ar = 0.0f32;
3148                        let mut ag = 0.0f32;
3149                        let mut ab = 0.0f32;
3150                        for (xt, &wx) in x_ws.iter().enumerate() {
3151                            let o = (xl + xt) * 3;
3152                            br += base_row[o] * wx;
3153                            bg += base_row[o + 1] * wx;
3154                            bb += base_row[o + 2] * wx;
3155                            ar += alt_row[o] * wx;
3156                            ag += alt_row[o + 1] * wx;
3157                            ab += alt_row[o + 2] * wx;
3158                        }
3159                        let d = gx * 3;
3160                        gm_base_row[d] += br * wy;
3161                        gm_base_row[d + 1] += bg * wy;
3162                        gm_base_row[d + 2] += bb * wy;
3163                        gm_alt_row[d] += ar * wy;
3164                        gm_alt_row[d + 1] += ag * wy;
3165                        gm_alt_row[d + 2] += ab * wy;
3166                    }
3167                }
3168                let dst_slice = if measure_only {
3169                    &mut dummy_row[..]
3170                } else {
3171                    gm_v.row_mut(gy)
3172                };
3173                extractor.encode_row_linear_f32(
3174                    &gm_base_row,
3175                    &gm_alt_row,
3176                    LinearInputChannels::Rgb,
3177                    gm_spec.layout(),
3178                    dst_slice,
3179                )?;
3180                step_pulse(pulse, 1)?;
3181            }
3182        }
3183    }
3184
3185    Ok((gain_buf, extractor.observed_gain_stops()))
3186}
3187
3188fn resolve_linear_rgb_primaries(
3189    color: &ColorSpace,
3190) -> Option<(crate::plan::RgbPrimaries, Option<DiffuseWhite>)> {
3191    use crate::plan::RgbPrimaries;
3192    match color {
3193        ColorSpace::Rgb {
3194            primaries,
3195            diffuse_white,
3196            ..
3197        } if *primaries != Primaries::Unknown => {
3198            Some((RgbPrimaries::Standard(*primaries), *diffuse_white))
3199        }
3200        ColorSpace::RgbCustom {
3201            primaries,
3202            diffuse_white,
3203            ..
3204        } => Some((RgbPrimaries::Custom(**primaries), *diffuse_white)),
3205        ColorSpace::Gray { diffuse_white, .. } => Some((RgbPrimaries::BT709, *diffuse_white)),
3206        ColorSpace::Icc { profile, .. } => {
3207            if let Some(id) = zenpixels::icc::IccIdentification::from_icc(profile)
3208                && id.primaries() != Primaries::Unknown
3209            {
3210                return Some((RgbPrimaries::Standard(id.primaries()), None));
3211            }
3212            let tag = zenpixels::CicpTag::from_icc(profile)?;
3213            if let Some(cp) = tag.custom_primaries() {
3214                return Some((RgbPrimaries::Custom(cp), None));
3215            }
3216            let primaries = tag.primaries()?;
3217            (primaries != Primaries::Unknown).then_some((RgbPrimaries::Standard(primaries), None))
3218        }
3219        _ => None,
3220    }
3221}