f-office-paint 0.2.3

Display list: the contract between layout and output.
Documentation
//! Per-pixel color conversions applied to decoded straight RGBA image pixels.

use std::sync::Arc;

use crate::Rgb;

/// Whole percentage in DrawingML (`ST_FixedPercentage`): 100,000 = 100%.
const PERCENT_WHOLE: i32 = 100_000;

/// One per-pixel color effect applied to straight RGBA pixels of a decoded image.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ColorEffect {
    /// Encoded RGB weighted by 0.2126, 0.7152 and 0.0722, truncated to a byte. Alpha unchanged.
    Gray709,
    /// Brightness (`bright`) and contrast (`contrast`), each in thousandths of a percent
    /// (`-100_000..=100_000`). Applies gain `g = 1 / (1 - C)` for `C >= 0` or `1 + C` for `C < 0`
    /// with affine channel map `v' = (v / 255 - 0.5 + B / 2) * g + 0.5 + B / 2`, clamped to
    /// `0..=255` and truncated. Alpha unchanged.
    Luminance {
        /// Brightness shift in thousandths of a percent.
        bright: i32,
        /// Contrast adjustment in thousandths of a percent.
        contrast: i32,
    },
    /// Thresholds encoded Rec. 709 luminance against `threshold` in thousandths of a percent
    /// (`0..=100_000`): channels become `255` when `lum >= threshold * 255`, else `0`. Alpha
    /// unchanged.
    BiLevel {
        /// Threshold in thousandths of a percent.
        threshold: i32,
    },
    /// Maps truncated Rec. 709 gray byte `g` linearly from `dark` (at `g = 0`) to `light` (at
    /// `g = 255`), rounding half-up per channel. Alpha unchanged.
    Duotone {
        /// Color mapped to black (`g = 0`).
        dark: Rgb,
        /// Color mapped to white (`g = 255`).
        light: Rgb,
    },
    /// Replaces pixels matching `from` with `to` (and sets alpha to `to_alpha` when `use_alpha`
    /// is true; with `use_alpha`, matching allows a channel difference of at most 1, whereas
    /// without `use_alpha` matching is exact on RGB and keeps source alpha).
    ColorChange {
        /// Source color to match.
        from: Rgb,
        /// Replacement RGB color.
        to: Rgb,
        /// Replacement alpha byte used when `use_alpha` is true.
        to_alpha: u8,
        /// Whether replacement updates alpha and uses the alpha-enabled matching tolerance.
        use_alpha: bool,
    },
}

/// The color conversion of one use of an image. The format crate chooses it;
/// the output crates apply the same arithmetic without knowing the format.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum ImageColor {
    /// Preserve decoded channels.
    #[default]
    Original,
    /// Encoded RGB weighted by 0.2126, 0.7152 and 0.0722, truncated to a byte.
    /// Alpha is unchanged. This is a channel conversion, not linear-light RGB.
    Gray709,
    /// One or more color effects applied in order.
    Effects(Arc<[ColorEffect]>),
}

impl ImageColor {
    /// Builds an [`ImageColor`] from an ordered list of [`ColorEffect`]s, collapsing consecutive
    /// `Gray709` steps and normalizing empty and single-grayscale lists to [`Self::Original`] and
    /// [`Self::Gray709`].
    #[must_use]
    pub fn from_effects(effects: Vec<ColorEffect>) -> Self {
        let mut normalized: Vec<ColorEffect> = Vec::with_capacity(effects.len());
        for effect in effects {
            if effect == ColorEffect::Gray709 && normalized.last() == Some(&ColorEffect::Gray709) {
                continue;
            }
            normalized.push(effect);
        }
        match normalized.as_slice() {
            [] => Self::Original,
            [ColorEffect::Gray709] => Self::Gray709,
            _ => Self::Effects(normalized.into()),
        }
    }

    /// Applies this conversion to straight RGBA pixels.
    pub fn apply(&self, rgba: &mut [u8]) {
        match self {
            Self::Original => {}
            Self::Gray709 => apply_effect(ColorEffect::Gray709, rgba),
            Self::Effects(effects) => {
                for &effect in effects.iter() {
                    apply_effect(effect, rgba);
                }
            }
        }
    }
}

