use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::{Arc, Mutex};
use f_office_paint::{
AlphaMix, DEFAULT_IMAGE_BYTES_CACHE, DisplayList, GroupPlaces, ImageData, ImageFormat, ImageId,
ImageItem, ImageLoader, ImageRef, Item, JpegQuality, JpegSample, JpegShare, LruBytesCache,
MAX_DECODED_BYTES, MAX_DECODED_BYTES_TO_WRITE_AGAIN, PaletteClass, PictureCrop, Resampler,
next_store_id,
};
use f_office_units::div_round_i128;
use crate::{Warning, Warnings};
use f_office_paint::image_header::{
jpeg_header, png_color_type, png_header, png_header_complete, png_palette_class,
};
mod resample;
type Part = [usize; 4];
type Resampled = ((usize, usize), Resampler);
type Key = (usize, Option<Part>, Option<Resampled>);
#[derive(Default)]
struct Files {
by_place: HashMap<SamePlace, usize>,
by_bytes: HashMap<Arc<[u8]>, usize>,
headers: HashMap<(usize, ImageFormat), Header>,
}
impl Files {
fn number(&mut self, data: &Arc<[u8]>) -> usize {
let by_bytes = &mut self.by_bytes;
*self
.by_place
.entry(SamePlace(Arc::clone(data)))
.or_insert_with(|| {
count_read_bytes(data.len());
let next = by_bytes.len();
*by_bytes.entry(Arc::clone(data)).or_insert(next)
})
}
fn header(&mut self, number: usize, data: &[u8], format: ImageFormat) -> Header {
*self.headers.entry((number, format)).or_insert_with(|| {
count_read_bytes(data.len());
Header::of(data, format)
})
}
}
struct SamePlace(Arc<[u8]>);
impl PartialEq for SamePlace {
fn eq(&self, other: &Self) -> bool {
Arc::ptr_eq(&self.0, &other.0)
}
}
impl Eq for SamePlace {}
impl Hash for SamePlace {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.as_ptr().addr().hash(state);
}
}
#[derive(Clone, Copy)]
struct Header {
pixels: Option<(usize, usize)>,
jpeg_rewritable: bool,
palette: Option<PaletteClass>,
png_rgb: bool,
}
impl Header {
fn of(data: &[u8], format: ImageFormat) -> Self {
match format {
ImageFormat::Jpeg => Self {
pixels: jpeg_header(data).map(|header| header.pixels),
jpeg_rewritable: jpeg_frame_rewritable(data),
palette: None,
png_rgb: false,
},
ImageFormat::Png => Self {
pixels: png_header(data).map(|header| header.pixels),
jpeg_rewritable: false,
palette: png_palette_class(data),
png_rgb: png_color_type(data).is_some_and(|kind| RGB_TYPES.contains(&kind)),
},
_ => Self {
pixels: None,
jpeg_rewritable: false,
palette: None,
png_rgb: false,
},
}
}
fn of_lazy(handle: &ImageRef, format: ImageFormat) -> Self {
const PREFIX: usize = 64 * 1024;
if let Some(prefix) = handle.load_prefix(PREFIX) {
let header = Self::of(&prefix, format);
let complete = match format {
ImageFormat::Jpeg => header.pixels.is_some(),
ImageFormat::Png => png_header_complete(&prefix) || prefix.len() < PREFIX,
_ => true,
};
if complete {
return header;
}
}
handle.load().map_or(
Self {
pixels: None,
jpeg_rewritable: false,
palette: None,
png_rgb: false,
},
|full| Self::of(&full, format),
)
}
}
fn be16(data: &[u8], offset: usize) -> Option<usize> {
let bytes: [u8; 2] = data.get(offset..offset.checked_add(2)?)?.try_into().ok()?;
Some(usize::from(u16::from_be_bytes(bytes)))
}
fn jpeg_frame_rewritable(data: &[u8]) -> bool {
let Some((marker, body)) = jpeg_sof_segment(data) else {
return false;
};
if !matches!(marker, 0xC0..=0xC2) || body.first() != Some(&8) {
return false;
}
let (Some(height), Some(width), Some(&count)) = (be16(body, 1), be16(body, 3), body.get(5))
else {
return false;
};
let count = usize::from(count);
if width == 0 || height == 0 || !matches!(count, 1 | 3) {
return false;
}
let Some(fields) = body.get(6..6 + 3 * count) else {
return false;
};
jpeg_sampling_within_limit(fields, (width, height), count)
}
fn jpeg_sampling_within_limit(
fields: &[u8],
(width, height): (usize, usize),
count: usize,
) -> bool {
let mut parts = [(0_usize, 0_usize); 3];
let (mut h_max, mut v_max) = (0_usize, 0_usize);
for (idx, &[_, sampling, table]) in fields.as_chunks::<3>().0.iter().enumerate() {
let (h, v) = (usize::from(sampling >> 4), usize::from(sampling & 15));
if h == 0 || v == 0 || table > 3 {
return false;
}
h_max = h_max.max(h);
v_max = v_max.max(v);
if let Some(slot) = parts.get_mut(idx) {
*slot = (h, v);
}
}
let Some(active) = parts.get(..count) else {
return false;
};
if active.iter().any(|&(h, v)| {
!h_max.is_multiple_of(h)
|| !v_max.is_multiple_of(v)
|| !matches!((h_max / h, v_max / v), (1 | 2, 1) | (2, 2))
}) {
return false;
}
let mcus = (width.div_ceil(8 * h_max), height.div_ceil(8 * v_max));
let Some(blocks) = active.iter().try_fold(0_usize, |sum, &(h, v)| {
sum.checked_add(mcus.0.checked_mul(h)?.checked_mul(mcus.1.checked_mul(v)?)?)
}) else {
return false;
};
blocks
.checked_mul(size_of::<[i32; 64]>())
.and_then(|bytes| u64::try_from(bytes).ok())
.is_some_and(|bytes| bytes <= MAX_DECODED_BYTES)
}
fn next_jpeg_marker(data: &[u8], mut at: usize) -> Option<(u8, usize)> {
while data.get(at) == Some(&0xFF) {
at += 1;
}
Some((*data.get(at)?, at + 1))
}
fn jpeg_sof_segment(data: &[u8]) -> Option<(u8, &[u8])> {
(data.get(..2) == Some(&[0xFF, 0xD8])).then_some(())?;
let mut at = 2_usize;
while let Some((marker, next)) = next_jpeg_marker(data, at) {
at = match marker {
0xD9 | 0xDA => return None,
0x01 | 0xD0..=0xD8 => next,
_ => {
let length = be16(data, next)?;
let end = next.checked_add(length)?;
let body = data.get(next.checked_add(2)?..end)?;
if matches!(marker, 0xC0..=0xC3 | 0xC5..=0xC7 | 0xC9..=0xCB | 0xCD..=0xCF) {
return Some((marker, body));
}
end
}
};
}
None
}
#[derive(Clone, Copy, Debug)]
enum LazyRewriteKind {
Jpeg {
quality: JpegQuality,
},
PngOrJpeg {
quality: JpegQuality,
share: JpegShare,
jpeg_sample: Option<JpegSample>,
},
Png,
}
#[derive(Clone, Debug)]
struct LazyRewriteSpec {
source: ImageRef,
format: ImageFormat,
part: Option<Part>,
size: Option<Resampled>,
kind: LazyRewriteKind,
crop: PictureCrop,
alpha_mix: AlphaMix,
}
type LazyKey = (ImageId, Option<Part>, Option<Resampled>);
#[derive(Debug)]
struct LazyRewritingLoader {
store_id: u64,
specs: Mutex<LazySpecTable>,
cache: LruBytesCache,
}
#[derive(Debug, Default)]
struct LazySpecTable {
list: Vec<LazyRewriteSpec>,
by_key: HashMap<LazyKey, u32>,
}
impl LazyRewritingLoader {
fn new() -> Arc<Self> {
Arc::new(Self {
store_id: next_store_id(),
specs: Mutex::new(LazySpecTable::default()),
cache: LruBytesCache::new(DEFAULT_IMAGE_BYTES_CACHE),
})
}
fn intern(self: &Arc<Self>, key: LazyKey, spec: LazyRewriteSpec) -> ImageRef {
let byte_len = spec.source.byte_len();
let index = {
let Ok(mut table) = self.specs.lock() else {
return spec.source;
};
if let Some(&existing) = table.by_key.get(&key) {
existing
} else {
let next = u32::try_from(table.list.len()).unwrap_or(u32::MAX);
table.list.push(spec);
table.by_key.insert(key, next);
next
}
};
ImageRef::new(
ImageId::new(self.store_id, index),
byte_len,
Arc::clone(self) as Arc<dyn ImageLoader>,
)
}
fn spec(&self, index: u32) -> Option<LazyRewriteSpec> {
let table = self.specs.lock().ok()?;
let idx = usize::try_from(index).ok()?;
table.list.get(idx).cloned()
}
}
impl ImageLoader for LazyRewritingLoader {
fn load(&self, index: u32) -> Option<Arc<[u8]>> {
self.load_with_format(index, ImageFormat::Unknown)
.map(|(bytes, _)| bytes)
}
fn load_with_format(
&self,
index: u32,
fallback: ImageFormat,
) -> Option<(Arc<[u8]>, ImageFormat)> {
if let Some(cached) = self.cache.get(index) {
return Some(cached);
}
let spec = self.spec(index)?;
let raw = spec.source.load()?;
let dummy_resampling =
|_pixels: (usize, usize), _palette: Option<PaletteClass>, _item: &ImageItem| None;
let rewritten = match spec.kind {
LazyRewriteKind::Jpeg { quality } => {
jpeg_again(&raw, (spec.part, spec.size), quality, spec.crop)
.map(|bytes| (bytes, ImageFormat::Jpeg))
}
LazyRewriteKind::PngOrJpeg {
quality,
share,
jpeg_sample,
} => {
let rewriting = Rewriting {
quality: Some(quality),
jpeg_share: Some(share),
jpeg_sample,
crop: spec.crop,
alpha_mix: spec.alpha_mix,
resampling: &dummy_resampling,
};
png_or_jpeg(&raw, (spec.part, spec.size), (quality, share), rewriting)
}
LazyRewriteKind::Png => {
png_again(&raw, (spec.part, spec.size), spec.alpha_mix, spec.crop)
.map(|bytes| (bytes, ImageFormat::Png))
}
};
let (bytes, format) = rewritten.unwrap_or((
raw,
if spec.format == ImageFormat::Unknown {
fallback
} else {
spec.format
},
));
self.cache.insert(index, Arc::clone(&bytes), format);
Some((bytes, format))
}
}
#[cfg(test)]
thread_local! {
static READ_BYTES: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn count_read_bytes(bytes: usize) {
#[cfg(test)]
READ_BYTES.with(|read| read.set(read.get() + bytes));
#[cfg(not(test))]
let _ = bytes;
}
pub type Resampling<'a> =
&'a dyn Fn((usize, usize), Option<PaletteClass>, &ImageItem) -> Option<Resampled>;
#[derive(Clone, Copy)]
pub struct Rewriting<'a> {
pub quality: Option<JpegQuality>,
pub jpeg_share: Option<JpegShare>,
pub jpeg_sample: Option<JpegSample>,
pub crop: PictureCrop,
pub alpha_mix: AlphaMix,
pub resampling: Resampling<'a>,
}
pub fn write_pictures_again(
list: DisplayList,
rewriting: Rewriting,
warnings: &mut Warnings,
) -> DisplayList {
let mut files = Files::default();
let mut lazy_headers: HashMap<(ImageId, ImageFormat), Header> = HashMap::new();
let mut written: HashMap<Key, Option<Written>> = HashMap::new();
let lazy_loader = LazyRewritingLoader::new();
let mut pages = Vec::new();
for page in list.into_pages() {
pages.push(page.map_items(|mut items| {
for image in page_images(&mut items) {
match &image.image.data {
ImageData::Lazy(handle) => {
let handle = handle.clone();
rewrite_lazy_image(
image,
handle,
rewriting,
(&mut lazy_headers, &lazy_loader),
warnings,
);
}
ImageData::Inline(data) => {
let data = Arc::clone(data);
rewrite_inline_image(
image,
&data,
rewriting,
(&mut files, &mut written),
warnings,
);
}
}
}
items
}));
}
DisplayList::new(pages)
}
fn rewrite_geometry(
image: &ImageItem,
header: Header,
rewriting: Rewriting,
) -> (Option<Part>, ImageItem, Option<Resampled>) {
let own = header.pixels.filter(|_| image.turn.is_none());
let part = own
.filter(|_| rewriting.crop.keeps_visible_part())
.and_then(|own| visible_part(image, own));
let drawn = part.map_or_else(|| image.clone(), |_| at_clip(image));
let shown = part.map(|[left, top, right, bottom]| (right - left, bottom - top));
let size = shown
.or(own)
.and_then(|pixels| (rewriting.resampling)(pixels, header.palette, &drawn));
(part, drawn, size)
}
fn lazy_rewrite_kind(
format: ImageFormat,
header: Header,
rewriting: Rewriting,
part: Option<Part>,
size: Option<Resampled>,
) -> Option<LazyRewriteKind> {
match (format, rewriting.quality, rewriting.jpeg_share) {
(ImageFormat::Jpeg, Some(quality), _) => Some(LazyRewriteKind::Jpeg { quality }),
(ImageFormat::Png, Some(quality), Some(share)) if header.png_rgb => {
Some(LazyRewriteKind::PngOrJpeg {
quality,
share,
jpeg_sample: rewriting.jpeg_sample,
})
}
(ImageFormat::Png, _, _) if part.is_some() || size.is_some() => Some(LazyRewriteKind::Png),
_ => None,
}
}
fn exceeds_png_rewrite_limit(own: Option<(usize, usize)>) -> bool {
let Some((width, height)) = own else {
return false;
};
let rgba_bytes = (width as u64)
.saturating_mul(height as u64)
.saturating_mul(4);
rgba_bytes > MAX_DECODED_BYTES_TO_WRITE_AGAIN
}
fn rewrite_lazy_image(
image: &mut ImageItem,
handle: ImageRef,
rewriting: Rewriting,
(lazy_headers, lazy_loader): (
&mut HashMap<(ImageId, ImageFormat), Header>,
&Arc<LazyRewritingLoader>,
),
warnings: &mut Warnings,
) {
let format = image.image.format;
let header = *lazy_headers
.entry((handle.id(), format))
.or_insert_with(|| Header::of_lazy(&handle, format));
let (part, drawn, size) = rewrite_geometry(image, header, rewriting);
let Some(kind) = lazy_rewrite_kind(format, header, rewriting, part, size) else {
return;
};
let cannot_rewrite = match format {
ImageFormat::Jpeg => !header.jpeg_rewritable,
ImageFormat::Png => exceeds_png_rewrite_limit(header.pixels),
_ => false,
};
if cannot_rewrite {
warnings.push(Warning::PictureNotWrittenAgain { format });
return;
}
if part.is_some() {
*image = drawn;
}
let new_handle = lazy_loader.intern(
(handle.id(), part, size),
LazyRewriteSpec {
source: handle,
format,
part,
size,
kind,
crop: rewriting.crop,
alpha_mix: rewriting.alpha_mix,
},
);
image.image.data = ImageData::Lazy(new_handle);
}
fn rewrite_inline_image(
image: &mut ImageItem,
data: &Arc<[u8]>,
rewriting: Rewriting,
(files, written): (&mut Files, &mut HashMap<Key, Option<Written>>),
warnings: &mut Warnings,
) {
let format = image.image.format;
let file = files.number(data);
let header = files.header(file, data, format);
let (part, drawn, size) = rewrite_geometry(image, header, rewriting);
let key = (file, part, size);
let again = match (format, rewriting.quality, rewriting.jpeg_share) {
(ImageFormat::Jpeg, Some(quality), _) => written.entry(key).or_insert_with(|| {
jpeg_again(data, (part, size), quality, rewriting.crop)
.map(|file| (file, ImageFormat::Jpeg))
}),
(ImageFormat::Png, Some(quality), Some(share)) if header.png_rgb => written
.entry(key)
.or_insert_with(|| png_or_jpeg(data, (part, size), (quality, share), rewriting)),
(ImageFormat::Png, _, _) if part.is_some() || size.is_some() => {
written.entry(key).or_insert_with(|| {
png_again(data, (part, size), rewriting.alpha_mix, rewriting.crop)
.map(|file| (file, ImageFormat::Png))
})
}
_ => return,
};
let Some((rewritten, out_format)) = again else {
warnings.push(Warning::PictureNotWrittenAgain { format });
return;
};
let (rewritten, out_format) = (Arc::clone(rewritten), *out_format);
if part.is_some() {
*image = drawn;
}
image.image.data = ImageData::Inline(rewritten);
image.image.format = out_format;
}
fn page_images(items: &mut [Item]) -> Vec<&mut ImageItem> {
let mut found = Vec::new();
for item in items {
match item {
Item::Image(image) => found.push(image),
Item::Group(group) if group.places == GroupPlaces::Page => {
found.extend(page_images(&mut group.items));
}
Item::Glyphs(_)
| Item::Rect(_)
| Item::Path(_)
| Item::Gradient(_)
| Item::Group(_) => {}
}
}
found
}
fn visible_part(image: &ImageItem, own: (usize, usize)) -> Option<Part> {
let (rect, clip) = rect_and_clip(image)?;
edges_of(rect, clip, own)
}
fn rect_and_clip(image: &ImageItem) -> Option<([i64; 4], [i64; 4])> {
let clip = image.shown()?;
let edges = |x: i64, y: i64, width: i64, height: i64| {
Some([x, y, x.checked_add(width)?, y.checked_add(height)?])
};
let rect = edges(
image.x.units(),
image.y.units(),
image.width.units(),
image.height.units(),
)?;
let clip = edges(
clip.x.units(),
clip.y.units(),
clip.width.units(),
clip.height.units(),
)?;
Some((rect, clip))
}
fn edges_of(rect: [i64; 4], clip: [i64; 4], own: (usize, usize)) -> Option<Part> {
let side = |start: i64, end: i64, from: i64, to: i64, count: usize| {
let [start, end, from, to] = [start, end, from, to].map(i128::from);
let (count, length) = (i128::try_from(count).ok()?, to - from);
(length > 0).then_some(())?;
let pixels = |offset: i128| div_round_i128(offset * count, length);
let first = pixels(start - from);
let last = first + pixels(end - start);
let inside = first >= 0 && first < last && last <= count;
inside.then_some((usize::try_from(first).ok()?, usize::try_from(last).ok()?))
};
let [x0, y0, x1, y1] = rect;
let (left, right) = side(clip[0], clip[2], x0, x1, own.0)?;
let (top, bottom) = side(clip[1], clip[3], y0, y1, own.1)?;
Some([left, top, right, bottom])
}
fn at_clip(image: &ImageItem) -> ImageItem {
let mut drawn = image.clone();
if let Some(clip) = image.shown() {
(drawn.x, drawn.y, drawn.width, drawn.height) = (clip.x, clip.y, clip.width, clip.height);
drawn.clip = None;
}
drawn
}
fn cut(samples: &[u8], own: (usize, usize), channels: usize, part: Part) -> Option<Vec<u8>> {
let [left, top, right, bottom] = part;
(right <= own.0 && bottom <= own.1 && left < right && top < bottom).then_some(())?;
let row = own.0.checked_mul(channels)?;
let mut out = Vec::with_capacity((right - left) * (bottom - top) * channels);
for y in top..bottom {
let start = y * row + left * channels;
out.extend_from_slice(samples.get(start..start + (right - left) * channels)?);
}
Some(out)
}
fn jpeg_again(
data: &[u8],
(part, size): (Option<Part>, Option<Resampled>),
quality: JpegQuality,
crop: PictureCrop,
) -> Option<Arc<[u8]>> {
let samples = f_office_jpeg::decode(data, MAX_DECODED_BYTES).ok()?;
let channels = samples.channels();
let own = (samples.width(), samples.height());
let picture = (samples.into_data(), own, channels.count());
let (own, values) = part_resampled(picture, (part, size), (crop, AlphaMix::Plain))?;
let samples = f_office_jpeg::Samples::new(own, channels, values).ok()?;
f_office_jpeg::encode(&samples, quality.get())
.ok()
.map(Into::into)
}
type Written = (Arc<[u8]>, ImageFormat);
const RGB_TYPES: [u8; 2] = [2, 6];
const FLATE_LEVEL: u32 = 6;
fn png_or_jpeg(
data: &Arc<[u8]>,
(part, size): (Option<Part>, Option<Resampled>),
(quality, share): (JpegQuality, JpegShare),
rewriting: Rewriting,
) -> Option<Written> {
let lossless = || {
if part.is_none() && size.is_none() {
return Some((Arc::clone(data), ImageFormat::Png));
}
png_again(data, (part, size), rewriting.alpha_mix, rewriting.crop)
.map(|file| (file, ImageFormat::Png))
};
let Ok(picture) =
f_office_paint::decode_file(data, ImageFormat::Png, MAX_DECODED_BYTES_TO_WRITE_AGAIN)
else {
return lossless();
};
if picture.color().has_alpha() && picture.to_rgba8().pixels().any(|pixel| pixel.0[3] < 255) {
return lossless();
}
let (Ok(width), Ok(height)) = (
usize::try_from(picture.width()),
usize::try_from(picture.height()),
) else {
return lossless();
};
let pixels = picture.to_rgb8().into_raw();
let (shown, color) = part_resampled(
(pixels, (width, height), 3),
(part, size),
(rewriting.crop, AlphaMix::Plain),
)?;
let flate = flate_size(&color)?;
let second = match rewriting.jpeg_sample {
Some(sample) => sample.takes(sample_size(&color, shown)?, shown.1, (flate, color.len())),
None => true,
};
let samples = f_office_jpeg::Samples::new(shown, f_office_jpeg::Channels::Rgb, color).ok()?;
let jpeg = f_office_jpeg::encode(&samples, quality.get()).ok()?;
if share.takes(jpeg.len(), flate) && second {
return Some((jpeg.into(), ImageFormat::Jpeg));
}
lossless()
}
fn flate_size(bytes: &[u8]) -> Option<usize> {
let mut flate =
flate2::write::ZlibEncoder::new(Vec::new(), flate2::Compression::new(FLATE_LEVEL));
std::io::Write::write_all(&mut flate, bytes).ok()?;
flate.finish().ok().map(|stream| stream.len())
}
fn sample_size(color: &[u8], (width, height): (usize, usize)) -> Option<usize> {
let row = width.checked_mul(3)?;
JpegSample::strips(height).try_fold(0_usize, |sum, rows| {
let strip = color.get(rows.start.checked_mul(row)?..rows.end.checked_mul(row)?)?;
sum.checked_add(flate_size(strip)?)
})
}
fn png_again(
data: &[u8],
(part, size): (Option<Part>, Option<Resampled>),
alpha_mix: AlphaMix,
crop: PictureCrop,
) -> Option<Arc<[u8]>> {
let picture =
f_office_paint::decode_file(data, ImageFormat::Png, MAX_DECODED_BYTES_TO_WRITE_AGAIN)
.ok()?;
let (pixels, channels, color) = if picture.color().has_alpha() {
(
picture.to_rgba8().into_raw(),
4,
image::ExtendedColorType::Rgba8,
)
} else {
(
picture.to_rgb8().into_raw(),
3,
image::ExtendedColorType::Rgb8,
)
};
let own = (
usize::try_from(picture.width()).ok()?,
usize::try_from(picture.height()).ok()?,
);
let (size, small) = part_resampled((pixels, own, channels), (part, size), (crop, alpha_mix))?;
let mut file = Vec::new();
image::ImageEncoder::write_image(
image::codecs::png::PngEncoder::new(&mut file),
&small,
u32::try_from(size.0).ok()?,
u32::try_from(size.1).ok()?,
color,
)
.ok()?;
Some(file.into())
}
fn part_resampled(
(pixels, own, channels): (Vec<u8>, (usize, usize), usize),
(part, wanted): (Option<Part>, Option<Resampled>),
(crop, alpha_mix): (PictureCrop, AlphaMix),
) -> Option<((usize, usize), Vec<u8>)> {
let Some(part) = part else {
return Some(resampled_mix((pixels, own, channels), wanted, alpha_mix));
};
let [left, top, right, bottom] = part;
let shown = (right.saturating_sub(left), bottom.saturating_sub(top));
if let Some((size, Resampler::Filter(limit))) = wanted
&& crop == PictureCrop::VisiblePartAtScale
&& size != shown
&& !limit.takes_linear(shown)
{
(right <= own.0 && bottom <= own.1 && left < right && top < bottom).then_some(())?;
let at_scale =
|samples: &[u8]| resample::resample_part_at_scale(samples, own, channels, part, size);
return Some((size, mixed(pixels, channels, alpha_mix, at_scale)));
}
let pixels = cut(&pixels, own, channels, part)?;
Some(resampled_mix((pixels, shown, channels), wanted, alpha_mix))
}
fn resampled_mix(
(pixels, own, channels): (Vec<u8>, (usize, usize), usize),
wanted: Option<Resampled>,
alpha_mix: AlphaMix,
) -> ((usize, usize), Vec<u8>) {
let Some((size, resampler)) = wanted.filter(|(size, _)| *size != own) else {
return (own, pixels);
};
let by_filter = |samples: &[u8]| resample::resample_by(resampler, samples, own, channels, size);
(size, mixed(pixels, channels, alpha_mix, by_filter))
}
fn mixed(
pixels: Vec<u8>,
channels: usize,
alpha_mix: AlphaMix,
resample: impl Fn(&[u8]) -> Vec<u8>,
) -> Vec<u8> {
if channels == 4 && alpha_mix == AlphaMix::Weighted {
divided_by_alpha(resample(&premultiplied(pixels)))
} else {
resample(&pixels)
}
}
fn premultiplied(mut samples: Vec<u8>) -> Vec<u8> {
for [red, green, blue, alpha] in samples.as_chunks_mut::<4>().0 {
let alpha = u32::from(*alpha);
for color in [red, green, blue] {
*color = weighted_level(u32::from(*color) * alpha);
}
}
samples
}
fn weighted_level(product: u32) -> u8 {
let (whole, rest) = (product / 255, product % 255);
let level = if rest * 2 > 255 { whole + 1 } else { whole };
u8::try_from(level).unwrap_or(u8::MAX)
}
fn divided_by_alpha(mut samples: Vec<u8>) -> Vec<u8> {
for [red, green, blue, alpha] in samples.as_chunks_mut::<4>().0 {
let alpha = u32::from(*alpha);
for color in [red, green, blue] {
*color = if alpha == 0 {
0
} else {
let value = (u32::from(*color) * 255 * 2 + alpha) / (alpha * 2);
u8::try_from(value.min(255)).unwrap_or(u8::MAX)
};
}
}
samples
}
#[cfg(test)]
mod tests;