f-office 0.1.0

Renders Office Open XML documents the way Microsoft Office does.
Documentation
//! Resampling a picture to fewer pixels, as a target's PDF writer does before it writes the
//! picture's file.

use std::collections::VecDeque;

use f_office_paint::{LinearLimit, Resampler};

/// The weights of the source samples of each output sample of one pass.
type Weights = Vec<Vec<(usize, f64)>>;

/// The samples of a picture of `own` pixels with `channels` interleaved 8-bit samples each,
/// resampled to `size` pixels as `resampler` says: by the filter with its limit ([`resample`]) or
/// by the pixel under each new pixel's centre ([`centre_pixels`]).
pub fn resample_by(
    resampler: Resampler,
    samples: &[u8],
    own: (usize, usize),
    channels: usize,
    size: (usize, usize),
) -> Vec<u8> {
    match resampler {
        Resampler::Filter(limit) => resample(samples, own, channels, size, limit),
        Resampler::CentrePixel => centre_pixels(samples, own, channels, size),
    }
}

/// The samples of a picture of `own` pixels with `channels` interleaved samples each, resampled
/// to `size` pixels by the pixel under each new pixel's centre: the new pixel at `x` of `w`
/// takes the pixel at `(2 x + 1) W / 2 w`, rounded down, of `W`, across and down. A pixel that
/// the samples lack, which a picture of its pixels does not have, is left out.
pub fn centre_pixels(
    samples: &[u8],
    own: (usize, usize),
    channels: usize,
    size: (usize, usize),
) -> Vec<u8> {
    let under = |at: usize, from: usize, to: usize| (2 * at + 1) * from / (2 * to);
    let mut out = Vec::with_capacity(size.0 * size.1 * channels);
    for y in 0..size.1 {
        let row = under(y, own.1, size.1) * own.0;
        for x in 0..size.0 {
            let start = (row + under(x, own.0, size.0)) * channels;
            out.extend_from_slice(samples.get(start..start + channels).unwrap_or_default());
        }
    }
    out
}

/// The samples of a picture of `own` pixels with `channels` interleaved 8-bit samples each,
/// resampled to `size` pixels: across first, then down. A picture that `limit` names
/// ([`LinearLimit::takes_linear`]) takes the linear interpolation between the two source pixels
/// at `x W / w`, with no rounding between the passes. Another takes the mean of the source area
/// that each output pixel covers, rounded to whole levels after the pass across, half to
/// even. Each result is rounded to the nearest level, half to even. The pass down takes the
/// rows of the pass across one at a time, so the floats in memory are a few output rows, not
/// the whole picture.
pub fn resample(
    samples: &[u8],
    own: (usize, usize),
    channels: usize,
    size: (usize, usize),
    limit: LinearLimit,
) -> Vec<u8> {
    let linear = limit.takes_linear(own);
    let weights = |from: usize, to: usize| {
        if linear {
            linear_weights(from, to)
        } else {
            area_weights(from, to)
        }
    };
    let (across, down) = (weights(own.0, size.0), weights(own.1, size.1));
    passes(samples, own, channels, (&across, &down), linear)
}

/// The samples of the visible part `part` (its left, top, right and bottom edges in pixels) of
/// a picture of `own` pixels with `channels` interleaved 8-bit samples each, resampled to
/// `size` pixels at the part's scale, the written count over the part's count on each axis.
/// The whole picture is resampled by the mean of the area, as [`resample`] takes it, to its
/// count times the scale, rounded to the nearest whole pixel, a half up; then written pixel `x`
/// takes the place of the part's first pixel times the scale, plus `x`, by the linear
/// interpolation with no rounding between the passes, each place held inside the picture.
pub fn resample_part_at_scale(
    samples: &[u8],
    own: (usize, usize),
    channels: usize,
    part: [usize; 4],
    size: (usize, usize),
) -> Vec<u8> {
    let [left, top, right, bottom] = part;
    let (part_width, part_height) = (right.saturating_sub(left), bottom.saturating_sub(top));
    let scaled = (
        scaled_count(own.0, size.0, part_width),
        scaled_count(own.1, size.1, part_height),
    );
    let first = passes(
        samples,
        own,
        channels,
        (
            &area_weights(own.0, scaled.0),
            &area_weights(own.1, scaled.1),
        ),
        false,
    );
    let across = placed_weights(left, size.0, part_width, scaled.0);
    let down = placed_weights(top, size.1, part_height, scaled.1);
    passes(&first, scaled, channels, (&across, &down), true)
}