/// Rec. 709 weighted encoded-RGB luminance numerator out of `10_000 * 255`.
#[inline]
fn luma_10000(r: u8, g: u8, b: u8) -> u32 {
    2126 * u32::from(r) + 7152 * u32::from(g) + 722 * u32::from(b)
}

/// Truncated Rec. 709 gray byte.
#[inline]
fn gray709_byte(r: u8, g: u8, b: u8) -> u8 {
    u8::try_from(luma_10000(r, g, b) / 10_000).unwrap_or(u8::MAX)
}

/// Builds a 256-entry channel lookup table for [`ColorEffect::Luminance`].
fn luminance_lut(bright: i32, contrast: i32) -> [u8; 256] {
    let s = i128::from(PERCENT_WHOLE);
    let b = i128::from(bright.clamp(-PERCENT_WHOLE, PERCENT_WHOLE));
    let c = i128::from(contrast.clamp(-PERCENT_WHOLE, PERCENT_WHOLE));
    let mut lut = [0u8; 256];
    if c >= s {
        let rhs = 255 * (s - b);
        for (idx, slot) in lut.iter_mut().enumerate() {
            let v = i128::try_from(idx).unwrap_or(0);
            *slot = if 2 * s * v >= rhs { u8::MAX } else { 0 };
        }
        return lut;
    }
    let (num_g, den_g) = if c >= 0 { (s, s - c) } else { (s + c, s) };
    let den = 2 * s * den_g;
    let offset = 255 * (s * (den_g - num_g) + b * (den_g + num_g));
    for (idx, slot) in lut.iter_mut().enumerate() {
        let v = i128::try_from(idx).unwrap_or(0);
        let num = 2 * s * num_g * v + offset;
        *slot = if num <= 0 {
            0
        } else {
            u8::try_from((num / den).min(255)).unwrap_or(u8::MAX)
        };
    }
    lut
}

/// Builds a 256-entry RGB lookup table for [`ColorEffect::Duotone`].
fn duotone_lut(dark: Rgb, light: Rgb) -> [[u8; 3]; 256] {
    let mix = |c1: u8, c2: u8, g: u32| -> u8 {
        let v = (u32::from(c1) * (255 - g) + u32::from(c2) * g + 127) / 255;
        u8::try_from(v).unwrap_or(u8::MAX)
    };
    let mut lut = [[0u8; 3]; 256];
    for (idx, slot) in lut.iter_mut().enumerate() {
        let g = u32::try_from(idx).unwrap_or(0);
        *slot = [
            mix(dark.r, light.r, g),
            mix(dark.g, light.g, g),
            mix(dark.b, light.b, g),
        ];
    }
    lut
}

/// Applies one [`ColorEffect`] in place to straight RGBA pixels.
fn apply_effect(effect: ColorEffect, rgba: &mut [u8]) {
    let pixels = rgba.as_chunks_mut::<4>().0;
    match effect {
        ColorEffect::Gray709 => apply_gray(pixels),
        ColorEffect::Luminance { bright, contrast } => apply_luminance(pixels, bright, contrast),
        ColorEffect::BiLevel { threshold } => apply_bilevel(pixels, threshold),
        ColorEffect::Duotone { dark, light } => apply_duotone(pixels, dark, light),
        ColorEffect::ColorChange {
            from,
            to,
            to_alpha,
            use_alpha,
        } => apply_color_change(pixels, from, to, to_alpha, use_alpha),
    }
}

fn apply_gray(pixels: &mut [[u8; 4]]) {
    for pixel in pixels {
        let gray = gray709_byte(pixel[0], pixel[1], pixel[2]);
        pixel[0] = gray;
        pixel[1] = gray;
        pixel[2] = gray;
    }
}

fn apply_luminance(pixels: &mut [[u8; 4]], bright: i32, contrast: i32) {
    let lut = luminance_lut(bright, contrast);
    for pixel in pixels {
        for ch in pixel.iter_mut().take(3) {
            *ch = lut.get(usize::from(*ch)).copied().unwrap_or(*ch);
        }
    }
}

