zenpixels_convert/tonemap/tone_mapper.rs
1//! Pluggable HDR→SDR tone mapping for [`RowPlan`](crate::RowPlan) and [`ImagePlan`](crate::ImagePlan).
2
3use alloc::boxed::Box;
4use core::fmt::Debug;
5use core::panic::{RefUnwindSafe, UnwindSafe};
6
7use how_far::Pulse;
8use zenpixels::Primaries;
9
10/// Pluggable HDR→SDR tone mapper for [`RowPlan`](crate::RowPlan) and [`ImagePlan`](crate::ImagePlan).
11///
12/// Implementations declare their analysis needs via
13/// [`requirements`](Self::requirements), then receive the gathered
14/// [`ToneMapContext`] in [`prepare`](Self::prepare) and produce a
15/// [`PreparedMapper`] — typically a [`StripMapper`] with image-specific
16/// coefficients precomputed.
17///
18/// The trait is **object-safe**: [`ConvertPolicy`](crate::ConvertPolicy)
19/// stores `Arc<dyn ToneMapper>` internally, so the dispatch table never
20/// has to know the concrete mapper type.
21///
22/// # Invariants
23///
24/// - **Pure and deterministic.** Given `&self` and a `ToneMapContext`,
25/// every method must be a pure function of its inputs. Interior
26/// mutability that perturbs output is forbidden.
27/// - **`Send + Sync + UnwindSafe + RefUnwindSafe + Debug`.** The
28/// supertrait bounds are required so plans (which are `Clone + Debug`)
29/// keep their auto-traits across the `Arc<dyn ToneMapper>` field
30/// stored on `ConvertStep::ToneMap`. Mappers are pure functions of
31/// their inputs and pose no panic-safety hazard; concrete
32/// implementations virtually always satisfy this without thought
33/// (any `#[derive(Debug)]` struct of plain numeric / `Arc` fields
34/// does).
35/// - **Stable [`name`](Self::name).** The string is consumed by
36/// diagnostics, trace recorders, and estimate / oracle cache keys.
37/// Treat it as part of the implementation's public contract: once
38/// shipped, do not rename across releases.
39///
40/// # Working space
41///
42/// The strip handed to [`StripMapper::map_strip`] is **linear-light** RGB
43/// in the primaries declared by
44/// [`working_primaries_for`](Self::working_primaries_for) (BT.2020 by
45/// default — the canonical HDR working space). Mappers that operate in a
46/// different gamut (a few Filmic variants prefer DCI-P3) override
47/// `working_primaries_for`; the pipeline inserts an extra gamut matrix
48/// on each side of the strip to honor that.
49pub trait ToneMapper: Send + Sync + UnwindSafe + RefUnwindSafe + Debug {
50 /// What pipeline-gathered context does this mapper need before it
51 /// can produce a [`PreparedMapper`]?
52 ///
53 /// Examples:
54 ///
55 /// - A pointwise curve with peaks pre-baked at construction returns
56 /// [`Requirements::NONE`] — no analysis needed.
57 /// - A pointwise curve that wants the pipeline to manage peaks
58 /// returns [`Requirements::SOURCE_PEAK_ONLY`].
59 /// - A local operator (Mantiuk, Fattal, bilateral) returns
60 /// `Requirements { full_image: true, ..Requirements::NONE }` —
61 /// currently rejected by the builder (reserved for a future
62 /// release; see [`PreparedMapper::Streaming`]).
63 fn requirements(&self) -> Requirements;
64
65 /// Build a per-image strip executor from the gathered context.
66 ///
67 /// Called **once** by the pipeline after the analysis pass.
68 /// Implementations should precompute curve coefficients / LUTs /
69 /// adaptation fields here, then return a [`PreparedMapper`] that the
70 /// pipeline applies strip-by-strip during row dispatch.
71 ///
72 /// `ctx` carries every field the mapper declared in
73 /// [`requirements`](Self::requirements), plus the always-populated
74 /// `source_peak_nits` / `target_peak_nits` / `working_primaries`.
75 ///
76 /// `pulse` carries optional cooperative cancellation and progress reporting
77 /// from [`how_far::Pulse`]. Callers pass `None` when cancellation and
78 /// progress reporting are not needed, or `Some(pulse)` (e.g.
79 /// `Some(&StopOnly::borrowed(stop))` for cancellation alone).
80 /// Implementations doing non-trivial preparation work (such as building 3D
81 /// LUTs or running a local spatial pass) should call `pulse.check()` before
82 /// and during that work and map [`StopReason`](how_far::StopReason) into
83 /// [`ConvertError::Cancelled`](crate::ConvertError::Cancelled). Per
84 /// `how-far`'s contract, implementations borrow `pulse` and never finish
85 /// it.
86 fn prepare(
87 &self,
88 ctx: &ToneMapContext,
89 pulse: Option<&dyn Pulse>,
90 ) -> Result<PreparedMapper, whereat::At<crate::ConvertError>>;
91
92 /// Short kebab-case identifier for diagnostics, trace logs, and
93 /// estimate / oracle cache keys.
94 ///
95 /// Examples: `"bt2446a"`, `"filmic-spline"`, `"aces-rrt"`,
96 /// `"itu2408"`, `"adaptive"`. Must be stable across releases of the
97 /// implementing crate — treat changing it as a breaking change.
98 fn name(&self) -> &'static str;
99
100 /// The working color primaries this mapper expects on its input
101 /// strip, given a target primaries hint.
102 ///
103 /// Default: [`Primaries::Bt2020`] — the canonical HDR working space.
104 fn working_primaries_for(&self, _target: Primaries) -> Primaries {
105 Primaries::Bt2020
106 }
107
108 /// Pre-baked `(source_peak_nits, target_peak_nits)` when this mapper ignores
109 /// pipeline-supplied peaks (e.g., `Bt2446A::with_peaks(Nits::new_positive_or_panic(4000.0), Nits::new_positive_or_panic(100.0))`).
110 ///
111 /// When `Some((src_peak, dst_peak))`, the pipeline normalizes input/output
112 /// strips to those exact peaks and skips redundant peak scanning.
113 fn baked_peaks(&self) -> Option<(f32, f32)> {
114 None
115 }
116}
117
118/// Per-image strip executor produced by [`ToneMapper::prepare`].
119///
120/// `Streaming` is the dominant case: a precomputed curve / LUT that the
121/// pipeline calls strip-by-strip via
122/// [`StripMapper::map_strip`].
123///
124/// `Buffered` is reserved for local operators that need to write their
125/// entire output during `prepare()` (e.g., Mantiuk gradient processing,
126/// Fattal, bilateral). The pipeline would read the buffer strip-by-strip
127/// during the apply pass. **Reserved for a future release; the current
128/// pipeline asserts `!requirements.full_image` at builder time** — the
129/// variant exists in the enum under `#[non_exhaustive]` so callers can
130/// exhaustively match without breaking when the variant lands.
131#[non_exhaustive]
132#[derive(Debug)]
133pub enum PreparedMapper {
134 /// Strip-by-strip executor. The pipeline calls
135 /// [`StripMapper::map_strip`] per strip with
136 /// image-specific coefficients already baked into the boxed
137 /// implementation.
138 Streaming(Box<dyn StripMapper>),
139 // Buffered(Box<[f32]>), // reserved — see enum-level docs
140}
141
142/// Compiled-for-this-image strip executor.
143///
144/// Produced by [`ToneMapper::prepare`] with image-specific coefficients
145/// (peak-aware curve coeffs, adaptation field, LUT rebuild) already baked
146/// in. The pipeline calls [`map_strip`](Self::map_strip) for each strip
147/// in the convert plan.
148///
149/// # Invariants
150///
151/// - **`Send + Sync + UnwindSafe + RefUnwindSafe + Debug`** — same
152/// rationale as on [`ToneMapper`]: the strip mapper rides inside a
153/// `OnceCell<Arc<dyn StripMapper>>` cached on the plan, which must
154/// carry its auto-traits through.
155/// - **No allocation, no panic on well-formed inputs.** Hot path —
156/// implementations should avoid heap allocation in
157/// [`map_strip`](Self::map_strip) and must not panic when the input
158/// and output slices satisfy the documented precondition.
159pub trait StripMapper: Send + Sync + UnwindSafe + RefUnwindSafe + Debug {
160 /// Apply tone mapping to an interleaved RGB strip in linear-light
161 /// working space.
162 ///
163 /// **Precondition.** Both slices are interleaved RGB triplets, i.e.
164 /// `input.len() % 3 == 0` and `input.len() == output.len()`. The
165 /// strip is interpreted in the primaries the parent
166 /// [`ToneMapper`] reports from
167 /// [`working_primaries_for`](ToneMapper::working_primaries_for)
168 /// (default BT.2020).
169 ///
170 /// **In-place permitted.** Implementations MAY support
171 /// `input.as_ptr() == output.as_ptr()` (the same slice passed twice
172 /// reinterpreted as immutable + mutable views by the caller), but
173 /// MUST behave correctly either way.
174 fn map_strip(&self, input: &[f32], output: &mut [f32]);
175}
176
177/// Pipeline analysis requirements declared by a [`ToneMapper`].
178///
179/// The pipeline reads this **before** building the execution plan and
180/// inserts analysis steps for whichever fields are `true`:
181///
182/// - [`source_peak_nits`](Self::source_peak_nits) — pipeline resolves via
183/// [`PeakSource`](zenpixels::PeakSource) (including streaming measurement via
184/// [`measure_content_light_level`](crate::measure_content_light_level)) and forwards it into [`ToneMapContext`].
185/// - [`full_image`](Self::full_image) — pipeline buffers the entire
186/// source image before calling `prepare`. **Reserved for a future
187/// release.** Setting `true` returns
188/// [`FullImageMapperNotSupported`](crate::ConvertError::FullImageMapperNotSupported)
189/// from the builder.
190#[non_exhaustive]
191#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
192pub struct Requirements {
193 /// The mapper reads [`ToneMapContext::source_peak_nits`], resolved from
194 /// [`PeakSource`](zenpixels::PeakSource) or `RowPlan::build`'s `hdr_peak`.
195 pub source_peak_nits: bool,
196 /// The pipeline must buffer the entire source image before calling
197 /// `prepare`. **Reserved for a future release.** Setting `true` returns
198 /// [`FullImageMapperNotSupported`](crate::ConvertError::FullImageMapperNotSupported)
199 /// when configured via
200 /// [`ConvertPolicy::with_tone_mapper`](crate::ConvertPolicy::with_tone_mapper).
201 pub full_image: bool,
202}
203
204impl Requirements {
205 /// No analysis required. The mapper is fully self-contained (peaks
206 /// pre-baked at construction, no image stats needed).
207 pub const NONE: Self = Self {
208 source_peak_nits: false,
209 full_image: false,
210 };
211
212 /// Only source peak is needed — the common case for any pointwise
213 /// tone curve that wants the pipeline to measure or supply the
214 /// peak (e.g., `Bt2446A::pipeline_managed`).
215 pub const SOURCE_PEAK_ONLY: Self = Self {
216 source_peak_nits: true,
217 full_image: false,
218 };
219}
220
221/// Gathered analysis context handed to [`ToneMapper::prepare`].
222///
223/// Fields are populated by the pipeline based on [`Requirements`] flags.
224/// Optional fields are `Some` iff the corresponding flag was `true`.
225/// Required fields ([`source_peak_nits`](Self::source_peak_nits),
226/// [`target_peak_nits`](Self::target_peak_nits),
227/// [`working_primaries`](Self::working_primaries)) are always populated.
228///
229/// Constructed by the pipeline; downstream code generally only reads
230/// this. The struct is `#[non_exhaustive]` so additional optional stats
231/// can be added in patch releases.
232#[non_exhaustive]
233#[derive(Debug)]
234pub struct ToneMapContext {
235 /// Resolved source peak luminance in cd/m², supplied via `RowPlan::build`
236 /// or [`PeakSource`](zenpixels::PeakSource) (`Fixed`, `Declared`, or `Measured`).
237 pub source_peak_nits: f32,
238 /// Target peak luminance in cd/m².
239 pub target_peak_nits: f32,
240 /// Working primaries the strip will be in. Default [`Primaries::Bt2020`].
241 pub working_primaries: Primaries,
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247 use alloc::sync::Arc;
248
249 /// Object-safety pin for [`ToneMapper`]. If the trait stops being
250 /// dyn-compatible — e.g. someone adds a generic method or a
251 /// `Self`-by-value return — this fails to compile, which is exactly
252 /// the breakage we want to catch at the trait-edit site.
253 #[allow(dead_code)]
254 fn _assert_obj_safe_tone_mapper(_: &dyn ToneMapper) {}
255
256 /// Object-safety pin for [`StripMapper`]. Same justification as
257 /// `_assert_obj_safe_tone_mapper`.
258 #[allow(dead_code)]
259 fn _assert_obj_safe_strip_mapper(_: &dyn StripMapper) {}
260
261 #[test]
262 fn requirements_none_constant_is_all_false() {
263 let r = Requirements::NONE;
264 assert!(!r.source_peak_nits);
265 assert!(!r.full_image);
266 assert_eq!(r, Requirements::default());
267 }
268
269 #[test]
270 fn requirements_source_peak_only_constant() {
271 let r = Requirements::SOURCE_PEAK_ONLY;
272 assert!(r.source_peak_nits);
273 assert!(!r.full_image);
274 }
275
276 #[test]
277 fn requirements_clone_and_debug_round_trip() {
278 let r = Requirements::SOURCE_PEAK_ONLY;
279 let r2 = r;
280 assert_eq!(r, r2);
281 let s = alloc::format!("{r:?}");
282 assert!(s.contains("Requirements"), "Debug shape: {s}");
283 }
284
285 /// Mock that records what context fields it observed at
286 /// `prepare()` time, using atomic storage so the `&self` method
287 /// can mutate state without interior unsafe (the crate is
288 /// `#![forbid(unsafe_code)]`).
289 #[derive(Debug, Default)]
290 struct MockMapper {
291 observed_source_peak_bits: core::sync::atomic::AtomicU32,
292 observed_target_peak_bits: core::sync::atomic::AtomicU32,
293 }
294
295 impl ToneMapper for MockMapper {
296 fn requirements(&self) -> Requirements {
297 Requirements {
298 source_peak_nits: true,
299 ..Requirements::NONE
300 }
301 }
302 fn prepare(
303 &self,
304 ctx: &ToneMapContext,
305 pulse: Option<&dyn Pulse>,
306 ) -> Result<PreparedMapper, whereat::At<crate::ConvertError>> {
307 use core::sync::atomic::Ordering;
308 crate::pulse::check_pulse(pulse)?;
309 self.observed_source_peak_bits
310 .store(ctx.source_peak_nits.to_bits(), Ordering::Relaxed);
311 self.observed_target_peak_bits
312 .store(ctx.target_peak_nits.to_bits(), Ordering::Relaxed);
313 Ok(PreparedMapper::Streaming(Box::new(IdentityStripMapper)))
314 }
315 fn name(&self) -> &'static str {
316 "mock"
317 }
318 }
319
320 #[derive(Debug)]
321 struct IdentityStripMapper;
322 impl StripMapper for IdentityStripMapper {
323 fn map_strip(&self, input: &[f32], output: &mut [f32]) {
324 output.copy_from_slice(input);
325 }
326 }
327
328 #[test]
329 fn mock_mapper_receives_populated_context() {
330 use core::sync::atomic::Ordering;
331 let mapper = MockMapper {
332 ..MockMapper::default()
333 };
334 // Drive `prepare` directly to verify the field plumbing: the
335 // pipeline integration test exercises the end-to-end flow.
336 let ctx = ToneMapContext {
337 source_peak_nits: 1000.0,
338 target_peak_nits: 100.0,
339 working_primaries: Primaries::Bt2020,
340 };
341 let _prepared = mapper.prepare(&ctx, None).unwrap();
342 assert_eq!(
343 f32::from_bits(mapper.observed_source_peak_bits.load(Ordering::Relaxed)),
344 1000.0
345 );
346 assert_eq!(
347 f32::from_bits(mapper.observed_target_peak_bits.load(Ordering::Relaxed)),
348 100.0
349 );
350 }
351
352 #[test]
353 fn mock_mapper_observes_pulse_cancellation() {
354 struct CancelledStop;
355 impl how_far::Stop for CancelledStop {
356 fn check(&self) -> Result<(), how_far::StopReason> {
357 Err(how_far::StopReason::Cancelled)
358 }
359 }
360 let mapper = MockMapper::default();
361 let ctx = ToneMapContext {
362 source_peak_nits: 1000.0,
363 target_peak_nits: 100.0,
364 working_primaries: Primaries::Bt2020,
365 };
366 let pulse = how_far::StopOnly::borrowed(&CancelledStop);
367 let err = mapper.prepare(&ctx, Some(&pulse)).unwrap_err();
368 assert_eq!(
369 *err.error(),
370 crate::ConvertError::Cancelled(how_far::StopReason::Cancelled)
371 );
372 assert_eq!(
373 how_far::AsStopReason::as_stop_reason(err.error()),
374 Some(how_far::StopReason::Cancelled)
375 );
376 }
377
378 #[test]
379 fn dyn_dispatch_round_trip() {
380 let mapper: Arc<dyn ToneMapper> = Arc::new(MockMapper::default());
381 assert_eq!(mapper.name(), "mock");
382 let r = mapper.requirements();
383 assert!(r.source_peak_nits);
384 assert!(!r.full_image);
385 }
386}