247 lines
9.1 KiB
Rust
247 lines
9.1 KiB
Rust
//! Compress presets (Day 2): images are downsampled to the preset's resolution and re-encoded as JPEG, every stream
|
||
//! is Flate-compressed, unreferenced objects are dropped and the file is written with object streams. Text, fonts,
|
||
//! vector content and the page structure are not touched, so all text stays extractable.
|
||
//!
|
||
//! "Resolution" needs no content-stream analysis: an image is never shown larger than the largest page, so its
|
||
//! pixel size is capped at (largest page side in inches × the preset's dpi). Images Pictor cannot decode safely
|
||
//! (JPEG 2000, CCITT, JBIG2, indexed or 16-bit colour, masks) are left as they are. Fonts are not subset (a gap,
|
||
//! recorded in docs/02_v1-1.md of the app).
|
||
use crate::{PdfError, lopdf_load};
|
||
use image::{DynamicImage, GenericImageView};
|
||
use lopdf::{Dictionary, Document, Object, Stream};
|
||
use serde::{Deserialize, Serialize};
|
||
|
||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||
#[serde(rename_all = "snake_case")]
|
||
pub enum CompressPreset {
|
||
/// Small enough to attach to an e-mail: target 5 MB or less.
|
||
Email,
|
||
/// For the web and the screen.
|
||
Web,
|
||
/// Good enough to print.
|
||
Print,
|
||
}
|
||
|
||
/// The E-mail preset's target.
|
||
pub const EMAIL_TARGET: usize = 5 << 20;
|
||
|
||
#[derive(Debug, Clone)]
|
||
pub struct Compressed {
|
||
pub bytes: Vec<u8>,
|
||
pub before: usize,
|
||
pub after: usize,
|
||
pub images_changed: usize,
|
||
/// Plain sentences (for example: the E-mail target could not be reached).
|
||
pub warnings: Vec<String>,
|
||
}
|
||
|
||
struct Step {
|
||
dpi: f32,
|
||
quality: u8,
|
||
}
|
||
|
||
fn steps(preset: CompressPreset) -> &'static [Step] {
|
||
match preset {
|
||
CompressPreset::Email => {
|
||
&[Step { dpi: 120.0, quality: 62 }, Step { dpi: 96.0, quality: 55 }, Step { dpi: 72.0, quality: 50 }]
|
||
}
|
||
CompressPreset::Web => &[Step { dpi: 150.0, quality: 72 }],
|
||
CompressPreset::Print => &[Step { dpi: 300.0, quality: 86 }],
|
||
}
|
||
}
|
||
|
||
/// Compresses a document with a preset. A protected document stays protected with the same password.
|
||
pub fn compress(bytes: &[u8], password: Option<&str>, preset: CompressPreset) -> Result<Compressed, PdfError> {
|
||
let mut last = None;
|
||
for (i, step) in steps(preset).iter().enumerate() {
|
||
let r = compress_step(bytes, password, step)?;
|
||
let done = preset != CompressPreset::Email || r.after <= EMAIL_TARGET || i + 1 == steps(preset).len();
|
||
last = Some(r);
|
||
if done {
|
||
break;
|
||
}
|
||
}
|
||
let mut r = last.expect("at least one step");
|
||
if preset == CompressPreset::Email && r.after > EMAIL_TARGET {
|
||
r.warnings.push(format!(
|
||
"Pictor got it down to {:.1} MB; the rest is text, fonts and drawings it does not change.",
|
||
r.after as f64 / 1048576.0
|
||
));
|
||
}
|
||
// Never hand back something bigger than the original.
|
||
if r.after >= r.before {
|
||
r.bytes = bytes.to_vec();
|
||
r.after = r.before;
|
||
r.images_changed = 0;
|
||
r.warnings.push("This PDF is already as small as Pictor can make it.".into());
|
||
}
|
||
Ok(r)
|
||
}
|
||
|
||
fn compress_step(bytes: &[u8], password: Option<&str>, step: &Step) -> Result<Compressed, PdfError> {
|
||
let mut doc = lopdf_load(bytes, password)?;
|
||
let largest_side_in = largest_page_side(&doc) / 72.0;
|
||
let max_px = (largest_side_in * step.dpi).ceil().max(64.0) as u32;
|
||
let ids: Vec<_> = doc.objects.keys().copied().collect();
|
||
let masks = soft_masks(&doc);
|
||
let mut changed = 0;
|
||
for id in ids {
|
||
if masks.contains(&id) {
|
||
continue;
|
||
}
|
||
let Some(Object::Stream(s)) = doc.objects.get(&id) else { continue };
|
||
if !is_image(&s.dict) {
|
||
continue;
|
||
}
|
||
let Some(new) = recompress(&doc, s, max_px, step.quality) else { continue };
|
||
if let Some(Object::Stream(s)) = doc.objects.get_mut(&id) {
|
||
*s = new;
|
||
changed += 1;
|
||
}
|
||
}
|
||
doc.compress();
|
||
doc.prune_objects();
|
||
let opts = lopdf::SaveOptions::builder().use_object_streams(true).use_xref_streams(true).build();
|
||
let mut out = Vec::new();
|
||
match password {
|
||
Some(p) => {
|
||
let plain = {
|
||
let mut v = Vec::new();
|
||
doc.save_with_options(&mut v, opts).map_err(|e| PdfError::Write(e.to_string()))?;
|
||
v
|
||
};
|
||
out = crate::protect(&plain, None, p, None)?;
|
||
}
|
||
None => doc.save_with_options(&mut out, opts).map_err(|e| PdfError::Write(e.to_string()))?,
|
||
}
|
||
Ok(Compressed { before: bytes.len(), after: out.len(), bytes: out, images_changed: changed, warnings: Vec::new() })
|
||
}
|
||
|
||
fn largest_page_side(doc: &Document) -> f32 {
|
||
let mut side: f32 = 0.0;
|
||
for page in doc.get_pages().values() {
|
||
let f = crate::edit::lopdf_frame(doc, *page);
|
||
side = side.max(f.crop[2] - f.crop[0]).max(f.crop[3] - f.crop[1]);
|
||
}
|
||
if side <= 0.0 { 842.0 } else { side.min(14_400.0) }
|
||
}
|
||
|
||
/// Images used as another image's soft mask: left alone (their size must stay what their parent expects).
|
||
fn soft_masks(doc: &Document) -> std::collections::HashSet<lopdf::ObjectId> {
|
||
doc.objects
|
||
.values()
|
||
.filter_map(|o| match o {
|
||
Object::Stream(s) => s.dict.get(b"SMask").ok().and_then(|m| m.as_reference().ok()),
|
||
_ => None,
|
||
})
|
||
.collect()
|
||
}
|
||
|
||
fn is_image(d: &Dictionary) -> bool {
|
||
matches!(d.get(b"Subtype"), Ok(Object::Name(n)) if n == b"Image")
|
||
&& !matches!(d.get(b"ImageMask"), Ok(Object::Boolean(true)))
|
||
}
|
||
|
||
fn name_or_first(o: Option<&Object>) -> Option<Vec<u8>> {
|
||
match o? {
|
||
Object::Name(n) => Some(n.clone()),
|
||
Object::Array(a) if a.len() == 1 => a[0].as_name().ok().map(|n| n.to_vec()),
|
||
Object::Array(a) if a.is_empty() => Some(Vec::new()),
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
/// Channels of a colour space Pictor can re-encode as JPEG: DeviceGray, DeviceRGB, or ICCBased with N 1 or 3.
|
||
fn channels(doc: &Document, cs: Option<&Object>) -> Option<u8> {
|
||
let cs = match cs? {
|
||
Object::Reference(r) => doc.get_object(*r).ok()?,
|
||
o => o,
|
||
};
|
||
match cs {
|
||
Object::Name(n) if n == b"DeviceGray" => Some(1),
|
||
Object::Name(n) if n == b"DeviceRGB" => Some(3),
|
||
Object::Array(a) if a.len() == 2 && a[0].as_name().ok() == Some(b"ICCBased") => {
|
||
let s = match &a[1] {
|
||
Object::Reference(r) => doc.get_object(*r).ok()?.as_stream().ok()?,
|
||
_ => return None,
|
||
};
|
||
match s.dict.get(b"N").ok()?.as_i64().ok()? {
|
||
1 => Some(1),
|
||
3 => Some(3),
|
||
_ => None,
|
||
}
|
||
}
|
||
_ => None,
|
||
}
|
||
}
|
||
|
||
fn recompress(doc: &Document, s: &Stream, max_px: u32, quality: u8) -> Option<Stream> {
|
||
let d = &s.dict;
|
||
let w = d.get(b"Width").ok()?.as_i64().ok()? as u32;
|
||
let h = d.get(b"Height").ok()?.as_i64().ok()? as u32;
|
||
if w == 0 || h == 0 || (w as u64) * (h as u64) > 150_000_000 {
|
||
return None;
|
||
}
|
||
if d.get(b"BitsPerComponent").ok().and_then(|b| b.as_i64().ok()) != Some(8) || d.has(b"Decode") {
|
||
return None;
|
||
}
|
||
let n = channels(doc, d.get(b"ColorSpace").ok())?;
|
||
let filter = name_or_first(d.get(b"Filter").ok()).unwrap_or_default();
|
||
let img: DynamicImage = match &filter[..] {
|
||
b"DCTDecode" => {
|
||
let i = image::load_from_memory_with_format(&s.content, image::ImageFormat::Jpeg).ok()?;
|
||
// CMYK JPEGs (Adobe) and odd channel counts are left alone.
|
||
if i.color().channel_count() != n {
|
||
return None;
|
||
}
|
||
i
|
||
}
|
||
b"FlateDecode" | b"" => {
|
||
let raw = if filter.is_empty() {
|
||
s.content.clone()
|
||
} else {
|
||
s.decompressed_content_with_limit(600 << 20).ok()?
|
||
};
|
||
let need = (w as usize) * (h as usize) * n as usize;
|
||
if raw.len() < need {
|
||
return None;
|
||
}
|
||
match n {
|
||
1 => DynamicImage::ImageLuma8(image::GrayImage::from_raw(w, h, raw[..need].to_vec())?),
|
||
_ => DynamicImage::ImageRgb8(image::RgbImage::from_raw(w, h, raw[..need].to_vec())?),
|
||
}
|
||
}
|
||
_ => return None,
|
||
};
|
||
let (iw, ih) = img.dimensions();
|
||
let img = if iw.max(ih) > max_px + max_px / 10 {
|
||
let k = max_px as f32 / iw.max(ih) as f32;
|
||
img.resize_exact(
|
||
((iw as f32 * k).round() as u32).max(1),
|
||
((ih as f32 * k).round() as u32).max(1),
|
||
image::imageops::FilterType::Lanczos3,
|
||
)
|
||
} else {
|
||
img
|
||
};
|
||
let mut jpeg = Vec::new();
|
||
let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, quality);
|
||
match n {
|
||
1 => img.to_luma8().write_with_encoder(enc).ok()?,
|
||
_ => img.to_rgb8().write_with_encoder(enc).ok()?,
|
||
}
|
||
let old = s.content.len();
|
||
if jpeg.len() as f64 > old as f64 * 0.9 {
|
||
return None;
|
||
}
|
||
let mut dict = d.clone();
|
||
dict.set("Width", img.width() as i64);
|
||
dict.set("Height", img.height() as i64);
|
||
dict.set("Filter", "DCTDecode");
|
||
dict.remove(b"DecodeParms");
|
||
dict.remove(b"Length");
|
||
let mut out = Stream::new(dict, jpeg);
|
||
out.allows_compression = false;
|
||
Some(out)
|
||
}
|