fn apply_bilevel(pixels: &mut [[u8; 4]], threshold: i32) {
    let thresh = u32::try_from(threshold.clamp(0, PERCENT_WHOLE)).unwrap_or(0);
    let rhs = thresh * 255;
    for pixel in pixels {
        let v = if luma_10000(pixel[0], pixel[1], pixel[2]) * 10 >= rhs {
            u8::MAX
        } else {
            0
        };
        pixel[0] = v;
        pixel[1] = v;
        pixel[2] = v;
    }
}

fn apply_duotone(pixels: &mut [[u8; 4]], dark: Rgb, light: Rgb) {
    let lut = duotone_lut(dark, light);
    for pixel in pixels {
        let gray = usize::from(gray709_byte(pixel[0], pixel[1], pixel[2]));
        let [r, g, b] = lut.get(gray).copied().unwrap_or([0, 0, 0]);
        pixel[0] = r;
        pixel[1] = g;
        pixel[2] = b;
    }
}

fn apply_color_change(pixels: &mut [[u8; 4]], from: Rgb, to: Rgb, to_alpha: u8, use_alpha: bool) {
    let tol = u8::from(use_alpha);
    for pixel in pixels {
        if pixel[0].abs_diff(from.r) <= tol
            && pixel[1].abs_diff(from.g) <= tol
            && pixel[2].abs_diff(from.b) <= tol
        {
            pixel[0] = to.r;
            pixel[1] = to.g;
            pixel[2] = to.b;
            if use_alpha {
                pixel[3] = to_alpha;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{ColorEffect, ImageColor};
    use crate::Rgb;

    #[test]
    fn normalizes_empty_and_repeated_grayscale_effects() {
        assert_eq!(ImageColor::from_effects(vec![]), ImageColor::Original);
        assert_eq!(
            ImageColor::from_effects(vec![ColorEffect::Gray709, ColorEffect::Gray709]),
            ImageColor::Gray709
        );
    }

    #[test]
    fn applies_washout_luminance_duotone_bilevel_and_color_change() {
        // Washout (+70% bright, -70% contrast) on black (0) -> 205, mid-gray (128) -> 243.
        let washout = ImageColor::from_effects(vec![ColorEffect::Luminance {
            bright: 70_000,
            contrast: -70_000,
        }]);
        let mut px = [0, 0, 0, 200, 128, 128, 128, 100];
        washout.apply(&mut px);
        assert_eq!(px, [205, 205, 205, 200, 243, 243, 243, 100]);

        // Duotone dark blue (31, 78, 121) to white (255, 255, 255) on gray 128 -> (143, 167, 188).
        let duo = ImageColor::from_effects(vec![ColorEffect::Duotone {
            dark: Rgb {
                r: 0x1F,
                g: 0x4E,
                b: 0x79,
            },
            light: Rgb::WHITE,
        }]);
        let mut dpx = [128, 128, 128, 180];
        duo.apply(&mut dpx);
        assert_eq!(dpx, [143, 167, 188, 180]);

        // BiLevel 50%: 127 -> 0, 128 -> 255, preserving alpha.
        let bi = ImageColor::from_effects(vec![ColorEffect::BiLevel { threshold: 50_000 }]);
        let mut bpx = [127, 127, 127, 90, 128, 128, 128, 90];
        bi.apply(&mut bpx);
        assert_eq!(bpx, [0, 0, 0, 90, 255, 255, 255, 90]);

        // ColorChange: white -> transparent with use_alpha=true matches 254 and 255, not 253.
        let cc = ImageColor::from_effects(vec![ColorEffect::ColorChange {
            from: Rgb::WHITE,
            to: Rgb::WHITE,
            to_alpha: 0,
            use_alpha: true,
        }]);
        let mut cpx = [253, 253, 253, 255, 254, 254, 254, 255, 255, 255, 255, 255];
        cc.apply(&mut cpx);
        assert_eq!(
            cpx,
            [253, 253, 253, 255, 255, 255, 255, 0, 255, 255, 255, 0]
        );
    }
}