zenpixels_convert/output.rs
1//! Atomic output preparation for encoders.
2//!
3//! [`finalize_for_output`] converts pixel data and generates matching metadata
4//! in a single atomic operation, preventing the most common color management
5//! bug: pixel values that don't match the embedded color metadata.
6//!
7//! # Why atomicity matters
8//!
9//! The most common color management bug looks like this:
10//!
11//! ```rust,ignore
12//! // BUG: pixels and metadata can diverge
13//! let pixels = convert_to_p3(&buffer);
14//! let metadata = OutputMetadata { icc: Some(srgb_icc), .. };
15//! // ^^^ pixels are Display P3 but metadata says sRGB — wrong!
16//! ```
17//!
18//! [`finalize_for_output`] prevents this by producing the pixels and metadata
19//! together. The [`EncodeReady`] struct bundles both, and the only way to
20//! create one is through this function. If the conversion fails, neither
21//! pixels nor metadata are produced.
22//!
23//! # Usage
24//!
25//! ```rust,ignore
26//! use zenpixels_convert::{
27//! finalize_for_output, OutputProfile, PixelFormat,
28//! };
29//!
30//! let ready = finalize_for_output(
31//! &buffer, // source pixel data
32//! &color_origin, // how the source described its color
33//! OutputProfile::SameAsOrigin, // re-embed original metadata
34//! PixelFormat::Rgb8, // target byte layout
35//! &cms, // CMS impl (for ICC transforms)
36//! )?;
37//!
38//! // Write pixels — these match the metadata
39//! encoder.write_pixels(ready.pixels())?;
40//!
41//! // Embed color metadata — guaranteed to match the pixels
42//! if let Some(icc) = &ready.metadata().icc {
43//! encoder.write_icc_chunk(icc)?;
44//! }
45//! if let Some(cicp) = &ready.metadata().cicp {
46//! encoder.write_cicp(cicp)?;
47//! }
48//! if let Some(hdr) = &ready.metadata().hdr {
49//! encoder.write_hdr_metadata(hdr)?;
50//! }
51//! ```
52//!
53//! # Output profiles
54//!
55//! [`OutputProfile`] controls what color space the output should be in:
56//!
57//! - **`SameAsOrigin`**: Re-embed the original ICC/CICP from the source file.
58//! Pixels are converted only if the target pixel format differs from the
59//! source. Used for transcoding without color changes. If the source had
60//! an ICC profile, it is passed through; if CICP, the CICP codes are
61//! preserved.
62//!
63//! - **`Named(cicp)`**: Convert to a well-known CICP profile (sRGB, Display P3,
64//! BT.2020, PQ, HLG). Uses hardcoded 3×3 gamut matrices and transfer
65//! function conversion via `RowConverter` — no CMS needed. Fast and
66//! deterministic.
67//!
68//! - **`Icc(bytes)`**: Convert to a specific ICC profile. Requires a
69//! [`ColorManagement`] implementation to build the source→destination
70//! transform. Use this for print workflows, custom profiles, or any
71//! profile that isn't a standard CICP combination.
72//!
73//! # CMS requirement
74//!
75//! The `cms` parameter is only used when:
76//! - `OutputProfile::Icc` is selected, or
77//! - `OutputProfile::SameAsOrigin` and the source has an ICC profile.
78//!
79//! For `OutputProfile::Named`, the CMS is unused — gamut conversion uses
80//! hardcoded matrices. Codecs that don't need ICC support can pass a
81//! no-op CMS implementation.
82
83use alloc::sync::Arc;
84
85use crate::cms::ColorManagement;
86use crate::error::ConvertError;
87use crate::hdr::HdrMetadata;
88use crate::{
89 Cicp, ColorOrigin, ColorPrimaries, PixelBuffer, PixelDescriptor, PixelFormat, PixelSlice,
90 TransferFunction,
91};
92use whereat::{At, ResultAtExt};
93
94/// Target output color profile.
95#[derive(Clone, Debug)]
96#[non_exhaustive]
97pub enum OutputProfile {
98 /// Re-encode with the original ICC/CICP from the source file.
99 SameAsOrigin,
100 /// Use a well-known CICP-described profile.
101 Named(Cicp),
102 /// Use specific ICC profile bytes.
103 Icc(Arc<[u8]>),
104}
105
106/// Metadata that the encoder should embed alongside the pixel data.
107///
108/// Generated atomically by [`finalize_for_output`] to guarantee that
109/// the metadata matches the pixel values.
110#[derive(Clone, Debug)]
111#[non_exhaustive]
112pub struct OutputMetadata {
113 /// ICC profile bytes to embed, if any.
114 pub icc: Option<Arc<[u8]>>,
115 /// CICP code points to embed, if any.
116 pub cicp: Option<Cicp>,
117 /// HDR metadata to embed (content light level, mastering display), if any.
118 pub hdr: Option<HdrMetadata>,
119}
120
121/// Pixel data bundled with matching metadata, ready for encoding.
122///
123/// The only way to create an `EncodeReady` is through [`finalize_for_output`],
124/// which guarantees that the pixels and metadata are consistent.
125///
126/// Use [`into_parts()`](Self::into_parts) to destructure if needed, but
127/// the default path keeps them coupled.
128#[non_exhaustive]
129pub struct EncodeReady {
130 pixels: PixelBuffer,
131 metadata: OutputMetadata,
132}
133
134impl EncodeReady {
135 /// Borrow the pixel data.
136 pub fn pixels(&self) -> PixelSlice<'_> {
137 self.pixels.as_slice()
138 }
139
140 /// Borrow the output metadata.
141 pub fn metadata(&self) -> &OutputMetadata {
142 &self.metadata
143 }
144
145 /// Consume and split into pixel buffer and metadata.
146 pub fn into_parts(self) -> (PixelBuffer, OutputMetadata) {
147 (self.pixels, self.metadata)
148 }
149}
150
151/// Atomically convert pixel data and generate matching encoder metadata.
152///
153/// This function does three things as a single operation:
154///
155/// 1. Determines the current pixel color state from `PixelDescriptor` +
156/// optional ICC profile on `ColorContext`.
157/// 2. Converts pixels to the target profile's space. For named profiles,
158/// uses hardcoded matrices. For custom ICC profiles, uses the CMS.
159/// 3. Bundles the converted pixels with matching metadata ([`EncodeReady`]).
160///
161/// # Arguments
162///
163/// - `buffer` — Source pixel data with its current descriptor.
164/// - `origin` — How the source file described its color (for `SameAsOrigin`).
165/// - `target` — Desired output color profile.
166/// - `pixel_format` — Target pixel format for the output.
167/// - `cms` — Color management system for ICC profile transforms.
168///
169/// # Errors
170///
171/// Returns [`ConvertError`] if:
172/// - The target format requires a conversion that isn't supported.
173/// - The CMS fails to build a transform for ICC profiles.
174/// - Buffer allocation fails.
175#[track_caller]
176pub fn finalize_for_output<C: ColorManagement>(
177 buffer: &PixelBuffer,
178 origin: &ColorOrigin,
179 target: OutputProfile,
180 pixel_format: PixelFormat,
181 cms: &C,
182) -> Result<EncodeReady, At<ConvertError>> {
183 let source_desc = buffer.descriptor();
184 let target_desc = pixel_format.descriptor();
185
186 // Determine output metadata based on target profile.
187 let (metadata, needs_cms_transform) = match &target {
188 OutputProfile::SameAsOrigin => {
189 let metadata = OutputMetadata {
190 icc: origin.icc.clone(),
191 cicp: origin.cicp,
192 hdr: None,
193 };
194 // If origin has ICC, we may need a CMS transform.
195 (metadata, origin.icc.is_some())
196 }
197 OutputProfile::Named(cicp) => {
198 let metadata = OutputMetadata {
199 icc: None,
200 cicp: Some(*cicp),
201 hdr: None,
202 };
203 (metadata, false)
204 }
205 OutputProfile::Icc(icc) => {
206 let metadata = OutputMetadata {
207 icc: Some(icc.clone()),
208 cicp: None,
209 hdr: None,
210 };
211 (metadata, true)
212 }
213 };
214
215 // If source has an ICC profile and we need CMS, use it.
216 if needs_cms_transform
217 && let Some(src_icc) = buffer.color_context().and_then(|c| c.icc.as_ref())
218 && let Some(dst_icc) = &metadata.icc
219 {
220 let transform = cms
221 .build_transform_for_format(src_icc, dst_icc, source_desc.format, pixel_format)
222 .map_err(|e| whereat::at!(ConvertError::CmsError(alloc::format!("{e:?}"))))?;
223
224 let src_slice = buffer.as_slice();
225 let mut out = PixelBuffer::try_new(buffer.width(), buffer.height(), target_desc)
226 .map_err(|_| whereat::at!(ConvertError::AllocationFailed))?;
227
228 {
229 let mut dst_slice = out.as_slice_mut();
230 for y in 0..buffer.height() {
231 let src_row = src_slice.row(y);
232 let dst_row = dst_slice.row_mut(y);
233 transform.transform_row(src_row, dst_row, buffer.width());
234 }
235 }
236
237 return Ok(EncodeReady {
238 pixels: out,
239 metadata,
240 });
241 }
242
243 // Named profile conversion: use hardcoded matrices via RowConverter.
244 let target_desc_full = target_desc
245 .with_transfer(resolve_transfer(&target, &source_desc))
246 .with_primaries(resolve_primaries(&target, &source_desc));
247
248 if source_desc.layout_compatible(target_desc_full)
249 && descriptors_match(&source_desc, &target_desc_full)
250 {
251 // No conversion needed — copy the buffer.
252 let src_slice = buffer.as_slice();
253 let bytes = src_slice.contiguous_bytes();
254 let out = PixelBuffer::from_vec(
255 bytes.into_owned(),
256 buffer.width(),
257 buffer.height(),
258 target_desc_full,
259 )
260 .map_err(|_| whereat::at!(ConvertError::AllocationFailed))?;
261 return Ok(EncodeReady {
262 pixels: out,
263 metadata,
264 });
265 }
266
267 // Use RowConverter for format conversion.
268 let mut converter = crate::RowConverter::new(source_desc, target_desc_full).at()?;
269 let src_slice = buffer.as_slice();
270 let mut out = PixelBuffer::try_new(buffer.width(), buffer.height(), target_desc_full)
271 .map_err(|_| whereat::at!(ConvertError::AllocationFailed))?;
272
273 {
274 let mut dst_slice = out.as_slice_mut();
275 for y in 0..buffer.height() {
276 let src_row = src_slice.row(y);
277 let dst_row = dst_slice.row_mut(y);
278 converter.convert_row(src_row, dst_row, buffer.width());
279 }
280 }
281
282 Ok(EncodeReady {
283 pixels: out,
284 metadata,
285 })
286}
287
288/// Resolve the target transfer function.
289fn resolve_transfer(target: &OutputProfile, source: &PixelDescriptor) -> TransferFunction {
290 match target {
291 OutputProfile::SameAsOrigin => source.transfer(),
292 OutputProfile::Named(cicp) => TransferFunction::from_cicp(cicp.transfer_characteristics)
293 .unwrap_or(TransferFunction::Unknown),
294 OutputProfile::Icc(_) => TransferFunction::Unknown,
295 }
296}
297
298/// Resolve the target color primaries.
299fn resolve_primaries(target: &OutputProfile, source: &PixelDescriptor) -> ColorPrimaries {
300 match target {
301 OutputProfile::SameAsOrigin => source.primaries,
302 OutputProfile::Named(cicp) => {
303 ColorPrimaries::from_cicp(cicp.color_primaries).unwrap_or(ColorPrimaries::Unknown)
304 }
305 OutputProfile::Icc(_) => ColorPrimaries::Unknown,
306 }
307}
308
309/// Check if two descriptors match in all conversion-relevant fields.
310fn descriptors_match(a: &PixelDescriptor, b: &PixelDescriptor) -> bool {
311 a.format == b.format
312 && a.transfer == b.transfer
313 && a.primaries == b.primaries
314 && a.signal_range == b.signal_range
315}