/// The samples of a picture of `own` pixels with `channels` interleaved samples each through
/// the pass across with the taps of `across` and the pass down with those of `down`, one list
/// of taps for each output sample, rounded to whole levels after the pass across unless
/// `linear`.
fn passes(
    samples: &[u8],
    own: (usize, usize),
    channels: usize,
    (across, down): (&Weights, &Weights),
    linear: bool,
) -> Vec<u8> {
    let row = own.0 * channels;
    let mut pass_down = PassDown::new(down, own.1, across.len() * channels);
    let mut across_row = vec![0.0; across.len() * channels];
    for y in 0..own.1 {
        let source = samples.get(y * row..(y + 1) * row).unwrap_or_default();
        pass_across(source, (across, channels, linear), &mut across_row);
        pass_down.take(y, &across_row);
    }
    pass_down.finish()
}

/// The count of `whole` pixels at the scale `written / part`, rounded to the nearest whole
/// pixel, a half up, and at least 1.
fn scaled_count(whole: usize, written: usize, part: usize) -> usize {
    let part = part.max(1);
    let doubled = whole.saturating_mul(written).saturating_mul(2);
    (doubled.saturating_add(part) / part.saturating_mul(2)).max(1)
}

/// The linear interpolation of each of `to` samples among `from` samples at the place `first`
/// times `to / part`, plus its index, between the two samples around it, each place held
/// inside the samples.
fn placed_weights(first: usize, to: usize, part: usize, from: usize) -> Weights {
    let last = from.saturating_sub(1);
    let start = index(first) * ratio(to, part);
    (0..to)
        .map(|x| {
            let place = (start + index(x)).min(index(last));
            let left = place.floor();
            let share = place - left;
            let left = whole(left).min(last);
            vec![(left, 1.0 - share), ((left + 1).min(last), share)]
        })
        .collect()
}

/// The pass across of one source row: each output sample of `row` from the source samples
/// that its taps name, kept as a float for linear interpolation and rounded to a whole level,
/// half to even, for the mean of an area.
fn pass_across(
    source: &[u8],
    (across, channels, linear): (&Weights, usize, bool),
    row: &mut [f64],
) {
    let pixels = row.chunks_exact_mut(channels.max(1));
    for (taps, pixel) in across.iter().zip(pixels) {
        for (c, sample) in pixel.iter_mut().enumerate() {
            let value = taps
                .iter()
                .map(|&(at, w)| f64::from(source.get(at * channels + c).copied().unwrap_or(0)) * w)
                .sum::<f64>();
            *sample = if linear {
                value
            } else {
                value.round_ties_even()
            };
        }
    }
}

/// The pass down, which takes the rows of the pass across one at a time and keeps only the
/// sums of the output rows that are not written yet, in place of a float copy of the whole
/// picture after the pass across.
struct PassDown {
    /// The output rows that take each source row, with its weight, in the order of their taps.
    takers: Vec<Vec<(usize, f64)>>,
    /// The last source row of each output row, or none for an output row without taps.
    last: Vec<Option<usize>>,
    /// The sums of the output rows from `written` on. Each sum adds its terms in the order of
    /// its taps from the start of a float sum, as a sum over the whole picture after the pass
    /// across does, so each sample stays the same.
    open: VecDeque<Vec<f64>>,
    /// The output rows written.
    written: usize,
    /// The samples of an output row.
    line: usize,
    out: Vec<u8>,
}

