Skip to main content

gamut_core/
convert.rs

1//! Format-agnostic conversion between interleaved pixel layouts, with every lossy decision made
2//! explicit by the caller.
3//!
4//! Decoders present an image in whatever layout the file natively carries. A caller usually wants
5//! one specific layout instead, and bridging the two splits cleanly in half:
6//!
7//! - **Lossless widening** — replicating grey into RGB, adding an opaque alpha channel, widening
8//!   8-bit samples to 16 — throws nothing away and needs no permission.
9//! - **Lossy narrowing** — dropping an alpha channel, narrowing 16-bit samples to 8, reducing RGB
10//!   to a single luma sample — destroys information, and *which* information it destroys is a
11//!   policy question with no universally right answer.
12//!
13//! This module defines both halves once, for every [`Pixel`] layout, so format crates never have to
14//! answer the policy questions themselves. A conversion is refused with [`Error::Unsupported`]
15//! unless the [`ConvertPolicy`] explicitly permits the loss it would incur — [`ConvertPolicy`]'s
16//! default is [`ConvertPolicy::lossless`], which permits none of it.
17//!
18//! # Two entry points, one engine
19//!
20//! [`convert`] is the typed door: `ImageRef<'_, P>` in, [`ImageBuf<Q>`] out. Callers use this.
21//!
22//! [`convert_from_raw`] is the decoder door. A decoder knows its target layout statically (it is
23//! implementing [`DecodeImage<Q>`](crate::DecodeImage)) but discovers the file's native layout at
24//! runtime, so its source is a [`RawImage`] carrying a [`PixelFormat`] tag rather than a brand.
25//! [`convert_from_raw_into`] writes into caller-provided storage, backing
26//! [`DecodeImage::decode_image_into`](crate::DecodeImage::decode_image_into).
27//!
28//! # What is out of scope
29//!
30//! [`Indexed8`](crate::Indexed8) and [`Cmyk8`](crate::Cmyk8) convert only to themselves. Palette
31//! indices are meaningless without the palette table, which the single-buffer model cannot carry
32//! (see `gamut-core`'s deferred shared-palette primitive), and CMYK↔RGB is a colour-management
33//! transform requiring an ICC rendering intent — not a layout rearrangement. Both refuse with a
34//! message naming the missing machinery rather than silently applying a naive approximation.
35//!
36//! # Associated (premultiplied) alpha
37//!
38//! Every gamut buffer with an alpha channel carries **unassociated** alpha ([`ColorModel::Rgba`],
39//! [`ColorModel::GrayAlpha`]). A format or pipeline that wants associated alpha — an AVIF encoder
40//! declaring its colour premultiplied, a compositor — converts in place with
41//! [`premultiply_alpha`], and back with [`unpremultiply_alpha`]. These are explicit operations, not
42//! [`ConvertPolicy`] conversions: the layout does not change (an [`Rgba8`](crate::Rgba8) buffer
43//! stays an `Rgba8` buffer), only the meaning of its colour samples does, and premultiplying is
44//! lossy wherever alpha is below full scale. Both leave a fully opaque pixel unchanged, and both
45//! leave a layout without an alpha channel unchanged, since every one of its pixels is opaque.
46//!
47//! # Example
48//!
49//! ```
50//! use gamut_core::{
51//!     convert::{convert, AlphaPolicy, ConvertPolicy},
52//!     Dimensions, ImageRef, Rgb8, Rgba8,
53//! };
54//!
55//! let dims = Dimensions::new(2, 1).unwrap();
56//! // Two half-transparent red pixels.
57//! let rgba = [255u8, 0, 0, 128, 255, 0, 0, 128];
58//! let image = ImageRef::<Rgba8>::new(&rgba, dims).unwrap();
59//!
60//! // Refused by default: dropping alpha loses information.
61//! assert!(convert::<Rgba8, Rgb8>(image, ConvertPolicy::lossless()).is_err());
62//!
63//! // Permitted once the caller says how alpha should be handled.
64//! let policy = ConvertPolicy::lossless().with_alpha(AlphaPolicy::Drop);
65//! let rgb = convert::<Rgba8, Rgb8>(image, policy).unwrap();
66//! assert_eq!(rgb.as_samples(), &[255, 0, 0, 255, 0, 0]);
67//! ```
68
69use crate::luminance::{
70    BT601_LUMA_WEIGHTS, BT709_LUMA_WEIGHTS, BT2020_LUMA_WEIGHTS, LUMA_FIX, LUMA_ONE,
71};
72use crate::{
73    ColorModel, Dimensions, Error, ImageBuf, ImageRef, Pixel, PixelFormat, Result, Sample,
74};
75
76/// What to do when the source carries an alpha channel the target layout cannot hold.
77///
78/// Only consulted when alpha would actually be lost. Adding an opaque alpha channel to a target
79/// that has one is lossless and always permitted, whatever this is set to.
80///
81/// Discriminants are explicit and permanent — they are C ABI values; new variants append.
82#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
83#[non_exhaustive]
84#[repr(u32)]
85pub enum AlphaPolicy {
86    /// Refuse the conversion with [`Error::Unsupported`]. The default.
87    #[default]
88    Reject = 0,
89    /// Discard the alpha channel, keeping the unassociated colour samples untouched.
90    ///
91    /// The transparent parts of the image keep whatever colour was stored under them, which for an
92    /// unassociated-alpha buffer may be arbitrary. Cheap and exactly reversible for opaque images.
93    Drop = 1,
94    /// Composite the image over [`ConvertPolicy::background`] and keep the result.
95    ///
96    /// Treats the source as unassociated alpha (which is what [`ColorModel::Rgba`] and
97    /// [`ColorModel::GrayAlpha`] specify) and computes `src * a + background * (1 - a)`.
98    CompositeOver = 2,
99}
100
101/// What to do when the target's samples are narrower than the source's.
102///
103/// Covers any reduction in sample precision: 16-bit samples into an 8-bit layout, and reducing a
104/// grey or colour image to [`Bilevel`](crate::Bilevel). Widening is lossless and always permitted.
105///
106/// Discriminants are explicit and permanent — they are C ABI values; new variants append.
107#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
108#[non_exhaustive]
109#[repr(u32)]
110pub enum DepthPolicy {
111    /// Refuse the conversion with [`Error::Unsupported`]. The default.
112    #[default]
113    Reject = 0,
114    /// Rescale to the narrower range, rounding to nearest.
115    ///
116    /// Narrowing 16-bit to 8-bit maps the full range onto the full range (`65535 → 255`), the exact
117    /// inverse of the widening PNG specifies in §13.12 — not a truncating shift, which would make
118    /// white slightly grey. A reduction to bilevel compares luma against
119    /// [`ConvertPolicy::threshold`].
120    Rescale = 1,
121}
122
123/// Which luma coefficients to use when reducing colour to a single grey sample.
124///
125/// Only consulted when the source carries RGB and the target is a grey layout. The weights
126/// themselves live in [`crate::luminance`].
127///
128/// Discriminants are explicit and permanent — they are C ABI values; new variants append.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
130#[non_exhaustive]
131#[repr(u32)]
132pub enum LumaPolicy {
133    /// Refuse the conversion with [`Error::Unsupported`]. The default.
134    #[default]
135    Reject = 0,
136    /// BT.601 / SMPTE 170M weights — the JFIF convention.
137    Bt601 = 1,
138    /// BT.709 weights — the sRGB/HD convention, and the right default for gamut's buffers.
139    Bt709 = 2,
140    /// BT.2020 / BT.2100 weights — for samples carrying wide-gamut UHD primaries.
141    Bt2020 = 3,
142}
143
144impl LumaPolicy {
145    /// The fixed-point weight triple this policy selects, or `None` for [`LumaPolicy::Reject`].
146    fn weights(self) -> Option<[u32; 3]> {
147        match self {
148            LumaPolicy::Reject => None,
149            LumaPolicy::Bt601 => Some(BT601_LUMA_WEIGHTS),
150            LumaPolicy::Bt709 => Some(BT709_LUMA_WEIGHTS),
151            LumaPolicy::Bt2020 => Some(BT2020_LUMA_WEIGHTS),
152        }
153    }
154}
155
156/// The lossy decisions a conversion is permitted to make, plus the parameters those decisions need.
157///
158/// Plain `Copy` data whose fields are reached through accessors, so it stays mechanically portable
159/// to C. Build one by starting from [`ConvertPolicy::lossless`] or [`ConvertPolicy::permissive`]
160/// and overriding what you need; every `with_*` setter and every getter is `const`.
161///
162/// ```
163/// use gamut_core::convert::{AlphaPolicy, ConvertPolicy, LumaPolicy};
164///
165/// let policy = ConvertPolicy::lossless()
166///     .with_alpha(AlphaPolicy::CompositeOver)
167///     .with_background([u16::MAX; 3]) // composite over white
168///     .with_luma(LumaPolicy::Bt709);
169/// ```
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
171#[must_use]
172pub struct ConvertPolicy {
173    alpha: AlphaPolicy,
174    depth: DepthPolicy,
175    luma: LumaPolicy,
176    background: [u16; 3],
177    threshold: u16,
178}
179
180impl Default for ConvertPolicy {
181    fn default() -> Self {
182        Self::lossless()
183    }
184}
185
186impl ConvertPolicy {
187    /// The default midpoint for a reduction to bilevel: half of full scale.
188    const DEFAULT_THRESHOLD: u16 = 32_768;
189
190    /// Permits no loss at all: every narrowing conversion is refused.
191    ///
192    /// The default, and what every gamut decoder uses unless the caller says otherwise, so a typed
193    /// decode never quietly discards part of the file.
194    pub const fn lossless() -> Self {
195        Self {
196            alpha: AlphaPolicy::Reject,
197            depth: DepthPolicy::Reject,
198            luma: LumaPolicy::Reject,
199            background: [0; 3],
200            threshold: Self::DEFAULT_THRESHOLD,
201        }
202    }
203
204    /// Permits every loss this module can express, with conventional defaults.
205    ///
206    /// Alpha is dropped, samples rescale to the target width, and colour reduces to luma with
207    /// [`LumaPolicy::Bt709`]. Suited to an application that just wants pixels in a fixed layout —
208    /// `gamut-cli` uses this. Prefer naming the individual policies when the choice matters.
209    pub const fn permissive() -> Self {
210        Self {
211            alpha: AlphaPolicy::Drop,
212            depth: DepthPolicy::Rescale,
213            luma: LumaPolicy::Bt709,
214            background: [0; 3],
215            threshold: Self::DEFAULT_THRESHOLD,
216        }
217    }
218
219    /// Sets how an alpha channel the target cannot hold is handled.
220    pub const fn with_alpha(mut self, policy: AlphaPolicy) -> Self {
221        self.alpha = policy;
222        self
223    }
224
225    /// Sets how samples narrower than the source's are produced.
226    pub const fn with_depth(mut self, policy: DepthPolicy) -> Self {
227        self.depth = policy;
228        self
229    }
230
231    /// Sets which luma coefficients reduce colour to grey.
232    pub const fn with_luma(mut self, policy: LumaPolicy) -> Self {
233        self.luma = policy;
234        self
235    }
236
237    /// Sets the background colour [`AlphaPolicy::CompositeOver`] composites against.
238    ///
239    /// Full-range RGB regardless of the layouts involved, so one value reads the same for 8- and
240    /// 16-bit targets: `[0; 3]` is black (the default) and `[u16::MAX; 3]` is white.
241    pub const fn with_background(mut self, rgb: [u16; 3]) -> Self {
242        self.background = rgb;
243        self
244    }
245
246    /// Sets the full-range luma at or above which a bilevel target records white.
247    ///
248    /// Defaults to half of full scale.
249    pub const fn with_threshold(mut self, threshold: u16) -> Self {
250        self.threshold = threshold;
251        self
252    }
253
254    /// How an alpha channel the target cannot hold is handled.
255    #[must_use]
256    pub const fn alpha(self) -> AlphaPolicy {
257        self.alpha
258    }
259
260    /// How samples narrower than the source's are produced.
261    #[must_use]
262    pub const fn depth(self) -> DepthPolicy {
263        self.depth
264    }
265
266    /// Which luma coefficients reduce colour to grey.
267    ///
268    /// A decoder that must choose what to ask its backend for — rather than converting after the
269    /// fact — reads this to decide whether a colour-to-grey request is worth attempting at all.
270    #[must_use]
271    pub const fn luma(self) -> LumaPolicy {
272        self.luma
273    }
274
275    /// The full-range background colour [`AlphaPolicy::CompositeOver`] composites against.
276    #[must_use]
277    pub const fn background(self) -> [u16; 3] {
278        self.background
279    }
280
281    /// The full-range luma at or above which a bilevel target records white.
282    #[must_use]
283    pub const fn threshold(self) -> u16 {
284        self.threshold
285    }
286}
287
288/// A borrowed interleaved image whose layout is known only at runtime.
289///
290/// The counterpart of [`ImageRef`] for a decoder that has just produced native samples and does not
291/// yet have them in a branded buffer: the layout travels as a [`PixelFormat`] tag instead of a
292/// [`Pixel`] brand. Validated on construction exactly as [`ImageRef::new`] is, so the conversion
293/// engine can trust the length and the sample width.
294#[derive(Debug, Clone, Copy)]
295#[must_use]
296pub struct RawImage<'a, S: Sample> {
297    samples: &'a [S],
298    format: PixelFormat,
299    dims: Dimensions,
300}
301
302impl<'a, S: Sample> RawImage<'a, S> {
303    /// Describes `samples` as an image of `dims` in layout `format`.
304    ///
305    /// # Errors
306    ///
307    /// Returns [`Error::InvalidInput`] if `S` is not `format`'s sample width, if `dims` is
308    /// zero-sized or overflows `usize`, or if `samples.len()` is not
309    /// `width * height * format.channels()`.
310    pub fn new(samples: &'a [S], format: PixelFormat, dims: Dimensions) -> Result<Self> {
311        if format.bytes_per_sample() != core::mem::size_of::<S>() {
312            return Err(Error::invalid_input(
313                env!("CARGO_PKG_NAME"),
314                "convert: sample type does not match the pixel format's sample width",
315            ));
316        }
317        if dims.is_empty() {
318            return Err(Error::invalid_input(
319                env!("CARGO_PKG_NAME"),
320                "convert: zero-sized image",
321            ));
322        }
323        let want = dims.sample_count(format.channels()).ok_or_else(|| {
324            Error::invalid_input(
325                env!("CARGO_PKG_NAME"),
326                "convert: image dimensions overflow usize",
327            )
328        })?;
329        if samples.len() != want {
330            return Err(Error::invalid_input(
331                env!("CARGO_PKG_NAME"),
332                "convert: sample count does not match dimensions",
333            ));
334        }
335        Ok(Self {
336            samples,
337            format,
338            dims,
339        })
340    }
341
342    /// Builds a view whose invariants a [`Pixel`] brand has already established.
343    ///
344    /// Backs [`ImageRef::as_raw`]; re-running [`RawImage::new`]'s checks there could only fail on
345    /// a buffer that was already validated at construction.
346    pub(crate) fn from_branded(samples: &'a [S], format: PixelFormat, dims: Dimensions) -> Self {
347        Self {
348            samples,
349            format,
350            dims,
351        }
352    }
353
354    /// The raw interleaved samples, row-major.
355    #[must_use]
356    pub fn as_samples(self) -> &'a [S] {
357        self.samples
358    }
359
360    /// The runtime layout tag.
361    #[must_use]
362    pub fn format(self) -> PixelFormat {
363        self.format
364    }
365
366    /// The image dimensions.
367    #[must_use]
368    pub fn dimensions(self) -> Dimensions {
369        self.dims
370    }
371}
372
373/// Colour (non-alpha) channels a model carries, or `None` when the model has no colour-model-free
374/// interpretation this module can convert through.
375fn colour_channels(model: ColorModel) -> Option<usize> {
376    match model {
377        // Bilevel is one channel of luma with only two legal states; the read/write helpers below
378        // handle the state mapping, so it travels the same path as Gray.
379        ColorModel::Gray | ColorModel::GrayAlpha | ColorModel::Bilevel => Some(1),
380        ColorModel::Rgb | ColorModel::Rgba => Some(3),
381        // Palette indices need the table; ink separations need a colour-management transform.
382        ColorModel::Cmyk | ColorModel::Indexed => None,
383    }
384}
385
386/// Whether a model carries an alpha channel after its colour channels.
387fn has_alpha(model: ColorModel) -> bool {
388    match model {
389        ColorModel::GrayAlpha | ColorModel::Rgba => true,
390        ColorModel::Gray
391        | ColorModel::Bilevel
392        | ColorModel::Rgb
393        | ColorModel::Cmyk
394        | ColorModel::Indexed => false,
395    }
396}
397
398/// The refusal for a layout this module deliberately does not convert.
399fn opaque_model(model: ColorModel) -> Error {
400    let message = match model {
401        ColorModel::Indexed => {
402            "convert: palette indices cannot be converted without the palette table"
403        }
404        _ => "convert: CMYK conversion needs a colour-management transform, not a layout change",
405    };
406    Error::unsupported(env!("CARGO_PKG_NAME"), message)
407}
408
409/// A validated, per-image conversion recipe: the policy questions are all answered here, once,
410/// before a single pixel is touched, so a refused conversion never writes a partial result.
411#[derive(Debug, Clone, Copy)]
412struct Plan {
413    src_channels: usize,
414    dst_channels: usize,
415    src_colour: usize,
416    dst_colour: usize,
417    src_alpha: bool,
418    dst_alpha: bool,
419    src_bilevel: bool,
420    dst_bilevel: bool,
421    /// Source and target layouts are the same: copy the samples through untouched. The only path
422    /// open to layouts with no colour-model-free interpretation ([`ColorModel::Cmyk`],
423    /// [`ColorModel::Indexed`]), for which a copy is the one conversion that is unambiguously
424    /// correct.
425    identity: bool,
426    /// Set only when alpha is genuinely lost; `Drop` and `CompositeOver` differ only then.
427    composite: bool,
428    weights: [u32; 3],
429    background: [u16; 3],
430    threshold: u16,
431}
432
433impl Plan {
434    /// A straight sample-for-sample copy between identical layouts.
435    fn identity(format: PixelFormat) -> Self {
436        Self {
437            src_channels: format.channels(),
438            dst_channels: format.channels(),
439            src_colour: 0,
440            dst_colour: 0,
441            src_alpha: false,
442            dst_alpha: false,
443            src_bilevel: false,
444            dst_bilevel: false,
445            identity: true,
446            composite: false,
447            weights: BT709_LUMA_WEIGHTS,
448            background: [0; 3],
449            threshold: 0,
450        }
451    }
452
453    /// Derives the recipe for `src` → `dst`, or the refusal explaining which policy is missing.
454    fn derive(src: PixelFormat, dst: PixelFormat, policy: ConvertPolicy) -> Result<Self> {
455        // Identical layouts short-circuit every policy question: nothing is lost, so nothing needs
456        // permission. This is what lets CMYK and palette buffers pass through unchanged.
457        if src == dst {
458            return Ok(Self::identity(src));
459        }
460
461        let (src_model, dst_model) = (src.color_model(), dst.color_model());
462        let src_colour = colour_channels(src_model).ok_or_else(|| opaque_model(src_model))?;
463        let dst_colour = colour_channels(dst_model).ok_or_else(|| opaque_model(dst_model))?;
464
465        let src_alpha = has_alpha(src_model);
466        let dst_alpha = has_alpha(dst_model);
467        let src_bilevel = src_model == ColorModel::Bilevel;
468        let dst_bilevel = dst_model == ColorModel::Bilevel;
469
470        // Losing alpha: the target has no slot for a channel the source actually carries.
471        let drops_alpha = src_alpha && !dst_alpha;
472        if drops_alpha && policy.alpha == AlphaPolicy::Reject {
473            return Err(Error::unsupported(
474                env!("CARGO_PKG_NAME"),
475                "convert: target layout cannot hold the source's alpha channel; set an AlphaPolicy",
476            ));
477        }
478
479        // Losing colour: three channels collapsing into one.
480        if src_colour == 3 && dst_colour == 1 && policy.luma == LumaPolicy::Reject {
481            return Err(Error::unsupported(
482                env!("CARGO_PKG_NAME"),
483                "convert: target layout cannot hold colour; set a LumaPolicy",
484            ));
485        }
486
487        // Losing precision: narrower samples, or a collapse to two states. A bilevel *source* is
488        // already two-state, so bilevel -> bilevel narrows nothing.
489        let narrows_samples = src.bytes_per_sample() > dst.bytes_per_sample();
490        let narrows_to_bilevel = dst_bilevel && !src_bilevel;
491        if (narrows_samples || narrows_to_bilevel) && policy.depth == DepthPolicy::Reject {
492            return Err(Error::unsupported(
493                env!("CARGO_PKG_NAME"),
494                "convert: target layout is narrower than the source; set a DepthPolicy",
495            ));
496        }
497
498        Ok(Self {
499            src_channels: src.channels(),
500            dst_channels: dst.channels(),
501            src_colour,
502            dst_colour,
503            src_alpha,
504            dst_alpha,
505            src_bilevel,
506            dst_bilevel,
507            identity: false,
508            composite: drops_alpha && policy.alpha == AlphaPolicy::CompositeOver,
509            // Unconditional for a grey target: the weights sum to LUMA_ONE, so applying them to an
510            // already-grey pixel reproduces it exactly and needs no special case. Reject cannot
511            // reach here for a colour source, so black weights would be unused; BT.709 keeps the
512            // grey-source path exact.
513            weights: policy.luma.weights().unwrap_or(BT709_LUMA_WEIGHTS),
514            background: policy.background,
515            threshold: policy.threshold,
516        })
517    }
518}
519
520/// Reads one source sample onto the canonical full-range scale.
521fn read<S: Sample>(sample: S, bilevel: bool) -> u16 {
522    if bilevel {
523        // ColorModel::Bilevel: 0 is black, any non-zero value is white. Accepts both the 0/1 form a
524        // 1-bit decoder produces and the 0/MAX form `write` emits.
525        if sample == S::default() { 0 } else { u16::MAX }
526    } else {
527        sample.to_full_range_u16()
528    }
529}
530
531/// Writes one canonical full-range value into a target sample.
532fn write<T: Sample>(value: u16, bilevel: bool, threshold: u16) -> T {
533    if bilevel {
534        if value >= threshold {
535            T::MAX_VALUE
536        } else {
537            T::default()
538        }
539    } else {
540        T::from_full_range_u16(value)
541    }
542}
543
544/// Composites one unassociated colour sample over `background`.
545fn composite(value: u16, alpha: u16, background: u16) -> u16 {
546    let inverse = u32::from(u16::MAX - alpha);
547    let blended = u64::from(value) * u64::from(alpha) + u64::from(background) * u64::from(inverse);
548    // Round to nearest so a fully opaque or fully transparent pixel is reproduced exactly.
549    ((blended + 32_767) / 65_535) as u16
550}
551
552/// Reduces a full-range RGB triple to one luma sample with the plan's weights.
553fn luma(rgb: [u16; 3], weights: [u32; 3]) -> u16 {
554    let sum: u64 = weights
555        .iter()
556        .zip(rgb)
557        .map(|(&weight, channel)| u64::from(weight) * u64::from(channel))
558        .sum();
559    ((sum + u64::from(LUMA_ONE / 2)) >> LUMA_FIX) as u16
560}
561
562/// Runs a derived plan over every pixel. Infallible: `derive` has already rejected the impossible
563/// and both slices are known to hold whole pixels of the right count.
564fn run<S: Sample, T: Sample>(src: &[S], dst: &mut [T], plan: &Plan) {
565    if plan.identity {
566        // Same layout, so same sample width: the widen/narrow pair round-trips exactly and is the
567        // only way to move between two distinct `Sample` types that happen to be the same width.
568        for (target, source) in dst.iter_mut().zip(src) {
569            *target = T::from_full_range_u16(source.to_full_range_u16());
570        }
571        return;
572    }
573    let pixels = src.chunks_exact(plan.src_channels);
574    let targets = dst.chunks_exact_mut(plan.dst_channels);
575    for (source, target) in pixels.zip(targets) {
576        let mut rgb = [0u16; 3];
577        if plan.src_colour == 1 {
578            let grey = read(source[0], plan.src_bilevel);
579            rgb = [grey; 3];
580        } else {
581            for (channel, sample) in rgb.iter_mut().zip(source) {
582                *channel = read(*sample, plan.src_bilevel);
583            }
584        }
585        // A source without alpha is fully opaque; that keeps the compositing arithmetic below
586        // uniform instead of branching on presence.
587        let alpha = if plan.src_alpha {
588            read(source[plan.src_colour], false)
589        } else {
590            u16::MAX
591        };
592
593        if plan.composite {
594            for (channel, background) in rgb.iter_mut().zip(plan.background) {
595                *channel = composite(*channel, alpha, background);
596            }
597        }
598
599        if plan.dst_colour == 1 {
600            target[0] = write(luma(rgb, plan.weights), plan.dst_bilevel, plan.threshold);
601        } else {
602            for (sample, channel) in target.iter_mut().zip(rgb) {
603                *sample = write(channel, plan.dst_bilevel, plan.threshold);
604            }
605        }
606        if plan.dst_alpha {
607            // Alpha itself is never bilevel-coded, and survives a drop only into a target that has
608            // a slot for it — so it passes through on the plain sample scale.
609            target[plan.dst_colour] = write(alpha, false, plan.threshold);
610        }
611    }
612}
613
614/// Converts a runtime-tagged raw image into the branded layout `Q`.
615///
616/// The entry point a decoder uses: it knows `Q` statically from the
617/// [`DecodeImage`](crate::DecodeImage) impl it is fulfilling, but learns the file's native layout
618/// only at runtime.
619///
620/// # Errors
621///
622/// Returns [`Error::Unsupported`] if the conversion would lose information `policy` does not
623/// permit, or if either layout is [`Indexed8`](crate::Indexed8) or [`Cmyk8`](crate::Cmyk8) and the
624/// two differ. Returns [`Error::InvalidInput`] if the dimensions overflow `usize`.
625pub fn convert_from_raw<S: Sample, Q: Pixel>(
626    src: RawImage<'_, S>,
627    policy: ConvertPolicy,
628) -> Result<ImageBuf<Q>> {
629    // `derive` runs first so an unsupported pair costs no allocation.
630    let plan = Plan::derive(src.format, Q::FORMAT, policy)?;
631    let mut out = ImageBuf::<Q>::zeroed(src.dims)?;
632    run(src.samples, out.as_mut_samples(), &plan);
633    Ok(out)
634}
635
636/// Converts a runtime-tagged raw image into caller-provided storage for layout `Q`.
637///
638/// Backs [`DecodeImage::decode_image_into`](crate::DecodeImage::decode_image_into), letting a
639/// decoder refill an existing buffer instead of allocating a new one. `dst` is left untouched
640/// unless the conversion succeeds.
641///
642/// # Errors
643///
644/// As [`convert_from_raw`], plus [`Error::InvalidInput`] if `dst` is not exactly
645/// `width * height * Q::CHANNELS` samples.
646pub fn convert_from_raw_into<S: Sample, Q: Pixel>(
647    src: RawImage<'_, S>,
648    policy: ConvertPolicy,
649    dst: &mut [Q::Sample],
650) -> Result<()> {
651    let plan = Plan::derive(src.format, Q::FORMAT, policy)?;
652    let want = src.dims.sample_count(Q::CHANNELS).ok_or_else(|| {
653        Error::invalid_input(
654            env!("CARGO_PKG_NAME"),
655            "convert: image dimensions overflow usize",
656        )
657    })?;
658    if dst.len() != want {
659        return Err(Error::invalid_input(
660            env!("CARGO_PKG_NAME"),
661            "convert: destination length does not match dimensions",
662        ));
663    }
664    run(src.samples, dst, &plan);
665    Ok(())
666}
667
668/// Converts a branded image from layout `P` to layout `Q`.
669///
670/// The typed door onto the same engine [`convert_from_raw`] drives; use it when both layouts are
671/// known at compile time.
672///
673/// # Errors
674///
675/// As [`convert_from_raw`].
676pub fn convert<P: Pixel, Q: Pixel>(
677    src: ImageRef<'_, P>,
678    policy: ConvertPolicy,
679) -> Result<ImageBuf<Q>> {
680    convert_from_raw(src.as_raw(), policy)
681}
682
683/// The largest code value a sample of type `S` holds: 255 for `u8`, 65535 for `u16`.
684fn code_max<S: Sample>() -> u64 {
685    (1 << (8 * core::mem::size_of::<S>())) - 1
686}
687
688/// A sample's own code value, read back off the full-range scale `S` widens onto.
689///
690/// Exact for both sample widths: `u8` widens by multiplying by 257 = 65535 / 255, and `u16` is the
691/// identity.
692fn to_code<S: Sample>(sample: S, max: u64) -> u64 {
693    u64::from(sample.to_full_range_u16()) * max / 65_535
694}
695
696/// The sample holding code value `code`, which must not exceed `max`. The exact inverse of
697/// [`to_code`].
698fn from_code<S: Sample>(code: u64, max: u64) -> S {
699    S::from_full_range_u16((code * 65_535 / max) as u16)
700}
701
702/// Associates one colour code value with its pixel's alpha: `round(colour * alpha / max)`.
703///
704/// `max` is odd for both sample widths, so `colour * alpha / max` is never exactly half-way between
705/// two integers and round-half-up is round-to-nearest without a tie to break.
706fn premultiply_code(colour: u64, alpha: u64, max: u64) -> u64 {
707    (colour * alpha + max / 2) / max
708}
709
710/// Dissociates one colour code value from its pixel's alpha: `round(colour * max / alpha)`,
711/// clamped to `max`.
712///
713/// A fully transparent pixel has no recoverable colour and yields 0. The clamp only acts on input
714/// that was never validly premultiplied — associated colour above its own alpha — which a reader
715/// still meets in the wild.
716fn unpremultiply_code(colour: u64, alpha: u64, max: u64) -> u64 {
717    if alpha == 0 {
718        return 0;
719    }
720    ((colour * max + alpha / 2) / alpha).min(max)
721}
722
723/// Rewrites every colour sample of `image` as `op(colour, alpha, max)`, leaving alpha untouched.
724///
725/// A layout without an alpha channel is opaque throughout, and both operations leave an opaque
726/// pixel unchanged, so such a layout is left alone rather than refused.
727fn apply_alpha<P: Pixel>(image: &mut ImageBuf<P>, op: fn(u64, u64, u64) -> u64) {
728    if !has_alpha(P::MODEL) {
729        return;
730    }
731    let max = code_max::<P::Sample>();
732    // Both alpha-carrying models store alpha after their colour channels.
733    let alpha_index = P::CHANNELS - 1;
734    for pixel in image.as_mut_samples().chunks_exact_mut(P::CHANNELS) {
735        let (colour, alpha) = pixel.split_at_mut(alpha_index);
736        let alpha = to_code(alpha[0], max);
737        for sample in colour {
738            *sample = from_code(op(to_code(*sample, max), alpha, max), max);
739        }
740    }
741}
742
743/// Converts `image` from unassociated to associated (premultiplied) alpha, in place.
744///
745/// Each colour sample becomes `round(colour * alpha / max)`, where `max` is the sample type's full
746/// scale (255 or 65535); alpha itself is unchanged. A fully opaque pixel is unchanged and a fully
747/// transparent one becomes transparent black.
748///
749/// **Lossy** wherever alpha is below full scale: a pixel of alpha `a` keeps only `a + 1` distinct
750/// colour levels, so [`unpremultiply_alpha`] recovers the original only to within
751/// `⌊(a + max) / 2a⌋` code values. To keep the unassociated image, premultiply a
752/// [`clone`](Clone::clone) of it.
753///
754/// A layout without an alpha channel is fully opaque, so it is left unchanged.
755///
756/// ```
757/// use gamut_core::{convert::premultiply_alpha, Dimensions, ImageBuf, Rgba8};
758///
759/// let dims = Dimensions::new(2, 1).unwrap();
760/// // Half-transparent white, and opaque orange.
761/// let mut image = ImageBuf::<Rgba8>::new(vec![255, 255, 255, 128, 255, 128, 0, 255], dims).unwrap();
762/// premultiply_alpha(&mut image);
763/// assert_eq!(image.as_samples(), &[128, 128, 128, 128, 255, 128, 0, 255]);
764/// ```
765pub fn premultiply_alpha<P: Pixel>(image: &mut ImageBuf<P>) {
766    apply_alpha(image, premultiply_code);
767}
768
769/// Converts `image` from associated (premultiplied) to unassociated alpha, in place.
770///
771/// Each colour sample becomes `round(colour * max / alpha)`, clamped to `max`, where `max` is the
772/// sample type's full scale (255 or 65535); alpha itself is unchanged. A fully opaque pixel is
773/// unchanged, and a fully transparent one — whose colour premultiplication erased — becomes
774/// transparent black.
775///
776/// The inverse of [`premultiply_alpha`] only up to the precision premultiplying discarded; see
777/// there for the bound. For well-formed associated input — every colour sample at most its pixel's
778/// alpha, as [`premultiply_alpha`] always produces — re-premultiplying the result reproduces the
779/// associated image exactly. Colour above alpha is malformed but still accepted: it is clamped to
780/// `max`, so re-premultiplying gives back the alpha rather than the original colour (8-bit colour
781/// 200 at alpha 100 unpremultiplies to 255 and re-premultiplies to 100).
782///
783/// A layout without an alpha channel is fully opaque, so it is left unchanged.
784///
785/// ```
786/// use gamut_core::{convert::unpremultiply_alpha, Dimensions, ImageBuf, Rgba8};
787///
788/// let dims = Dimensions::new(2, 1).unwrap();
789/// // Half-transparent white, premultiplied; and fully transparent.
790/// let mut image = ImageBuf::<Rgba8>::new(vec![128, 128, 128, 128, 0, 0, 0, 0], dims).unwrap();
791/// unpremultiply_alpha(&mut image);
792/// assert_eq!(image.as_samples(), &[255, 255, 255, 128, 0, 0, 0, 0]);
793/// ```
794pub fn unpremultiply_alpha<P: Pixel>(image: &mut ImageBuf<P>) {
795    apply_alpha(image, unpremultiply_code);
796}
797
798#[cfg(test)]
799mod tests {
800    use super::*;
801    use crate::{
802        Bilevel, Cmyk8, ErrorKind, Gray8, Gray16, GrayAlpha8, GrayAlpha16, Indexed8, Rgb8, Rgb16,
803        Rgba8, Rgba16,
804    };
805
806    fn dims(w: u32, h: u32) -> Dimensions {
807        Dimensions {
808            width: w,
809            height: h,
810        }
811    }
812
813    /// Builds a one-pixel raw image; the shortest way to exercise a specific layout pair.
814    fn raw<S: Sample>(samples: &[S], format: PixelFormat) -> RawImage<'_, S> {
815        RawImage::new(samples, format, dims(1, 1)).unwrap()
816    }
817
818    #[test]
819    fn lossless_widening_needs_no_policy() {
820        let strict = ConvertPolicy::lossless();
821
822        // Grey replicates into every colour channel, and gains opaque alpha.
823        let grey = raw(&[7u8], PixelFormat::Gray8);
824        let rgb = convert_from_raw::<_, Rgb8>(grey, strict).unwrap();
825        assert_eq!(rgb.as_samples(), &[7, 7, 7]);
826        let rgba = convert_from_raw::<_, Rgba8>(grey, strict).unwrap();
827        assert_eq!(rgba.as_samples(), &[7, 7, 7, 255]);
828
829        // 8 -> 16 widening replicates the byte (PNG 13.12), so 0xFF reaches full scale.
830        let white = raw(&[255u8, 128, 0], PixelFormat::Rgb8);
831        let wide = convert_from_raw::<_, Rgb16>(white, strict).unwrap();
832        assert_eq!(wide.as_samples(), &[0xFFFF, 0x8080, 0]);
833    }
834
835    #[test]
836    fn dropping_alpha_needs_an_alpha_policy() {
837        let src = raw(&[10u8, 20, 30, 128], PixelFormat::Rgba8);
838
839        let refused = convert_from_raw::<_, Rgb8>(src, ConvertPolicy::lossless()).unwrap_err();
840        assert_eq!(refused.kind(), ErrorKind::Unsupported);
841        assert_eq!(refused.origin(), Some("gamut-core"));
842
843        // Drop keeps the stored colour untouched.
844        let dropped = convert_from_raw::<_, Rgb8>(
845            src,
846            ConvertPolicy::lossless().with_alpha(AlphaPolicy::Drop),
847        )
848        .unwrap();
849        assert_eq!(dropped.as_samples(), &[10, 20, 30]);
850    }
851
852    #[test]
853    fn compositing_blends_against_the_background() {
854        // Half-transparent mid-grey over black and over white must land either side of the source.
855        let src = raw(&[128u8, 128, 128, 128], PixelFormat::Rgba8);
856        let over_black = ConvertPolicy::lossless()
857            .with_alpha(AlphaPolicy::CompositeOver)
858            .with_background([0; 3]);
859        let over_white = ConvertPolicy::lossless()
860            .with_alpha(AlphaPolicy::CompositeOver)
861            .with_background([u16::MAX; 3]);
862
863        let dark = convert_from_raw::<_, Rgb8>(src, over_black).unwrap();
864        let light = convert_from_raw::<_, Rgb8>(src, over_white).unwrap();
865        assert!(dark.as_samples()[0] < 128, "{:?}", dark.as_samples());
866        assert!(light.as_samples()[0] > 128, "{:?}", light.as_samples());
867
868        // The endpoints are exact: opaque reproduces the source, transparent reproduces the
869        // background. This is what distinguishes correct rounding from an off-by-one blend.
870        let opaque = raw(&[200u8, 100, 50, 255], PixelFormat::Rgba8);
871        assert_eq!(
872            convert_from_raw::<_, Rgb8>(opaque, over_white)
873                .unwrap()
874                .as_samples(),
875            &[200, 100, 50]
876        );
877        let clear = raw(&[200u8, 100, 50, 0], PixelFormat::Rgba8);
878        assert_eq!(
879            convert_from_raw::<_, Rgb8>(clear, over_white)
880                .unwrap()
881                .as_samples(),
882            &[255, 255, 255]
883        );
884    }
885
886    #[test]
887    fn compositing_rounds_to_nearest_at_full_precision() {
888        // An 8-bit target re-quantises the blend, which hides a one-unit error in the rounding
889        // addend. A 16-bit target does not: an opaque sample of 1 survives only if the addend is
890        // added, since (1*65535 - 32767) / 65535 truncates to 0.
891        let src = raw(&[1u16, 1, 1, u16::MAX], PixelFormat::Rgba16);
892        let policy = ConvertPolicy::lossless()
893            .with_alpha(AlphaPolicy::CompositeOver)
894            .with_background([0; 3]);
895        assert_eq!(
896            convert_from_raw::<_, Rgb16>(src, policy)
897                .unwrap()
898                .as_samples(),
899            &[1, 1, 1]
900        );
901    }
902
903    #[test]
904    fn reducing_colour_needs_a_luma_policy_and_honours_the_standard() {
905        let src = raw(&[255u8, 0, 0], PixelFormat::Rgb8);
906        assert_eq!(
907            convert_from_raw::<_, Gray8>(src, ConvertPolicy::lossless())
908                .unwrap_err()
909                .kind(),
910            ErrorKind::Unsupported
911        );
912
913        // Pure red weighs 0.299 under BT.601 and 0.2126 under BT.709 -- the two must not agree,
914        // otherwise the policy is being ignored.
915        let bt601 = convert_from_raw::<_, Gray8>(
916            src,
917            ConvertPolicy::lossless().with_luma(LumaPolicy::Bt601),
918        )
919        .unwrap();
920        let bt709 = convert_from_raw::<_, Gray8>(
921            src,
922            ConvertPolicy::lossless().with_luma(LumaPolicy::Bt709),
923        )
924        .unwrap();
925        assert_eq!(bt601.as_samples(), &[76]); // round(0.299 * 255)
926        assert_eq!(bt709.as_samples(), &[54]); // round(0.2126 * 255)
927        assert_ne!(bt601.as_samples(), bt709.as_samples());
928    }
929
930    #[test]
931    fn luma_rounds_to_nearest_rather_than_truncating() {
932        // BT.709 red weight is 13933, so an input of 3 sums to 41799 -- less than one full unit
933        // (65536) but more than half of it. Rounding gives 1, truncation gives 0. A 16-bit target
934        // keeps the difference visible instead of re-quantising it away.
935        let src = raw(&[3u16, 0, 0], PixelFormat::Rgb16);
936        let policy = ConvertPolicy::lossless().with_luma(LumaPolicy::Bt709);
937        assert_eq!(
938            convert_from_raw::<_, Gray16>(src, policy)
939                .unwrap()
940                .as_samples(),
941            &[1]
942        );
943    }
944
945    #[test]
946    fn a_grey_source_reaches_a_grey_target_unchanged() {
947        // The luma reduction runs unconditionally for a grey target, so every value must survive it
948        // bit-exactly -- otherwise GrayAlpha8 -> Gray8 would drift.
949        let policy = ConvertPolicy::lossless().with_alpha(AlphaPolicy::Drop);
950        for value in 0..=u8::MAX {
951            let samples = [value, 255];
952            let src = raw(&samples, PixelFormat::GrayAlpha8);
953            let out = convert_from_raw::<_, Gray8>(src, policy).unwrap();
954            assert_eq!(out.as_samples(), &[value]);
955        }
956    }
957
958    #[test]
959    fn narrowing_samples_needs_a_depth_policy() {
960        let src = raw(&[0xFFFFu16, 0x8080, 0], PixelFormat::Rgb16);
961        assert_eq!(
962            convert_from_raw::<_, Rgb8>(src, ConvertPolicy::lossless())
963                .unwrap_err()
964                .kind(),
965            ErrorKind::Unsupported
966        );
967        let narrowed = convert_from_raw::<_, Rgb8>(
968            src,
969            ConvertPolicy::lossless().with_depth(DepthPolicy::Rescale),
970        )
971        .unwrap();
972        // Full scale must reach full scale: a truncating `>> 8` would give 254 for 0xFFFF.
973        assert_eq!(narrowed.as_samples(), &[255, 128, 0]);
974    }
975
976    #[test]
977    fn bilevel_expands_losslessly_and_thresholds_on_the_way_back() {
978        // Both conventions for "white" (1 from a 1-bit decoder, 255 from `write`) must expand.
979        for white in [1u8, 255] {
980            let samples = [white];
981            let src = raw(&samples, PixelFormat::Bilevel);
982            let grey = convert_from_raw::<_, Gray8>(src, ConvertPolicy::lossless()).unwrap();
983            assert_eq!(grey.as_samples(), &[255]);
984        }
985        let black = raw(&[0u8], PixelFormat::Bilevel);
986        assert_eq!(
987            convert_from_raw::<_, Gray8>(black, ConvertPolicy::lossless())
988                .unwrap()
989                .as_samples(),
990            &[0]
991        );
992
993        // Going the other way is a precision loss, and the threshold is respected on both sides.
994        let mid = raw(&[128u8], PixelFormat::Gray8);
995        assert_eq!(
996            convert_from_raw::<_, Bilevel>(mid, ConvertPolicy::lossless())
997                .unwrap_err()
998                .kind(),
999            ErrorKind::Unsupported
1000        );
1001        let rescale = ConvertPolicy::lossless().with_depth(DepthPolicy::Rescale);
1002        assert_eq!(
1003            convert_from_raw::<_, Bilevel>(mid, rescale)
1004                .unwrap()
1005                .as_samples(),
1006            &[255]
1007        );
1008        // 128 widens to 0x8080, just above the default midpoint; raising the threshold flips it.
1009        assert_eq!(
1010            convert_from_raw::<_, Bilevel>(mid, rescale.with_threshold(0x8081))
1011                .unwrap()
1012                .as_samples(),
1013            &[0]
1014        );
1015    }
1016
1017    #[test]
1018    fn palette_and_cmyk_convert_only_to_themselves() {
1019        let strict = ConvertPolicy::lossless();
1020        let permissive = ConvertPolicy::permissive();
1021
1022        let indexed = raw(&[5u8], PixelFormat::Indexed8);
1023        let cmyk = raw(&[1u8, 2, 3, 4], PixelFormat::Cmyk8);
1024
1025        // Refused in both directions, and not rescued by a permissive policy -- the machinery is
1026        // missing, so no policy can authorise it.
1027        for policy in [strict, permissive] {
1028            assert_eq!(
1029                convert_from_raw::<_, Rgb8>(indexed, policy)
1030                    .unwrap_err()
1031                    .kind(),
1032                ErrorKind::Unsupported
1033            );
1034            assert_eq!(
1035                convert_from_raw::<_, Rgb8>(cmyk, policy)
1036                    .unwrap_err()
1037                    .kind(),
1038                ErrorKind::Unsupported
1039            );
1040            let rgb = raw(&[1u8, 2, 3], PixelFormat::Rgb8);
1041            assert_eq!(
1042                convert_from_raw::<_, Cmyk8>(rgb, policy)
1043                    .unwrap_err()
1044                    .kind(),
1045                ErrorKind::Unsupported
1046            );
1047            assert_eq!(
1048                convert_from_raw::<_, Indexed8>(rgb, policy)
1049                    .unwrap_err()
1050                    .kind(),
1051                ErrorKind::Unsupported
1052            );
1053        }
1054
1055        // Each refusal names the machinery it is missing; they are not interchangeable.
1056        let indexed_err = convert_from_raw::<_, Rgb8>(indexed, strict).unwrap_err();
1057        let cmyk_err = convert_from_raw::<_, Rgb8>(cmyk, strict).unwrap_err();
1058        let indexed_msg = indexed_err.static_message().unwrap();
1059        let cmyk_msg = cmyk_err.static_message().unwrap();
1060        assert_ne!(indexed_msg, cmyk_msg);
1061        assert!(indexed_msg.contains("palette"), "{indexed_msg}");
1062        assert!(cmyk_msg.contains("colour-management"), "{cmyk_msg}");
1063
1064        // Identity still works: the samples pass straight through.
1065        assert_eq!(
1066            convert_from_raw::<_, Indexed8>(indexed, strict)
1067                .unwrap()
1068                .as_samples(),
1069            &[5]
1070        );
1071        assert_eq!(
1072            convert_from_raw::<_, Cmyk8>(cmyk, strict)
1073                .unwrap()
1074                .as_samples(),
1075            &[1, 2, 3, 4]
1076        );
1077    }
1078
1079    #[test]
1080    fn typed_convert_matches_the_raw_engine() {
1081        let dimensions = dims(2, 1);
1082        let rgba = [10u8, 20, 30, 255, 40, 50, 60, 255];
1083        let image = ImageRef::<Rgba8>::new(&rgba, dimensions).unwrap();
1084        let policy = ConvertPolicy::lossless().with_alpha(AlphaPolicy::Drop);
1085
1086        let typed = convert::<Rgba8, Rgb8>(image, policy).unwrap();
1087        let via_raw = convert_from_raw::<_, Rgb8>(
1088            RawImage::new(&rgba, PixelFormat::Rgba8, dimensions).unwrap(),
1089            policy,
1090        )
1091        .unwrap();
1092        assert_eq!(typed, via_raw);
1093        assert_eq!(typed.as_samples(), &[10, 20, 30, 40, 50, 60]);
1094        assert_eq!(typed.dimensions(), dimensions);
1095    }
1096
1097    #[test]
1098    fn convert_into_reuses_storage_and_validates_length() {
1099        let dimensions = dims(2, 1);
1100        let grey = [1u8, 2];
1101        let src = RawImage::new(&grey, PixelFormat::Gray8, dimensions).unwrap();
1102
1103        let mut dst = ImageBuf::<Rgb8>::zeroed(dimensions).unwrap();
1104        convert_from_raw_into::<_, Rgb8>(src, ConvertPolicy::lossless(), dst.as_mut_samples())
1105            .unwrap();
1106        assert_eq!(dst.as_samples(), &[1, 1, 1, 2, 2, 2]);
1107
1108        // A wrongly sized destination is rejected before anything is written.
1109        let mut short = [0u8; 5];
1110        let err = convert_from_raw_into::<_, Rgb8>(src, ConvertPolicy::lossless(), &mut short)
1111            .unwrap_err();
1112        assert_eq!(err.kind(), ErrorKind::InvalidInput);
1113        assert_eq!(short, [0; 5]);
1114
1115        // A refused conversion leaves the destination untouched too.
1116        let alpha_src = RawImage::new(&[1u8, 2, 3, 4], PixelFormat::Rgba8, dims(1, 1)).unwrap();
1117        let mut target = [9u8; 3];
1118        assert!(
1119            convert_from_raw_into::<_, Rgb8>(alpha_src, ConvertPolicy::lossless(), &mut target)
1120                .is_err()
1121        );
1122        assert_eq!(target, [9; 3]);
1123    }
1124
1125    #[test]
1126    fn raw_image_validates_its_description() {
1127        let samples = [0u8; 6];
1128        assert!(RawImage::new(&samples, PixelFormat::Rgb8, dims(2, 1)).is_ok());
1129        // Wrong sample count.
1130        assert!(RawImage::new(&samples, PixelFormat::Rgb8, dims(3, 1)).is_err());
1131        // Zero-sized.
1132        assert!(RawImage::new(&[] as &[u8], PixelFormat::Rgb8, dims(0, 1)).is_err());
1133        // Sample width disagrees with the format: u8 samples described as a 16-bit layout.
1134        assert!(RawImage::new(&samples, PixelFormat::Rgb16, dims(2, 1)).is_err());
1135        assert!(RawImage::new(&[0u16; 6], PixelFormat::Rgb8, dims(2, 1)).is_err());
1136        // Accessors report what was validated.
1137        let image = RawImage::new(&samples, PixelFormat::Rgb8, dims(2, 1)).unwrap();
1138        assert_eq!(image.format(), PixelFormat::Rgb8);
1139        assert_eq!(image.dimensions(), dims(2, 1));
1140        assert_eq!(image.as_samples().len(), 6);
1141    }
1142
1143    /// One `RawImage` per format, sized for a single pixel, so the matrix test below can drive
1144    /// every source layout without eleven hand-written buffers.
1145    fn sample_pixel(format: PixelFormat) -> Vec<u8> {
1146        (0..format.channels()).map(|i| (i as u8 + 1) * 17).collect()
1147    }
1148
1149    /// Whether `src -> dst` should succeed under `permissive`, derived independently of `Plan` so
1150    /// the test states the contract rather than restating the implementation.
1151    fn expected_supported(src: PixelFormat, dst: PixelFormat) -> bool {
1152        let opaque =
1153            |f: PixelFormat| matches!(f.color_model(), ColorModel::Cmyk | ColorModel::Indexed);
1154        if opaque(src) || opaque(dst) {
1155            return src == dst;
1156        }
1157        true
1158    }
1159
1160    #[test]
1161    fn every_layout_pair_is_either_supported_or_refused() {
1162        // Drives all 11 x 11 = 121 pairs. Under `permissive` every pair must succeed except those
1163        // involving the two layouts this module deliberately excludes; under `lossless` a pair may
1164        // additionally refuse, but must never panic or produce a wrongly sized buffer.
1165        for &src in PixelFormat::ALL {
1166            for &dst in PixelFormat::ALL {
1167                let bytes = sample_pixel(src);
1168                let result = if src.bytes_per_sample() == 1 {
1169                    run_pair(RawImage::new(&bytes, src, dims(1, 1)).unwrap(), dst)
1170                } else {
1171                    let widened: Vec<u16> = bytes.iter().map(|&b| u16::from(b) * 257).collect();
1172                    run_pair(RawImage::new(&widened, src, dims(1, 1)).unwrap(), dst)
1173                };
1174                assert_eq!(
1175                    result.is_ok(),
1176                    expected_supported(src, dst),
1177                    "{src:?} -> {dst:?} disagreed with the documented contract"
1178                );
1179                if let Ok(len) = result {
1180                    assert_eq!(
1181                        len,
1182                        dst.channels(),
1183                        "{src:?} -> {dst:?} wrote a short pixel"
1184                    );
1185                }
1186            }
1187        }
1188    }
1189
1190    /// Converts `src` to the runtime-selected `dst` under `permissive`, reporting the produced
1191    /// sample count. The `match` is the one place the runtime tag is turned back into a brand.
1192    fn run_pair<S: Sample>(src: RawImage<'_, S>, dst: PixelFormat) -> Result<usize> {
1193        let policy = ConvertPolicy::permissive();
1194        macro_rules! go {
1195            ($marker:ty) => {
1196                convert_from_raw::<S, $marker>(src, policy).map(|b| b.as_samples().len())
1197            };
1198        }
1199        match dst {
1200            PixelFormat::Gray8 => go!(Gray8),
1201            PixelFormat::Bilevel => go!(Bilevel),
1202            PixelFormat::Indexed8 => go!(Indexed8),
1203            PixelFormat::Rgb8 => go!(Rgb8),
1204            PixelFormat::Rgba8 => go!(Rgba8),
1205            PixelFormat::Cmyk8 => go!(Cmyk8),
1206            PixelFormat::GrayAlpha8 => go!(GrayAlpha8),
1207            PixelFormat::Gray16 => go!(Gray16),
1208            PixelFormat::Rgb16 => go!(Rgb16),
1209            PixelFormat::Rgba16 => go!(Rgba16),
1210            PixelFormat::GrayAlpha16 => go!(GrayAlpha16),
1211        }
1212    }
1213
1214    #[test]
1215    fn policy_defaults_and_setters_are_independent() {
1216        assert_eq!(ConvertPolicy::default(), ConvertPolicy::lossless());
1217        assert_ne!(ConvertPolicy::lossless(), ConvertPolicy::permissive());
1218
1219        // Each setter must change only its own field; a shared assignment would be invisible to a
1220        // test that only checked one of them.
1221        let base = ConvertPolicy::lossless();
1222        assert_eq!(
1223            base.with_alpha(AlphaPolicy::Drop).depth,
1224            DepthPolicy::Reject
1225        );
1226        assert_eq!(
1227            base.with_depth(DepthPolicy::Rescale).alpha,
1228            AlphaPolicy::Reject
1229        );
1230        assert_eq!(base.with_luma(LumaPolicy::Bt601).luma, LumaPolicy::Bt601);
1231        assert_eq!(base.with_background([1, 2, 3]).background, [1, 2, 3]);
1232        assert_eq!(base.with_threshold(7).threshold, 7);
1233        assert_eq!(base.with_threshold(7).background, [0; 3]);
1234    }
1235
1236    /// One image of layout `P` holding `samples`, laid out as a single row.
1237    fn row<P: Pixel>(samples: Vec<P::Sample>) -> ImageBuf<P> {
1238        let width = u32::try_from(samples.len() / P::CHANNELS).unwrap();
1239        ImageBuf::new(samples, dims(width, 1)).unwrap()
1240    }
1241
1242    #[test]
1243    fn code_values_round_trip_through_the_full_range_scale_at_both_widths() {
1244        assert_eq!(code_max::<u8>(), 255);
1245        assert_eq!(code_max::<u16>(), 65_535);
1246        for code in [0u8, 1, 128, 254, 255] {
1247            assert_eq!(to_code(code, 255), u64::from(code));
1248            assert_eq!(from_code::<u8>(u64::from(code), 255), code);
1249        }
1250        for code in [0u16, 1, 0x8000, 0xFFFE, 0xFFFF] {
1251            assert_eq!(to_code(code, 65_535), u64::from(code));
1252            assert_eq!(from_code::<u16>(u64::from(code), 65_535), code);
1253        }
1254    }
1255
1256    #[test]
1257    fn premultiply_rounds_to_nearest() {
1258        // 1 * 128 / 255 = 0.502: nearest is 1, truncation gives 0.
1259        assert_eq!(premultiply_code(1, 128, 255), 1);
1260        // 1 * 127 / 255 = 0.498: nearest is 0, so the addend must be half of max and not more.
1261        assert_eq!(premultiply_code(1, 127, 255), 0);
1262        assert_eq!(premultiply_code(200, 128, 255), 100); // 100.39
1263        assert_eq!(premultiply_code(255, 0, 255), 0);
1264        assert_eq!(premultiply_code(77, 255, 255), 77);
1265        // 16-bit: 1 * 32768 / 65535 = 0.500008, just above the half.
1266        assert_eq!(premultiply_code(1, 32_768, 65_535), 1);
1267        assert_eq!(premultiply_code(1, 32_767, 65_535), 0);
1268    }
1269
1270    #[test]
1271    fn unpremultiply_rounds_to_nearest_and_clamps() {
1272        // 1 * 255 / 4 = 63.75: nearest is 64, truncation gives 63.
1273        assert_eq!(unpremultiply_code(1, 4, 255), 64);
1274        // 1 * 255 / 2 = 127.5, a tie, which rounds half up.
1275        assert_eq!(unpremultiply_code(1, 2, 255), 128);
1276        // 3 * 255 / 7 = 109.29: half of alpha (3) is the whole addend; more would reach 110.
1277        assert_eq!(unpremultiply_code(3, 7, 255), 109);
1278        assert_eq!(unpremultiply_code(100, 128, 255), 199); // 199.2
1279        assert_eq!(unpremultiply_code(77, 255, 255), 77);
1280        // Colour above its own alpha was never validly premultiplied; it clamps to full scale.
1281        assert_eq!(unpremultiply_code(200, 100, 255), 255);
1282        assert_eq!(unpremultiply_code(2, 1, 65_535), 65_535);
1283        // Transparent: nothing to recover, and no division by zero.
1284        assert_eq!(unpremultiply_code(9, 0, 255), 0);
1285        assert_eq!(unpremultiply_code(1, 2, 65_535), 32_768);
1286    }
1287
1288    #[test]
1289    fn premultiplying_rewrites_colour_and_keeps_alpha() {
1290        let mut rgba = row::<Rgba8>(vec![200, 100, 50, 128, 9, 9, 9, 0, 1, 2, 3, 255]);
1291        premultiply_alpha(&mut rgba);
1292        assert_eq!(
1293            rgba.as_samples(),
1294            &[100, 50, 25, 128, 0, 0, 0, 0, 1, 2, 3, 255]
1295        );
1296        unpremultiply_alpha(&mut rgba);
1297        assert_eq!(
1298            rgba.as_samples(),
1299            &[199, 100, 50, 128, 0, 0, 0, 0, 1, 2, 3, 255]
1300        );
1301
1302        let mut wide = row::<Rgba16>(vec![0xFFFF, 0x8000, 1, 0x8000]);
1303        premultiply_alpha(&mut wide);
1304        assert_eq!(wide.as_samples(), &[0x8000, 0x4000, 1, 0x8000]);
1305    }
1306
1307    #[test]
1308    fn grey_alpha_layouts_carry_alpha_in_their_second_channel() {
1309        let mut narrow = row::<GrayAlpha8>(vec![200, 128, 255, 0]);
1310        premultiply_alpha(&mut narrow);
1311        assert_eq!(narrow.as_samples(), &[100, 128, 0, 0]);
1312
1313        let mut wide = row::<GrayAlpha16>(vec![0x8000, 0x8000]);
1314        unpremultiply_alpha(&mut wide);
1315        assert_eq!(wide.as_samples(), &[0xFFFF, 0x8000]);
1316    }
1317
1318    #[test]
1319    fn a_layout_without_alpha_is_opaque_and_left_unchanged() {
1320        // Were the last channel read as alpha, blue = 0 would erase red and green.
1321        let mut rgb = row::<Rgb8>(vec![200, 100, 0]);
1322        premultiply_alpha(&mut rgb);
1323        assert_eq!(rgb.as_samples(), &[200, 100, 0]);
1324        unpremultiply_alpha(&mut rgb);
1325        assert_eq!(rgb.as_samples(), &[200, 100, 0]);
1326    }
1327
1328    #[test]
1329    fn luma_policies_select_distinct_weights() {
1330        assert_eq!(LumaPolicy::Reject.weights(), None);
1331        assert_eq!(LumaPolicy::Bt601.weights(), Some(BT601_LUMA_WEIGHTS));
1332        assert_eq!(LumaPolicy::Bt709.weights(), Some(BT709_LUMA_WEIGHTS));
1333        assert_eq!(LumaPolicy::Bt2020.weights(), Some(BT2020_LUMA_WEIGHTS));
1334    }
1335}