use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::sync::Arc;
use f_office_paint::{
AlphaMix, DisplayList, GroupPlaces, ImageFormat, ImageItem, Item, JpegQuality, JpegSample,
JpegShare, MAX_DECODED_BYTES, MAX_DECODED_BYTES_TO_WRITE_AGAIN, PaletteClass, PictureCrop,
Resampler,
};
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_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)>,
palette: Option<PaletteClass>,
}
impl Header {
fn of(data: &[u8], format: ImageFormat) -> Self {
match format {
ImageFormat::Jpeg => Self {
pixels: jpeg_header(data).map(|header| header.pixels),
palette: None,
},
ImageFormat::Png => Self {
pixels: png_header(data).map(|header| header.pixels),
palette: png_palette_class(data),
},
_ => Self {
pixels: None,
palette: None,
},
}
}
}
#[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 written: HashMap<Key, Option<Written>> = HashMap::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) {
let (data, format) = (&image.image.data, image.image.format);
let file = files.number(data);
let header = files.header(file, data, format);
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));
let key = (file, part, size);
let data = &image.image.data;
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 png_color_type(data).is_some_and(|kind| RGB_TYPES.contains(&kind)) =>
{
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))
})
}
_ => continue,
};
let Some((data, format)) = again else {
warnings.push(Warning::PictureNotWrittenAgain { format });
continue;
};
let (data, format) = (Arc::clone(data), *format);
if part.is_some() {
*image = drawn;
}
image.image.data = data;
image.image.format = format;
}
items
}));
}
DisplayList::new(pages)
}
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;