impl PassDown {
    /// The pass down of `down` over `rows` source rows of `line` samples.
    fn new(down: &Weights, rows: usize, line: usize) -> Self {
        let mut takers = vec![Vec::new(); rows];
        for (output, taps) in down.iter().enumerate() {
            for &(at, w) in taps {
                if let Some(taker) = takers.get_mut(at) {
                    taker.push((output, w));
                }
            }
        }
        Self {
            takers,
            last: down
                .iter()
                .map(|taps| taps.iter().map(|&(at, _)| at).max())
                .collect(),
            open: VecDeque::new(),
            written: 0,
            line,
            out: Vec::with_capacity(down.len() * line),
        }
    }

    /// Adds source row `y` after the pass across to the sums of its output rows, and writes
    /// the output rows whose last source row it is, in their order.
    fn take(&mut self, y: usize, row: &[f64]) {
        for &(output, w) in self.takers.get(y).map_or(&[][..], Vec::as_slice) {
            while self.written + self.open.len() <= output {
                self.open.push_back(vec![-0.0; self.line]);
            }
            if let Some(sum) = self.open.get_mut(output - self.written) {
                for (total, &value) in sum.iter_mut().zip(row) {
                    *total += value * w;
                }
            }
        }
        while let Some(&last) = self.last.get(self.written)
            && last.is_none_or(|at| at <= y)
        {
            self.write_next();
        }
    }

    /// Writes the levels of the next output row; a row without terms gives zero levels.
    fn write_next(&mut self) {
        match self.open.pop_front() {
            Some(sum) => self.out.extend(sum.into_iter().map(level)),
            None => self.out.extend(std::iter::repeat_n(0, self.line)),
        }
        self.written += 1;
    }

    /// The output samples, after the output rows that still wait are written.
    fn finish(mut self) -> Vec<u8> {
        while self.written < self.last.len() {
            self.write_next();
        }
        self.out
    }
}

/// A sample value rounded to the nearest level, half to even, within 0 to 255.
fn level(value: f64) -> u8 {
    let rounded = value.round_ties_even().clamp(0.0, 255.0);
    // The value lies within 0 to 255 after the clamp.
    #[expect(
        clippy::cast_possible_truncation,
        clippy::cast_sign_loss,
        reason = "clamped to 0..=255"
    )]
    let level = rounded as u8;
    level
}

/// The linear interpolation of each of `to` samples at `x from / to` between the two source
/// samples around it, the last source sample standing for those beyond the edge.
fn linear_weights(from: usize, to: usize) -> Weights {
    let scale = ratio(from, to);
    (0..to)
        .map(|x| {
            let place = index(x) * scale;
            let left = place.floor();
            let share = place - left;
            let left = whole(left).min(from - 1);
            vec![(left, 1.0 - share), ((left + 1).min(from - 1), share)]
        })
        .collect()
}

/// The mean of the source samples that each of `to` samples covers, each weighted by the
/// share of it that lies inside, when `to` samples span the `from` source samples.
fn area_weights(from: usize, to: usize) -> Weights {
    let scale = ratio(from, to);
    (0..to)
        .map(|x| {
            let (low, high) = (index(x) * scale, index(x + 1) * scale);
            let mut taps: Vec<(usize, f64)> = (whole(low.floor())..whole(high.ceil()).min(from))
                .map(|at| {
                    let cover = high.min(index(at + 1)) - low.max(index(at));
                    (at, cover.max(0.0))
                })
                .collect();
            let total: f64 = taps.iter().map(|&(_, w)| w).sum();
            if total > 0.0 {
                for tap in &mut taps {
                    tap.1 /= total;
                }
            }
            taps
        })
        .collect()
}

/// `from / to` as a float.
fn ratio(from: usize, to: usize) -> f64 {
    index(from) / index(to.max(1))
}

/// A pixel index as a float; picture sizes stay far below 2^52.
#[expect(
    clippy::cast_precision_loss,
    reason = "picture sizes stay far below 2^52"
)]
const fn index(i: usize) -> f64 {
    i as f64
}

/// A whole, non-negative float as an index.
#[expect(
    clippy::cast_possible_truncation,
    clippy::cast_sign_loss,
    reason = "whole and non-negative"
)]
const fn whole(value: f64) -> usize {
    value as usize
}

#[cfg(test)]
mod tests;