1use 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#[derive(Copy, Clone, Debug, Default, PartialEq, Eq, Hash)]
22#[non_exhaustive]
23pub enum LightLevelMethod {
24 #[default]
26 MaxRgb,
27 LuminanceBt2020,
29}
30
31#[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 pub const BIN_MIN_NITS: f32 = 0.005;
46 pub const BIN_MAX_NITS: f32 = 10_000.0;
48 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 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 #[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 #[inline]
97 #[must_use]
98 pub fn bins(&self) -> &[u64] {
99 &self.bins
100 }
101
102 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 #[inline]
124 #[must_use]
125 pub const fn method(&self) -> LightLevelMethod {
126 self.method
127 }
128
129 #[inline]
131 #[must_use]
132 pub const fn total_pixels(&self) -> u64 {
133 self.total
134 }
135
136 #[inline]
138 #[must_use]
139 pub const fn zero_pixels(&self) -> u64 {
140 self.zero_count
141 }
142
143 #[inline]
145 #[must_use]
146 pub const fn max_nits(&self) -> f32 {
147 self.literal_max_nits
148 }
149
150 #[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 #[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 #[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 #[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 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#[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#[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 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#[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#[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#[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#[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#[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 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 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#[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#[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#[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 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 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 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}