Skip to main content

zenpixels_convert/
measure.rs

1//! Streaming HDR content-light-level (MaxCLL / MaxFALL) measurement in O(1) row memory.
2//!
3//! Operates directly over any [`PixelSource`] (`PixelView`, `PixelBuf`, `BandedBuf`)
4//! using a stack-resident 64-pixel tile — **zero full-image F32 temporary buffer**.
5
6use alloc::boxed::Box;
7use how_far::Pulse;
8use whereat::At;
9use zenpixels::{
10    ColorSpace, ContentLightLevel, DiffuseWhite, HlgMode, HlgRendering, PixelFormat, PixelSource,
11    SampleType, Transfer,
12};
13
14use crate::accelerators::Accelerators;
15use crate::error::{ConvertError, err_at};
16use crate::policy::{ConvertPolicy, DepthPolicy, GamutPolicy};
17use crate::pulse::{check_pulse, live_pulse, step_pulse};
18use crate::tonemap::{BT2020_LB, BT2020_LG, BT2020_LR};
19
20/// Per-pixel reduction method for content-light-level measurement.
21#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
22#[non_exhaustive]
23pub enum LightLevelMethod {
24    /// `max(R, G, B)` per pixel — CTA-861.3 / HDR10 default.
25    #[default]
26    MaxRgb,
27    /// BT.2020 NCL luminance (`0.2627·R + 0.6780·G + 0.0593·B`).
28    LuminanceBt2020,
29}
30
31/// 1024-bin log2 histogram of per-pixel luminance in cd/m² over `[0.005, 10_000]` nits,
32/// tracking exact zero / non-positive counts separately from positive sub-bin samples.
33#[derive(Clone, Debug)]
34pub struct LightLevelHistogram {
35    bins: Box<[u64]>,
36    zero_count: u64,
37    total: u64,
38    sum_nits: f64,
39    literal_max_nits: f32,
40    method: LightLevelMethod,
41}
42
43impl LightLevelHistogram {
44    /// Lower bin edge (`0.005` cd/m²).
45    pub const BIN_MIN_NITS: f32 = 0.005;
46    /// Upper bin edge (`10_000.0` cd/m², ST 2084 PQ peak).
47    pub const BIN_MAX_NITS: f32 = 10_000.0;
48    /// Number of log2-spaced bins (`1024`, ~0.02 stops per bin).
49    pub const NUM_BINS: usize = 1024;
50
51    const LOG2_MIN: f32 = -7.643_856;
52    const LOG2_MAX: f32 = 13.287_712;
53    const INV_SPAN: f32 = (Self::NUM_BINS - 1) as f32 / (Self::LOG2_MAX - Self::LOG2_MIN);
54
55    /// Fallibly construct an empty histogram (returns `Err(ConvertError::AllocationFailed)` on OOM).
56    pub fn new(method: LightLevelMethod) -> Result<Self, At<ConvertError>> {
57        let mut bins = alloc::vec::Vec::new();
58        bins.try_reserve_exact(Self::NUM_BINS)
59            .map_err(|_| crate::error::err_at(ConvertError::AllocationFailed))?;
60        bins.resize(Self::NUM_BINS, 0u64);
61        Ok(Self {
62            bins: bins.into_boxed_slice(),
63            zero_count: 0,
64            total: 0,
65            sum_nits: 0.0,
66            literal_max_nits: 0.0,
67            method,
68        })
69    }
70
71    /// Record a single pixel's light level in cd/m².
72    #[inline]
73    pub fn record(&mut self, nits: f32) {
74        if !nits.is_finite() || nits <= 0.0 {
75            self.zero_count += 1;
76            self.total += 1;
77            return;
78        }
79        if nits > self.literal_max_nits {
80            self.literal_max_nits = nits;
81        }
82        self.sum_nits += f64::from(nits);
83        self.total += 1;
84        let idx = if nits <= Self::BIN_MIN_NITS {
85            0
86        } else if nits >= Self::BIN_MAX_NITS {
87            Self::NUM_BINS - 1
88        } else {
89            let l2 = libm::log2f(nits);
90            (((l2 - Self::LOG2_MIN) * Self::INV_SPAN) as usize).min(Self::NUM_BINS - 1)
91        };
92        self.bins[idx] += 1;
93    }
94
95    /// Read-only view of the 1024 log2-spaced luminance histogram bins.
96    #[inline]
97    #[must_use]
98    pub fn bins(&self) -> &[u64] {
99        &self.bins
100    }
101
102    /// Merge another [`LightLevelHistogram`] accumulated with the same [`LightLevelMethod`]
103    /// into `self` (useful for parallel tile/strip reduction).
104    ///
105    /// Returns [`ConvertError::UnsupportedRoute`] if `self.method() != other.method()`.
106    pub fn merge(&mut self, other: &Self) -> Result<(), At<ConvertError>> {
107        if self.method != other.method {
108            return Err(crate::error::err_at(ConvertError::UnsupportedRoute));
109        }
110        for (dst, &src) in self.bins.iter_mut().zip(other.bins.iter()) {
111            *dst = dst.saturating_add(src);
112        }
113        self.zero_count = self.zero_count.saturating_add(other.zero_count);
114        self.total = self.total.saturating_add(other.total);
115        self.sum_nits += other.sum_nits;
116        if other.literal_max_nits > self.literal_max_nits {
117            self.literal_max_nits = other.literal_max_nits;
118        }
119        Ok(())
120    }
121
122    /// Reduction method used to build this histogram.
123    #[inline]
124    #[must_use]
125    pub const fn method(&self) -> LightLevelMethod {
126        self.method
127    }
128
129    /// Total pixels recorded.
130    #[inline]
131    #[must_use]
132    pub const fn total_pixels(&self) -> u64 {
133        self.total
134    }
135
136    /// Number of recorded zero / non-positive / non-finite samples.
137    #[inline]
138    #[must_use]
139    pub const fn zero_pixels(&self) -> u64 {
140        self.zero_count
141    }
142
143    /// Exact literal maximum luminance observed in cd/m².
144    #[inline]
145    #[must_use]
146    pub const fn max_nits(&self) -> f32 {
147        self.literal_max_nits
148    }
149
150    /// Arithmetic mean luminance (MaxFALL) in cd/m².
151    #[inline]
152    #[must_use]
153    pub fn mean_nits(&self) -> f32 {
154        if self.total == 0 {
155            0.0
156        } else {
157            (self.sum_nits / self.total as f64) as f32
158        }
159    }
160
161    /// Nearest-rank order-statistic quantile readout (`quantile` in `0.0..=1.0`, e.g. `0.9999`).
162    ///
163    /// Uses rank `k = ceil(quantile * total).max(1)` over the sorted sample set (so
164    /// `quantile = 0.0` returns `0.0` when any black pixel was recorded, and `quantile = 0.5` on
165    /// `[0, 1, 100]` selects the 2nd sample ≈ `1.0`).
166    #[must_use]
167    pub fn quantile_nits(&self, quantile: f32) -> f32 {
168        if self.total == 0 {
169            return 0.0;
170        }
171        if quantile >= 1.0 {
172            return self.literal_max_nits;
173        }
174        let q_clamped = if quantile.is_nan() {
175            0.0
176        } else {
177            quantile.clamp(0.0, 1.0)
178        };
179        let rank = (libm::ceil((self.total as f64) * f64::from(q_clamped)) as u64).max(1);
180        if rank <= self.zero_count {
181            return 0.0;
182        }
183        let mut acc = self.zero_count;
184        for (i, &count) in self.bins.iter().enumerate() {
185            acc += count;
186            if acc >= rank {
187                if i == 0 {
188                    return Self::BIN_MIN_NITS.min(self.literal_max_nits);
189                }
190                let l2 = Self::LOG2_MIN + (i as f32) / Self::INV_SPAN;
191                return libm::exp2f(l2).min(self.literal_max_nits);
192            }
193        }
194        self.literal_max_nits
195    }
196
197    /// Convert literal max + mean into ITU-T H.274 / CTA-861.3 upper-bound [`ContentLightLevel`].
198    #[must_use]
199    pub fn to_content_light_level(&self) -> ContentLightLevel {
200        ContentLightLevel::new(
201            ceil_cll_u16(self.max_nits()),
202            ceil_cll_u16(self.mean_nits()),
203        )
204    }
205
206    /// Convert quantile peak (`quantile` in `0.0..=1.0`, e.g. `0.9999`) + mean into
207    /// [`ContentLightLevel`].
208    #[must_use]
209    pub fn to_robust_content_light_level(&self, quantile: f32) -> ContentLightLevel {
210        ContentLightLevel::new(
211            ceil_cll_u16(self.quantile_nits(quantile)),
212            ceil_cll_u16(self.mean_nits()),
213        )
214    }
215}
216
217#[inline]
218fn ceil_cll_u16(nits: f32) -> u16 {
219    if !nits.is_finite() || nits <= 0.0 {
220        return 0;
221    }
222    // Ceiling upper bound per ITU-T H.274 / CTA-861.3, with tiny relative guard so exact
223    // integer light levels with 1-ULP float rounding (e.g. 812.00006) do not jump by +1.
224    let v = f64::from(nits);
225    let adjusted = if v >= 1.0 { v * (1.0 - 1e-6) } else { v };
226    libm::ceil(adjusted).clamp(0.0, f64::from(u16::MAX)) as u16
227}
228
229fn measurement_linear_color(
230    spec: &PixelFormat,
231    white: DiffuseWhite,
232    method: LightLevelMethod,
233) -> ColorSpace {
234    match method {
235        LightLevelMethod::LuminanceBt2020 => ColorSpace::Rgb {
236            primaries: zenpixels::Primaries::Bt2020,
237            transfer: Transfer::Linear,
238            range: zenpixels::SignalRange::Full,
239            alpha: zenpixels::AlphaMode::None,
240            diffuse_white: Some(white),
241        },
242        LightLevelMethod::MaxRgb => match &spec.color() {
243            ColorSpace::Rgb { primaries, .. } if *primaries != zenpixels::Primaries::Unknown => {
244                ColorSpace::Rgb {
245                    primaries: *primaries,
246                    transfer: Transfer::Linear,
247                    range: zenpixels::SignalRange::Full,
248                    alpha: zenpixels::AlphaMode::None,
249                    diffuse_white: Some(white),
250                }
251            }
252            ColorSpace::RgbCustom { primaries, .. } => ColorSpace::RgbCustom {
253                primaries: primaries.clone(),
254                transfer: Transfer::Linear,
255                range: zenpixels::SignalRange::Full,
256                alpha: zenpixels::AlphaMode::None,
257                diffuse_white: Some(white),
258            },
259            _ => ColorSpace::Rgb {
260                primaries: zenpixels::Primaries::Bt2020,
261                transfer: Transfer::Linear,
262                range: zenpixels::SignalRange::Full,
263                alpha: zenpixels::AlphaMode::None,
264                diffuse_white: Some(white),
265            },
266        },
267    }
268}
269
270/// Measure a full [`LightLevelHistogram`] over any [`PixelSource`] in O(1) row scratch memory.
271///
272/// For [`LightLevelMethod::MaxRgb`], RGB inputs are measured in their **native RGB primaries**
273/// (CTA-861.3 / ITU-T H.274 MaxCLL definition); for [`LightLevelMethod::LuminanceBt2020`],
274/// pixels are linearized into BT.2020 to compute CIE Y luminance.
275#[inline]
276pub fn measure_histogram<S: PixelSource + ?Sized>(
277    src: &S,
278    white: DiffuseWhite,
279    hlg_rendering: Option<HlgRendering>,
280    method: LightLevelMethod,
281) -> Result<LightLevelHistogram, At<ConvertError>> {
282    measure_histogram_dyn(
283        &crate::plan::RefSource(src),
284        white,
285        hlg_rendering,
286        method,
287        None,
288    )
289}
290
291/// Measure a full [`LightLevelHistogram`] over any [`PixelSource`] in O(1) row scratch memory
292/// with optional cooperative cancellation and row progress via `pulse` (pass `None` when not
293/// needed).
294#[inline]
295pub fn measure_histogram_with_pulse<S: PixelSource + ?Sized>(
296    src: &S,
297    white: DiffuseWhite,
298    hlg_rendering: Option<HlgRendering>,
299    method: LightLevelMethod,
300    pulse: Option<&dyn Pulse>,
301) -> Result<LightLevelHistogram, At<ConvertError>> {
302    measure_histogram_dyn(
303        &crate::plan::RefSource(src),
304        white,
305        hlg_rendering,
306        method,
307        pulse,
308    )
309}
310
311#[inline(never)]
312fn measure_histogram_dyn(
313    src: &dyn PixelSource,
314    white: DiffuseWhite,
315    hlg_rendering: Option<HlgRendering>,
316    method: LightLevelMethod,
317    pulse: Option<&dyn Pulse>,
318) -> Result<LightLevelHistogram, At<ConvertError>> {
319    let pulse = live_pulse(pulse);
320    check_pulse(pulse)?;
321    let spec = src.source_format();
322    let w = src.source_width();
323    let h = src.source_height();
324    let mut hist = LightLevelHistogram::new(method)?;
325    if w == 0 || h == 0 {
326        return Ok(hist);
327    }
328
329    let linear_spec = PixelFormat::new(
330        zenpixels::SampleLayout::RGBF32,
331        measurement_linear_color(spec, white, method),
332    )
333    .map_err(|e| err_at((*e.error()).into()))?;
334    let mut policy = ConvertPolicy::working_linear()
335        .with_diffuse_white(white)
336        .with_depth(DepthPolicy::Round)
337        .with_gamut(GamutPolicy::PreserveExtended)
338        .with_alpha(crate::policy::AlphaPolicy::DiscardUnchecked)
339        .with_accelerators(Accelerators::default());
340    if let Some(r) = hlg_rendering {
341        policy = policy.with_hlg_rendering(r);
342    }
343    let row_plan =
344        crate::plan::RowPlan::build_with_pulse(spec, &linear_spec, &policy, None, pulse)?;
345
346    // Single reusable fallibly-allocated, 4-byte-aligned f32 scratch row
347    // (O(width) = a few KiB, NEVER O(width * height), safe on odd allocators!).
348    let num_floats = (w as usize)
349        .checked_mul(3)
350        .ok_or_else(|| crate::error::err_at(ConvertError::DimensionMismatch))?;
351    let mut scratch_f32: alloc::vec::Vec<f32> = alloc::vec::Vec::new();
352    scratch_f32
353        .try_reserve_exact(num_floats)
354        .map_err(|_| crate::error::err_at(ConvertError::AllocationFailed))?;
355    scratch_f32.resize(num_floats, 0.0f32);
356    let white_nits = white.nits();
357    for y in 0..h {
358        let scratch_bytes: &mut [u8] = bytemuck::cast_slice_mut(&mut scratch_f32);
359        row_plan.convert_row_at(y, src.source_row(y), scratch_bytes, w)?;
360        for px in scratch_f32.as_chunks::<3>().0 {
361            let v = match method {
362                LightLevelMethod::MaxRgb => px[0].max(px[1]).max(px[2]),
363                LightLevelMethod::LuminanceBt2020 => {
364                    BT2020_LR * px[0] + BT2020_LG * px[1] + BT2020_LB * px[2]
365                }
366            };
367            hist.record(v * white_nits);
368        }
369        step_pulse(pulse, 1)?;
370    }
371    Ok(hist)
372}
373
374/// Measure [`ContentLightLevel`] (literal MaxCLL + MaxFALL) over any [`PixelSource`] in O(1) row memory.
375#[inline]
376pub fn measure_content_light_level<S: PixelSource + ?Sized>(
377    src: &S,
378    white: DiffuseWhite,
379    hlg_rendering: Option<HlgRendering>,
380    method: LightLevelMethod,
381) -> Result<ContentLightLevel, At<ConvertError>> {
382    Ok(measure_histogram_dyn(
383        &crate::plan::RefSource(src),
384        white,
385        hlg_rendering,
386        method,
387        None,
388    )?
389    .to_content_light_level())
390}
391
392/// Measure [`ContentLightLevel`] (literal MaxCLL + MaxFALL) over any [`PixelSource`] with
393/// optional cooperative cancellation and row progress via `pulse` (pass `None` when not needed).
394#[inline]
395pub fn measure_content_light_level_with_pulse<S: PixelSource + ?Sized>(
396    src: &S,
397    white: DiffuseWhite,
398    hlg_rendering: Option<HlgRendering>,
399    method: LightLevelMethod,
400    pulse: Option<&dyn Pulse>,
401) -> Result<ContentLightLevel, At<ConvertError>> {
402    Ok(measure_histogram_dyn(
403        &crate::plan::RefSource(src),
404        white,
405        hlg_rendering,
406        method,
407        pulse,
408    )?
409    .to_content_light_level())
410}
411
412/// 3-tap mirror-padded horizontal box filter over one linear-light RGB(A) f32 row.
413/// Returns `(max_smoothed_rel, sum_rel)` in diffuse-white-relative units.
414#[inline]
415fn scan_row_max_mean_smoothed<const N: usize>(row: &[f32], method: LightLevelMethod) -> (f32, f64) {
416    const ONE_THIRD: f32 = 1.0 / 3.0;
417    let pixel_count = row.len() / N;
418    if pixel_count == 0 {
419        return (0.0, 0.0);
420    }
421
422    let reduce_at = |i: usize| -> f32 {
423        let px = &row[i * N..(i + 1) * N];
424        let r = if px[0].is_finite() {
425            px[0].max(0.0)
426        } else {
427            0.0
428        };
429        let g = if px[1].is_finite() {
430            px[1].max(0.0)
431        } else {
432            0.0
433        };
434        let b = if px[2].is_finite() {
435            px[2].max(0.0)
436        } else {
437            0.0
438        };
439        match method {
440            LightLevelMethod::MaxRgb => r.max(g).max(b),
441            LightLevelMethod::LuminanceBt2020 => BT2020_LR * r + BT2020_LG * g + BT2020_LB * b,
442        }
443    };
444
445    if pixel_count == 1 {
446        let m = reduce_at(0);
447        return (m, f64::from(m));
448    }
449    if pixel_count == 2 {
450        let m0 = reduce_at(0);
451        let m1 = reduce_at(1);
452        let s0 = (2.0 * m0 + m1) * ONE_THIRD;
453        let s1 = (m0 + 2.0 * m1) * ONE_THIRD;
454        return (s0.max(s1), f64::from(m0) + f64::from(m1));
455    }
456
457    let m0 = reduce_at(0);
458    let m1 = reduce_at(1);
459    let mut prev = m0;
460    let mut curr = m1;
461    let mut max_x3 = 2.0 * m0 + m1;
462    let mut sum = f64::from(m0);
463
464    for i in 2..pixel_count {
465        let next = reduce_at(i);
466        let s = prev + curr + next;
467        if s > max_x3 {
468            max_x3 = s;
469        }
470        sum += f64::from(curr);
471        prev = curr;
472        curr = next;
473    }
474    let s_last = prev + 2.0 * curr;
475    if s_last > max_x3 {
476        max_x3 = s_last;
477    }
478    sum += f64::from(curr);
479
480    (max_x3 * ONE_THIRD, sum)
481}
482
483/// Measure defect-tolerant [`ContentLightLevel`] using a 3-tap horizontal mirror-padded
484/// box filter on per-pixel light levels (`(m[i-1] + m[i] + m[i+1]) / 3`) in O(1) row memory.
485///
486/// Suppresses isolated stuck/hot pixels by 3× while preserving bright features spanning
487/// ≥2 horizontal pixels; MaxFALL remains the exact arithmetic mean across all pixels.
488#[inline]
489pub fn measure_max_smoothed<S: PixelSource + ?Sized>(
490    src: &S,
491    white: DiffuseWhite,
492    hlg_rendering: Option<HlgRendering>,
493    method: LightLevelMethod,
494) -> Result<ContentLightLevel, At<ConvertError>> {
495    measure_max_smoothed_dyn(
496        &crate::plan::RefSource(src),
497        white,
498        hlg_rendering,
499        method,
500        None,
501    )
502}
503
504/// Measure defect-tolerant [`ContentLightLevel`] using a 3-tap horizontal mirror-padded box
505/// filter with optional cooperative cancellation and row progress via `pulse` (pass `None`
506/// when not needed).
507#[inline]
508pub fn measure_max_smoothed_with_pulse<S: PixelSource + ?Sized>(
509    src: &S,
510    white: DiffuseWhite,
511    hlg_rendering: Option<HlgRendering>,
512    method: LightLevelMethod,
513    pulse: Option<&dyn Pulse>,
514) -> Result<ContentLightLevel, At<ConvertError>> {
515    measure_max_smoothed_dyn(
516        &crate::plan::RefSource(src),
517        white,
518        hlg_rendering,
519        method,
520        pulse,
521    )
522}
523
524#[inline(never)]
525fn measure_max_smoothed_dyn(
526    src: &dyn PixelSource,
527    white: DiffuseWhite,
528    hlg_rendering: Option<HlgRendering>,
529    method: LightLevelMethod,
530    pulse: Option<&dyn Pulse>,
531) -> Result<ContentLightLevel, At<ConvertError>> {
532    let pulse = live_pulse(pulse);
533    check_pulse(pulse)?;
534    let spec = src.source_format();
535    let w = src.source_width();
536    let h = src.source_height();
537    if w == 0 || h == 0 {
538        return Ok(ContentLightLevel::new(0, 0));
539    }
540    let total_px = (w as f64) * (h as f64);
541
542    // Zero-allocation fast path for unpremultiplied full-packing Linear F32 RGB(A) in matching primaries.
543    let target_linear_color = measurement_linear_color(spec, white, method);
544    let fast_linear_match = match &spec.color() {
545        ColorSpace::Rgb {
546            transfer: Transfer::Linear,
547            range: zenpixels::SignalRange::Full,
548            alpha,
549            diffuse_white: src_white,
550            ..
551        }
552        | ColorSpace::RgbCustom {
553            transfer: Transfer::Linear,
554            range: zenpixels::SignalRange::Full,
555            alpha,
556            diffuse_white: src_white,
557            ..
558        } if spec.color().same_rgb_chromaticity(&target_linear_color)
559            && *alpha != zenpixels::AlphaMode::Premultiplied =>
560        {
561            Some(*src_white)
562        }
563        _ => None,
564    };
565    if spec.layout().packing().is_full()
566        && spec.layout().sample() == SampleType::F32
567        && matches!(
568            spec.layout().order(),
569            zenpixels::ChannelOrder::Rgb | zenpixels::ChannelOrder::Rgba
570        )
571        && let Some(src_white) = fast_linear_match
572    {
573        let ch = spec.layout().channels();
574        let eff_white = src_white.unwrap_or(white).nits();
575        let mut max_rel = 0.0_f32;
576        let mut sum_rel = 0.0_f64;
577        let mut aligned_scratch: alloc::vec::Vec<f32> = alloc::vec::Vec::new();
578        for y in 0..h {
579            let row = src.source_row(y);
580            let floats: &[f32] = if let Ok(f) = bytemuck::try_cast_slice::<u8, f32>(row) {
581                f
582            } else {
583                let need = (w as usize) * ch;
584                if aligned_scratch.len() < need {
585                    aligned_scratch
586                        .try_reserve_exact(need - aligned_scratch.len())
587                        .map_err(|_| crate::error::err_at(ConvertError::AllocationFailed))?;
588                    aligned_scratch.resize(need, 0.0);
589                }
590                for (dst_f, chunk) in aligned_scratch[..need]
591                    .iter_mut()
592                    .zip(row.as_chunks::<4>().0)
593                {
594                    *dst_f = f32::from_ne_bytes(*chunk);
595                }
596                &aligned_scratch[..need]
597            };
598            let (rm, rs) = if ch == 3 {
599                scan_row_max_mean_smoothed::<3>(floats, method)
600            } else {
601                scan_row_max_mean_smoothed::<4>(floats, method)
602            };
603            if rm > max_rel {
604                max_rel = rm;
605            }
606            sum_rel += rs;
607            step_pulse(pulse, 1)?;
608        }
609        return Ok(ContentLightLevel::new(
610            ceil_cll_u16(max_rel * eff_white),
611            ceil_cll_u16(((sum_rel / total_px) * f64::from(eff_white)) as f32),
612        ));
613    }
614
615    // General streaming path: 1 fallibly-allocated RGBF32 row via RowPlan.
616    let linear_spec = PixelFormat::new(zenpixels::SampleLayout::RGBF32, target_linear_color)
617        .map_err(|e| err_at((*e.error()).into()))?;
618    let mut policy = ConvertPolicy::working_linear()
619        .with_diffuse_white(white)
620        .with_depth(DepthPolicy::Round)
621        .with_gamut(GamutPolicy::PreserveExtended)
622        .with_alpha(crate::policy::AlphaPolicy::DiscardUnchecked)
623        .with_accelerators(Accelerators::default());
624    if let Some(r) = hlg_rendering {
625        policy = policy.with_hlg_rendering(r);
626    }
627    let row_plan =
628        crate::plan::RowPlan::build_with_pulse(spec, &linear_spec, &policy, None, pulse)?;
629
630    let num_floats = (w as usize)
631        .checked_mul(3)
632        .ok_or_else(|| crate::error::err_at(ConvertError::DimensionMismatch))?;
633    let mut scratch_f32: alloc::vec::Vec<f32> = alloc::vec::Vec::new();
634    scratch_f32
635        .try_reserve_exact(num_floats)
636        .map_err(|_| crate::error::err_at(ConvertError::AllocationFailed))?;
637    scratch_f32.resize(num_floats, 0.0f32);
638
639    let white_nits = white.nits();
640    let mut max_rel = 0.0_f32;
641    let mut sum_rel = 0.0_f64;
642    for y in 0..h {
643        let scratch_bytes: &mut [u8] = bytemuck::cast_slice_mut(&mut scratch_f32);
644        row_plan.convert_row_at(y, src.source_row(y), scratch_bytes, w)?;
645        let (rm, rs) = scan_row_max_mean_smoothed::<3>(&scratch_f32, method);
646        if rm > max_rel {
647            max_rel = rm;
648        }
649        sum_rel += rs;
650        step_pulse(pulse, 1)?;
651    }
652    Ok(ContentLightLevel::new(
653        ceil_cll_u16(max_rel * white_nits),
654        ceil_cll_u16(((sum_rel / total_px) * f64::from(white_nits)) as f32),
655    ))
656}
657
658/// Fast zero-histogram streaming max-luminance peak scan in cd/m² (O(1) row scratch).
659///
660/// Measures native-primaries `MaxRgb` peak luminance without building a log histogram,
661/// allocating at most one fallibly-reserved `f32` row (or zero bytes on unpremultiplied
662/// Linear F32 / Full PQ U16 RGB sources).
663#[inline]
664pub fn measure_peak<S: PixelSource + ?Sized>(
665    src: &S,
666    white: DiffuseWhite,
667    hlg_rendering: Option<HlgRendering>,
668) -> Result<f32, At<ConvertError>> {
669    measure_max_nits_streaming_dyn(&crate::plan::RefSource(src), white, hlg_rendering, None)
670}
671
672/// Fast zero-histogram streaming max-luminance peak scan in cd/m² with optional cooperative
673/// cancellation and row progress via `pulse` (pass `None` when not needed).
674#[inline]
675pub fn measure_peak_with_pulse<S: PixelSource + ?Sized>(
676    src: &S,
677    white: DiffuseWhite,
678    hlg_rendering: Option<HlgRendering>,
679    pulse: Option<&dyn Pulse>,
680) -> Result<f32, At<ConvertError>> {
681    measure_max_nits_streaming_dyn(&crate::plan::RefSource(src), white, hlg_rendering, pulse)
682}
683
684/// Fast zero-histogram streaming max-luminance peak scan in cd/m² (O(1) row scratch).
685#[inline(never)]
686pub(crate) fn measure_max_nits_streaming_dyn(
687    src: &dyn PixelSource,
688    white: DiffuseWhite,
689    hlg_rendering: Option<HlgRendering>,
690    pulse: Option<&dyn Pulse>,
691) -> Result<f32, At<ConvertError>> {
692    let pulse = live_pulse(pulse);
693    check_pulse(pulse)?;
694    let spec = src.source_format();
695    let w = src.source_width();
696    let h = src.source_height();
697    if w == 0 || h == 0 {
698        return Ok(0.0);
699    }
700
701    // Zero-allocation fast paths for unpremultiplied native-primaries Linear F32 or Full PQ U16 RGB.
702    if spec.layout().packing().is_full() {
703        let fast_lin_white = match &spec.color() {
704            ColorSpace::Rgb {
705                primaries,
706                transfer: Transfer::Linear,
707                range: zenpixels::SignalRange::Full,
708                alpha,
709                diffuse_white: src_white,
710            } if *primaries != zenpixels::Primaries::Unknown
711                && *alpha != zenpixels::AlphaMode::Premultiplied =>
712            {
713                Some(*src_white)
714            }
715            ColorSpace::RgbCustom {
716                transfer: Transfer::Linear,
717                range: zenpixels::SignalRange::Full,
718                alpha,
719                diffuse_white: src_white,
720                ..
721            } if *alpha != zenpixels::AlphaMode::Premultiplied => Some(*src_white),
722            _ => None,
723        };
724        if let Some(src_white) = fast_lin_white
725            && spec.layout().sample() == SampleType::F32
726        {
727            let ch = spec.layout().channels();
728            let eff_white = src_white.unwrap_or(white).nits();
729            let mut max_v = 0.0f32;
730            for y in 0..h {
731                let row = src.source_row(y);
732                for px in row.chunks_exact(ch * 4) {
733                    for c in 0..3 {
734                        let v = f32::from_ne_bytes(px[c * 4..c * 4 + 4].try_into().unwrap());
735                        if v.is_finite() && v > max_v {
736                            max_v = v;
737                        }
738                    }
739                }
740                step_pulse(pulse, 1)?;
741            }
742            return Ok(max_v * eff_white);
743        }
744        let fast_pq = matches!(
745            &spec.color(),
746            ColorSpace::Rgb {
747                primaries,
748                transfer: Transfer::Pq,
749                range: zenpixels::SignalRange::Full,
750                alpha,
751                ..
752            } if *primaries != zenpixels::Primaries::Unknown
753                && *alpha != zenpixels::AlphaMode::Premultiplied
754        ) || matches!(
755            &spec.color(),
756            ColorSpace::RgbCustom {
757                transfer: Transfer::Pq,
758                range: zenpixels::SignalRange::Full,
759                alpha,
760                ..
761            } if *alpha != zenpixels::AlphaMode::Premultiplied
762        );
763        if fast_pq && spec.layout().sample() == SampleType::U16 {
764            let ch = spec.layout().channels();
765            let mut max_code = 0u16;
766            for y in 0..h {
767                let row = src.source_row(y);
768                for px in row.chunks_exact(ch * 2) {
769                    for c in 0..3 {
770                        let v = u16::from_ne_bytes([px[c * 2], px[c * 2 + 1]]);
771                        if v > max_code {
772                            max_code = v;
773                        }
774                    }
775                }
776                step_pulse(pulse, 1)?;
777            }
778            // Use the exact same PQ EOTF as the row pipeline for 100% consistent peak definition.
779            let mut norm = [f32::from(max_code) * (1.0 / 65535.0)];
780            #[cfg(feature = "hdr-transfers")]
781            crate::transfers::hdr::pq_eotf_scalar_slice(&mut norm, 10_000.0);
782            #[cfg(not(feature = "hdr-transfers"))]
783            {
784                norm[0] = crate::strip::pq_eotf_scalar(norm[0]) * 10_000.0;
785            }
786            return Ok(norm[0]);
787        }
788    }
789
790    // General zero-histogram streaming max reducer: 1 fallibly-allocated f32 row via RowPlan!
791    let eff_hlg = match &spec.color() {
792        ColorSpace::Rgb {
793            transfer: Transfer::Hlg(HlgMode::Display(r)),
794            ..
795        }
796        | ColorSpace::RgbCustom {
797            transfer: Transfer::Hlg(HlgMode::Display(r)),
798            ..
799        } => Some(*r),
800        _ => hlg_rendering,
801    };
802    let linear_spec = PixelFormat::new(
803        zenpixels::SampleLayout::RGBF32,
804        measurement_linear_color(spec, white, LightLevelMethod::MaxRgb),
805    )
806    .map_err(|e| err_at((*e.error()).into()))?;
807    let mut policy = ConvertPolicy::working_linear()
808        .with_diffuse_white(white)
809        .with_depth(DepthPolicy::Round)
810        .with_gamut(GamutPolicy::PreserveExtended)
811        .with_alpha(crate::policy::AlphaPolicy::DiscardUnchecked)
812        .with_accelerators(Accelerators::default());
813    if let Some(r) = eff_hlg {
814        policy = policy.with_hlg_rendering(r);
815    }
816    let row_plan =
817        crate::plan::RowPlan::build_with_pulse(spec, &linear_spec, &policy, None, pulse)?;
818
819    let num_floats = (w as usize)
820        .checked_mul(3)
821        .ok_or_else(|| crate::error::err_at(ConvertError::DimensionMismatch))?;
822    let mut scratch_f32: alloc::vec::Vec<f32> = alloc::vec::Vec::new();
823    scratch_f32
824        .try_reserve_exact(num_floats)
825        .map_err(|_| crate::error::err_at(ConvertError::AllocationFailed))?;
826    scratch_f32.resize(num_floats, 0.0f32);
827
828    let white_nits = white.nits();
829    let mut max_v = 0.0f32;
830    for y in 0..h {
831        let scratch_bytes: &mut [u8] = bytemuck::cast_slice_mut(&mut scratch_f32);
832        row_plan.convert_row_at(y, src.source_row(y), scratch_bytes, w)?;
833        for &v in &scratch_f32 {
834            if v.is_finite() && v > max_v {
835                max_v = v;
836            }
837        }
838        step_pulse(pulse, 1)?;
839    }
840    Ok(max_v * white_nits)
841}