mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:42:27 +00:00
* prepress: separate a page in bands, past the 4 MP plate cap `plates_in_bands` finds a page's inks once, then separates it in row bands of at most MAX_PLATE_PIXELS each, rendering every band through craft-pdf raster's size/offset viewport. A page can now be separated at print resolution with bounded memory: only the renderer's 8192-pixel side limit and a 256 MP per-plate total (MAX_BANDED_PIXELS) lower the resolution. `plates` is unchanged in behaviour: it is the one-band case of the same code. Tests: bands of 7 rows join byte for byte into the whole-page render of an anti-aliased disc under an overprinting spot (fails when the band offset is dropped), and a 40 pt page at 3700 dpi separates at full resolution in bands under the cap (fails when banding uses the plate cap's scale). Refs #838. * prepress: bands pass the renderer's whole-page limits The page's pixel size came from `raster::dimensions` on the whole page, which enforces the renderer's 64 MP and 8192-pixel side limits, so a Letter page past about 830 dpi failed with OutputLimit instead of banding. The size is now computed as the renderer floors it, and only each band's viewport reaches the renderer. Bands are also capped at MAX_SIDE rows, and ink discovery renders within the renderer's limits. A Letter page at 900 dpi now separates in 19 bands at full resolution; across the page the side limit still lowers it, near 960 dpi. Test: a 10 x 2000 pt strip at 600 dpi (16 666 rows) separates in three bands with its black square on the right rows. It fails with either the whole-page dimensions call or the uncapped band height restored. * prepress: check the page before discovery; say what the banded cap bounds The page-size check now runs before ink discovery renders anything. MAX_BANDED_PIXELS bounds pixels, not the number of bands; the doc comment and the README caps table say so. * prepress: count a sub-pixel side as one pixel in the banded cap A side scaled under one pixel still renders one, so a very thin, tall page could pass MAX_BANDED_PIXELS by far. banded_scale now fits the other side alone in that case, and separate() refuses any floored size over the cap before it renders a band. * prepress: keep the banded area scale under the cap after rounding The area scale came from the exact cap, so f32 rounding could floor a page one row past it (17 x 15 058 824 pt at 72 dpi), which then failed with OutputLimit. The same 0.1% margin as the one-pixel branches now applies to the area scale too, with a test on that page. --------- Co-authored-by: KenM76 <KenM76>
607 lines
26 KiB
Rust
607 lines
26 KiB
Rust
//! A PDF page separated into plates, one gray film per ink.
|
||
//!
|
||
//! A plate is the page rendered with hayro-interpret's plate mode
|
||
//! (`InterpreterSettings::plate`): every paint draws its tint of one ink as gray, and a paint
|
||
//! that overprints without naming the ink leaves the film as it is (ISO 32000-2 §8.6.7).
|
||
//! Clipping, anti-aliasing, soft masks, transparency groups and blending stay the renderer's
|
||
//! own. `Separation` and `DeviceN` colorants paint their own plates, DeviceCMYK its four
|
||
//! components, DeviceGray black only, and other process color converts to CMYK through the
|
||
//! printing condition (see [`Conversion`]).
|
||
//!
|
||
//! Ported from PdfCraft #2770 by Guillem Hermida (`crates/render/src/separations.rs` at
|
||
//! 6fcf2a4, MIT OR Apache-2.0), with craft-cms in place of moxcms.
|
||
|
||
use std::collections::HashSet;
|
||
use std::ops::ControlFlow;
|
||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||
use std::sync::{Arc, Mutex};
|
||
|
||
use craft_pdf::interpret::InterpreterSettings;
|
||
use craft_pdf::interpret::color::{CmykSimulation, Ink as PdfInk, InkSinkFn, Plate};
|
||
use craft_pdf::raster::{self, MAX_SIDE, RenderCache};
|
||
use craft_pdf::syntax::Pdf;
|
||
use craft_pdf::syntax::object::dict::keys::{DEST_OUTPUT_PROFILE, OUTPUT_CONDITION, OUTPUT_CONDITION_IDENTIFIER, OUTPUT_INTENTS, S};
|
||
use craft_pdf::syntax::object::{Array, Dict, Name, Stream, String as PdfText};
|
||
use craft_pdf::{OpenError, open_slice};
|
||
|
||
use crate::cms::{CmsConversion, ProfileError, srgb8_to_lab};
|
||
use crate::ink::{Alternate, InkId, InkSet, Spot};
|
||
|
||
/// Spot inks separated per page, after the four process inks. More than any press runs: a
|
||
/// `DeviceN` space has at most 32 colorants, and every plate costs a render and a byte per
|
||
/// pixel. Further spot inks are listed in [`Plates::unseparated`].
|
||
pub const MAX_SPOT_INKS: usize = 32;
|
||
|
||
/// Device pixels per plate (4 MP, 2000 × 2000), so a page with many inks stays within a few
|
||
/// hundred megabytes. The resolution is reduced to fit; [`Plates::dpi`] says what was used.
|
||
pub const MAX_PLATE_PIXELS: f32 = 4.0e6;
|
||
|
||
/// Pixels per plate of a page separated in bands (256 MP, 16000 × 16000). It bounds the memory a
|
||
/// page's bands add up to; a long page reaches it, while across a Letter or A4 page the side limit
|
||
/// stops near 960 dpi first. The resolution is reduced to fit. It does not bound the band count: a
|
||
/// page a few points wide and very tall still makes one band per 8192 rows.
|
||
pub const MAX_BANDED_PIXELS: f32 = 2.56e8;
|
||
|
||
/// The resolution, in pixels per point, inks are discovered at before the plates render.
|
||
const DISCOVERY_SCALE: f32 = 0.1;
|
||
|
||
/// Spot ink names recorded while discovering, past which further names are dropped.
|
||
const MAX_LISTED_SPOTS: usize = MAX_SPOT_INKS * 4;
|
||
|
||
/// Output intents looked at per page: each can cost a profile's decoding and parsing.
|
||
const MAX_OUTPUT_INTENTS: usize = 16;
|
||
|
||
/// Decoding limit for an output intent's profile.
|
||
const MAX_PROFILE_BYTES: usize = 16 << 20;
|
||
|
||
/// The longest output condition kept, in characters.
|
||
const MAX_CONDITION: usize = 160;
|
||
|
||
/// The printing condition process color converts to when the page has no usable output
|
||
/// intent.
|
||
#[derive(Clone, Debug, Default)]
|
||
#[non_exhaustive]
|
||
pub enum Fallback {
|
||
/// craft-cms's Coated FOGRA39 profile.
|
||
#[default]
|
||
Fogra39,
|
||
/// The caller's CMYK ICC profile.
|
||
Profile(Arc<[u8]>),
|
||
/// The ISO 32000-2 §10.4.2.4 device formulas, black generation and undercolor removal the
|
||
/// identity: neutral RGB goes to black alone, ICCBased CMYK separates as it is.
|
||
DeviceFormulas,
|
||
}
|
||
|
||
/// How [`plates`] separates.
|
||
#[derive(Clone, Debug)]
|
||
pub struct Options {
|
||
/// Honor `OP`, `op` and `OPM` as a separating device does. Without it every paint knocks
|
||
/// out what is under it.
|
||
pub overprint: bool,
|
||
/// The printing condition when the page has no output intent with a usable CMYK profile.
|
||
pub fallback: Fallback,
|
||
}
|
||
|
||
impl Default for Options {
|
||
fn default() -> Self {
|
||
Self { overprint: true, fallback: Fallback::default() }
|
||
}
|
||
}
|
||
|
||
/// How process color that isn't CMYK already became CMYK.
|
||
#[derive(Clone, Debug, PartialEq)]
|
||
#[non_exhaustive]
|
||
pub enum Conversion {
|
||
/// Through the CMYK profile of the page's or document's output intent (ISO 32000-2
|
||
/// §14.11.5).
|
||
OutputIntent {
|
||
/// The profile's description, else the intent's output condition.
|
||
profile: String,
|
||
/// The intent's `/OutputConditionIdentifier`, such as `FOGRA39`.
|
||
condition: Option<String>,
|
||
},
|
||
/// Through [`Fallback::Fogra39`] or [`Fallback::Profile`]; the profile's description.
|
||
Fallback { profile: String },
|
||
/// By [`Fallback::DeviceFormulas`].
|
||
DeviceFormulas,
|
||
}
|
||
|
||
/// A page separated into plates.
|
||
#[derive(Clone, Debug)]
|
||
pub struct Plates {
|
||
/// The process inks, then the spot inks the page paints, in the order first painted. Spots
|
||
/// carry a Lab alternate measured from their sRGB appearance at 100%.
|
||
pub inks: InkSet,
|
||
/// Spot inks past [`MAX_SPOT_INKS`]: listed, not separated.
|
||
pub unseparated: Vec<String>,
|
||
pub width: u32,
|
||
pub height: u32,
|
||
/// The resolution the plates rendered at, after [`MAX_PLATE_PIXELS`].
|
||
pub dpi: f32,
|
||
pub conversion: Conversion,
|
||
/// One plane per ink, in [`InkSet::iter`] order: the tint per pixel, row-major, 0 for no
|
||
/// ink and 255 for 100%.
|
||
pub planes: Vec<Vec<u8>>,
|
||
}
|
||
|
||
impl Plates {
|
||
/// Ink `id`'s plane.
|
||
pub fn plane(&self, id: InkId) -> Option<&[u8]> {
|
||
self.planes.get(id.index()).map(Vec::as_slice)
|
||
}
|
||
|
||
/// Ink `id`'s tint at pixel (`x`, `y`), 0–255.
|
||
pub fn tint(&self, id: InkId, x: u32, y: u32) -> Option<u8> {
|
||
self.plane(id)?.get(self.index_of(x, y)?).copied()
|
||
}
|
||
}
|
||
|
||
#[derive(Debug, thiserror::Error)]
|
||
#[non_exhaustive]
|
||
pub enum Error {
|
||
#[error(transparent)]
|
||
Open(#[from] OpenError),
|
||
#[error("page {0} does not exist")]
|
||
NoPage(usize),
|
||
#[error("the resolution must be positive and finite")]
|
||
InvalidDpi,
|
||
#[error("the fallback profile can't be a printing condition: {0}")]
|
||
Profile(#[from] ProfileError),
|
||
/// After a [`raster::Error::BackendPanic`] the document is dropped; nothing else is kept.
|
||
#[error(transparent)]
|
||
Render(#[from] raster::Error),
|
||
}
|
||
|
||
/// Separates page `page` (from 0) of `pdf` at `dpi`, reduced to fit [`MAX_PLATE_PIXELS`] and
|
||
/// the renderer's side limit: one plate per ink, the four process inks and up to
|
||
/// [`MAX_SPOT_INKS`] spot inks the page paints. Spot inks only soft masks use are left out
|
||
/// (masks don't print). [`plates_in_bands`] separates at higher resolutions. Never panics.
|
||
pub fn plates(pdf: &[u8], page: usize, dpi: f32, opts: &Options) -> Result<Plates, Error> {
|
||
let mut whole = None;
|
||
// One band of the whole page: `plate_scale` keeps it within `MAX_PLATE_PIXELS`.
|
||
separate(pdf, page, dpi, opts, plate_scale, Some(u32::MAX), &mut |band: Band| {
|
||
whole = Some(band.plates);
|
||
ControlFlow::Break(())
|
||
})?;
|
||
whole.ok_or(Error::Render(raster::Error::OutputLimit))
|
||
}
|
||
|
||
/// Rows of a page's plates, from [`plates_in_bands`].
|
||
#[derive(Clone, Debug)]
|
||
pub struct Band {
|
||
/// The band's first row on the page, from the top.
|
||
pub top: u32,
|
||
/// The page's height in pixels. The band's own height is the plates' height.
|
||
pub page_height: u32,
|
||
/// The band's plates: as wide as the page, `height` rows from `top`. Every band has the
|
||
/// same inks, in the same order.
|
||
pub plates: Plates,
|
||
}
|
||
|
||
/// Separates page `page` (from 0) of `pdf` at `dpi` as [`plates`] does, in bands from the top
|
||
/// down, each at most [`MAX_PLATE_PIXELS`]. The resolution is reduced only to fit the
|
||
/// renderer's side limit across the page (`MAX_SIDE`, 8192 pixels) and [`MAX_BANDED_PIXELS`]
|
||
/// in all; [`Plates::dpi`] says what was used. The page's inks are found once, so every band has the same ones.
|
||
///
|
||
/// `each` gets the bands in order and returns [`ControlFlow::Break`] to stop. Each band renders
|
||
/// the page again, clipped to its rows. Never panics.
|
||
pub fn plates_in_bands(pdf: &[u8], page: usize, dpi: f32, opts: &Options, mut each: impl FnMut(Band) -> ControlFlow<()>) -> Result<(), Error> {
|
||
separate(pdf, page, dpi, opts, banded_scale, None, &mut each)
|
||
}
|
||
|
||
/// Separates in bands of `rows` rows, else as many as fit [`MAX_PLATE_PIXELS`], at `scale_of`'s
|
||
/// scale.
|
||
fn separate(
|
||
pdf: &[u8],
|
||
page: usize,
|
||
dpi: f32,
|
||
opts: &Options,
|
||
scale_of: fn(f32, f32, f32) -> f32,
|
||
rows: Option<u32>,
|
||
each: &mut dyn FnMut(Band) -> ControlFlow<()>,
|
||
) -> Result<(), Error> {
|
||
if !dpi.is_finite() || dpi <= 0.0 {
|
||
return Err(Error::InvalidDpi);
|
||
}
|
||
let doc = open_slice(pdf, None)?;
|
||
let (simulation, conversion) = match catch_unwind(AssertUnwindSafe(|| output_intent(&doc, page))) {
|
||
Ok(Some(found)) => (Some(found.0), found.1),
|
||
Ok(None) | Err(_) => fallback(&opts.fallback)?,
|
||
};
|
||
let pages = doc.pages();
|
||
let p = pages.get(page).ok_or(Error::NoPage(page))?;
|
||
let (w, h) = p.render_dimensions();
|
||
if !w.is_finite() || !h.is_finite() || w <= 0.0 || h <= 0.0 {
|
||
return Err(Error::Render(raster::Error::InvalidPage));
|
||
}
|
||
let scale = scale_of(w, h, dpi / 72.0);
|
||
let cache = RenderCache::new();
|
||
// Inks are found on a small render of the whole page, within the renderer's limits.
|
||
let (inks, separated, unseparated) = discover(p, &cache, plate_scale(w, h, DISCOVERY_SCALE.min(scale)))?;
|
||
// The page's size in pixels, as the renderer floors it. Only each band's viewport goes to
|
||
// the renderer, so the page itself may pass the renderer's own size limits.
|
||
let [width, page_height] = [w, h].map(|side| (side * scale).floor().max(1.0) as u32);
|
||
// A band is within the plate cap and, like any render, the renderer's side limit.
|
||
let fit = (MAX_PLATE_PIXELS / width as f32).floor().clamp(1.0, MAX_SIDE as f32) as u32;
|
||
if u64::from(width) * u64::from(page_height) > MAX_BANDED_PIXELS as u64 {
|
||
return Err(Error::Render(raster::Error::OutputLimit));
|
||
}
|
||
let rows = rows.unwrap_or(fit).clamp(1, page_height);
|
||
let mut top = 0;
|
||
while top < page_height {
|
||
let height = rows.min(page_height - top);
|
||
let mut planes = Vec::with_capacity(separated.len());
|
||
for ink in &separated {
|
||
let plate = Plate { ink: ink.clone(), overprint: opts.overprint, simulation: simulation.clone(), spots_as_process: false };
|
||
let settings = InterpreterSettings { plate: Some(plate), ..Default::default() };
|
||
let viewport = raster::Options { size: Some([width, height]), offset: [0.0, top as f32], ..film(scale) };
|
||
let film = raster::render(p, &cache, &settings, &viewport)?;
|
||
// The film is gray on white: its red channel is the paper left uncovered.
|
||
planes.push(film.bytes().as_chunks::<4>().0.iter().map(|[red, ..]| 255 - red).collect());
|
||
}
|
||
let plates =
|
||
Plates { inks: inks.clone(), unseparated: unseparated.clone(), width, height, dpi: scale * 72.0, conversion: conversion.clone(), planes };
|
||
if each(Band { top, page_height, plates }).is_break() {
|
||
break;
|
||
}
|
||
top += height;
|
||
}
|
||
Ok(())
|
||
}
|
||
|
||
/// The inks page `p` paints, found at `scale`, a low resolution: the process inks, then up to
|
||
/// [`MAX_SPOT_INKS`] spots as the [`InkSet`], the renderer's inks to separate in the same
|
||
/// order, and the names of spots left unseparated.
|
||
fn discover<'a>(p: &'a craft_pdf::syntax::page::Page<'a>, cache: &RenderCache<'a>, scale: f32) -> Result<(InkSet, Vec<PdfInk>, Vec<String>), Error> {
|
||
let log = Arc::new(Mutex::new(SpotLog::default()));
|
||
let settings = InterpreterSettings { ink_sink: Some(spot_sink(&log)), ..Default::default() };
|
||
raster::render(p, cache, &settings, &film(scale))?;
|
||
let spots = std::mem::take(&mut log.lock().unwrap_or_else(|poisoned| poisoned.into_inner()).order);
|
||
|
||
let mut inks = InkSet::new();
|
||
let mut separated: Vec<PdfInk> = PdfInk::PROCESS.to_vec();
|
||
let mut unseparated = Vec::new();
|
||
for (ink, swatch) in spots {
|
||
if separated.len() >= 4 + MAX_SPOT_INKS {
|
||
unseparated.push(ink.name().to_string());
|
||
continue;
|
||
}
|
||
let alternate = Alternate::Lab(srgb8_to_lab(swatch).unwrap_or([0.0; 3]));
|
||
let spot = Spot { name: ink.name().to_string(), alternate, solidity: None };
|
||
// hayro hands over names with their `#xx` escapes decoded, so `#` here is a literal
|
||
// character. Two names that read the same after lossy UTF-8 decoding share one plate.
|
||
match inks.add_decoded(spot) {
|
||
Some(id) if id.index() == separated.len() => separated.push(ink),
|
||
_ => unseparated.push(ink.name().to_string()),
|
||
}
|
||
}
|
||
Ok((inks, separated, unseparated))
|
||
}
|
||
|
||
/// Raster options for a gray film at `scale`. The plate's film must keep its tints: no color
|
||
/// replacement.
|
||
fn film(scale: f32) -> raster::Options {
|
||
raster::Options { scale: [scale, scale], background: [255; 4], color_replacement: None, ..Default::default() }
|
||
}
|
||
|
||
/// The scale a `w` × `h` pt page separates at in bands: `scale`, within the renderer's side
|
||
/// limit across the page and [`MAX_BANDED_PIXELS`]. Down the page there is no side limit.
|
||
fn banded_scale(w: f32, h: f32, scale: f32) -> f32 {
|
||
let (w, h) = (w.max(1.0), h.max(1.0));
|
||
// The margin keeps the floored size under the cap despite f32 rounding.
|
||
let cap = MAX_BANDED_PIXELS * 0.999;
|
||
let by_area = (cap / (w * h)).sqrt();
|
||
let mut s = scale.min(by_area).min(MAX_SIDE as f32 / w);
|
||
// A side scaled under one pixel still renders one, so the other side alone must fit.
|
||
if w * s < 1.0 {
|
||
s = s.min(cap / h);
|
||
}
|
||
if h * s < 1.0 {
|
||
s = s.min(cap / w);
|
||
}
|
||
if s.is_finite() && s > 0.0 { s } else { f32::MIN_POSITIVE }
|
||
}
|
||
|
||
/// The scale a `w` × `h` pt page separates at: `scale`, within [`MAX_PLATE_PIXELS`] and
|
||
/// [`MAX_SIDE`].
|
||
fn plate_scale(w: f32, h: f32, scale: f32) -> f32 {
|
||
let (w, h) = (w.max(1.0), h.max(1.0));
|
||
let by_area = (MAX_PLATE_PIXELS / (w * h)).sqrt();
|
||
let by_side = MAX_SIDE as f32 / w.max(h);
|
||
let s = scale.min(by_area).min(by_side);
|
||
if s.is_finite() && s > 0.0 { s } else { f32::MIN_POSITIVE }
|
||
}
|
||
|
||
pub(crate) fn fallback(fallback: &Fallback) -> Result<(Option<CmykSimulation>, Conversion), Error> {
|
||
let (conversion, icc): (CmsConversion, &[u8]) = match fallback {
|
||
Fallback::DeviceFormulas => return Ok((None, Conversion::DeviceFormulas)),
|
||
Fallback::Fogra39 => (CmsConversion::fogra39(), craft_cms::builtin::COATED_FOGRA39_ICC),
|
||
Fallback::Profile(icc) => (CmsConversion::new(icc)?, icc),
|
||
};
|
||
let simulation = conversion.simulation(icc);
|
||
let profile = simulation.description().unwrap_or("unnamed CMYK profile").to_string();
|
||
Ok((Some(simulation), Conversion::Fallback { profile }))
|
||
}
|
||
|
||
/// Spot inks reported while a page renders, in the order first painted, each with its sRGB
|
||
/// appearance at 100%.
|
||
#[derive(Default)]
|
||
struct SpotLog {
|
||
order: Vec<(PdfInk, [u8; 3])>,
|
||
seen: HashSet<PdfInk>,
|
||
}
|
||
|
||
fn spot_sink(log: &Arc<Mutex<SpotLog>>) -> InkSinkFn {
|
||
let log = log.clone();
|
||
Arc::new(move |ink: &PdfInk, appearance: &dyn Fn(f32) -> [u8; 3]| {
|
||
let mut log = log.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||
if log.seen.contains(ink) || log.order.len() >= MAX_LISTED_SPOTS {
|
||
return;
|
||
}
|
||
log.seen.insert(ink.clone());
|
||
log.order.push((ink.clone(), appearance(1.0)));
|
||
})
|
||
}
|
||
|
||
/// A text string entry of `dict`, without control characters and at most [`MAX_CONDITION`]
|
||
/// characters long; `None` when missing or blank.
|
||
fn text_entry(dict: &Dict<'_>, key: &[u8]) -> Option<String> {
|
||
let s = dict.get::<PdfText<'_>>(key)?;
|
||
let text: String = pdf_text(s.as_bytes()).chars().filter(|c| !c.is_control()).take(MAX_CONDITION).collect();
|
||
let text = text.trim();
|
||
(!text.is_empty()).then(|| text.to_string())
|
||
}
|
||
|
||
/// A PDF text string (ISO 32000-2 §7.9.2.2): UTF-16BE or UTF-8 after its byte order mark, else
|
||
/// PDFDocEncoding, read here as Latin-1 (they differ only in rarely used punctuation).
|
||
pub(crate) fn pdf_text(bytes: &[u8]) -> String {
|
||
if let Some(utf16) = bytes.strip_prefix(&[0xFE, 0xFF]) {
|
||
let units: Vec<u16> = utf16.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect();
|
||
return String::from_utf16_lossy(&units);
|
||
}
|
||
if let Some(utf8) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
|
||
return String::from_utf8_lossy(utf8).into_owned();
|
||
}
|
||
bytes.iter().map(|b| char::from(*b)).collect()
|
||
}
|
||
|
||
/// The printing condition of page `page` (ISO 32000-2 §14.11.5): of the page's own
|
||
/// `/OutputIntents` (PDF 2.0), else the catalog's, the first whose `/DestOutputProfile` is a
|
||
/// CMYK profile craft-cms converts into, a `GTS_PDFX` intent before the others.
|
||
pub(crate) fn output_intent(pdf: &Pdf, page: usize) -> Option<(CmykSimulation, Conversion)> {
|
||
output_intents(pdf, page).iter().find_map(|intent| {
|
||
let icc = intent.get::<Stream<'_>>(DEST_OUTPUT_PROFILE)?.decoded_within(MAX_PROFILE_BYTES).ok()?;
|
||
let simulation = CmsConversion::new(&icc).ok()?.simulation(&icc);
|
||
let condition = text_entry(intent, OUTPUT_CONDITION_IDENTIFIER);
|
||
let profile = simulation
|
||
.description()
|
||
.map(str::to_string)
|
||
.or_else(|| text_entry(intent, OUTPUT_CONDITION))
|
||
.or_else(|| condition.clone())
|
||
.unwrap_or_else(|| "unnamed CMYK profile".to_string());
|
||
Some((simulation, Conversion::OutputIntent { profile, condition }))
|
||
})
|
||
}
|
||
|
||
/// The output intent [`output_intent`] picks, as written in the PDF.
|
||
#[cfg(feature = "flatten")]
|
||
pub(crate) struct IntentProfile {
|
||
pub icc: Vec<u8>,
|
||
pub identifier: Option<String>,
|
||
pub condition: Option<String>,
|
||
pub registry_name: Option<String>,
|
||
pub info: Option<String>,
|
||
}
|
||
|
||
/// The output intent [`output_intent`] picks: its profile bytes and entries, to write the same
|
||
/// intent again.
|
||
#[cfg(feature = "flatten")]
|
||
pub(crate) fn output_intent_profile(pdf: &Pdf, page: usize) -> Option<IntentProfile> {
|
||
output_intents(pdf, page).iter().find_map(|intent| {
|
||
let icc = intent.get::<Stream<'_>>(DEST_OUTPUT_PROFILE)?.decoded_within(MAX_PROFILE_BYTES).ok()?;
|
||
if *icc != *craft_cms::builtin::COATED_FOGRA39_ICC && CmsConversion::new(&icc).is_err() {
|
||
return None;
|
||
}
|
||
Some(IntentProfile {
|
||
icc: icc.into_owned(),
|
||
identifier: text_entry(intent, OUTPUT_CONDITION_IDENTIFIER),
|
||
condition: text_entry(intent, OUTPUT_CONDITION),
|
||
registry_name: text_entry(intent, b"RegistryName"),
|
||
info: text_entry(intent, b"Info"),
|
||
})
|
||
})
|
||
}
|
||
|
||
/// The page's own `/OutputIntents` (PDF 2.0), else the catalog's, a `GTS_PDFX` intent first.
|
||
fn output_intents(pdf: &Pdf, page: usize) -> Vec<Dict<'_>> {
|
||
fn list<'a>(intents: Option<Array<'a>>) -> Vec<Dict<'a>> {
|
||
intents.iter().flat_map(|a| a.iter::<Dict<'a>>()).take(MAX_OUTPUT_INTENTS).collect()
|
||
}
|
||
let xref = pdf.xref();
|
||
let mut listed = list(pdf.pages().get(page).and_then(|p| p.raw().get::<Array<'_>>(OUTPUT_INTENTS)));
|
||
if listed.is_empty() {
|
||
listed = list(xref.get::<Dict<'_>>(xref.root_id()).and_then(|catalog| catalog.get::<Array<'_>>(OUTPUT_INTENTS)));
|
||
}
|
||
// A stable sort: the PDF/X intent first, the others in their order.
|
||
listed.sort_by_key(|d| d.get::<Name<'_>>(S).is_none_or(|s| s.as_ref() != b"GTS_PDFX"));
|
||
listed
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
/// A 40 × 40 pt page: a black disc with anti-aliased edges, a spot square overprinting it.
|
||
fn disc_and_spot() -> Vec<u8> {
|
||
let content = "0 0 0 1 k 20 4 m 29 4 36 11 36 20 c 36 29 29 36 20 36 c 11 36 4 29 4 20 c 4 11 11 4 20 4 c f /GS0 gs /CS0 cs 0.5 scn 10.3 10.3 19.4 19.4 re f";
|
||
let resources = "/ColorSpace << /CS0 [/Separation /Gold /DeviceCMYK << /FunctionType 2 /Domain [0 1] /C0 [0 0 0 0] /C1 [0 0.3 1 0] /N 1 >>] >> /ExtGState << /GS0 << /op true >> >>";
|
||
let mut out = b"%PDF-1.7
|
||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||
"
|
||
.to_vec();
|
||
out.extend_from_slice(
|
||
b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||
",
|
||
);
|
||
out.extend_from_slice(
|
||
format!(
|
||
"3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 40 40] /Contents 4 0 R /Resources << {resources} >> >> endobj
|
||
"
|
||
)
|
||
.as_bytes(),
|
||
);
|
||
out.extend_from_slice(
|
||
format!(
|
||
"4 0 obj << /Length {} >> stream
|
||
{content}
|
||
endstream endobj
|
||
",
|
||
content.len()
|
||
)
|
||
.as_bytes(),
|
||
);
|
||
out.extend_from_slice(
|
||
b"trailer << /Root 1 0 R >>
|
||
%%EOF",
|
||
);
|
||
out
|
||
}
|
||
|
||
#[test]
|
||
fn bands_join_into_the_page_rendered_whole() {
|
||
let pdf = disc_and_spot();
|
||
let whole = plates(&pdf, 0, 216.0, &Options::default()).unwrap();
|
||
assert_eq!((whole.width, whole.height, whole.planes.len()), (120, 120, 5));
|
||
let mut joined = vec![Vec::new(); 5];
|
||
let mut tops = Vec::new();
|
||
separate(&pdf, 0, 216.0, &Options::default(), plate_scale, Some(7), &mut |band: Band| {
|
||
assert_eq!((band.plates.width, band.page_height, band.plates.inks.len()), (120, 120, 5));
|
||
tops.push((band.top, band.plates.height));
|
||
for (plane, part) in joined.iter_mut().zip(&band.plates.planes) {
|
||
plane.extend_from_slice(part);
|
||
}
|
||
ControlFlow::Continue(())
|
||
})
|
||
.unwrap();
|
||
assert_eq!(tops.len(), 18, "17 bands of 7 rows and one of 1: {tops:?}");
|
||
assert_eq!(tops.last(), Some(&(119, 1)));
|
||
assert!(whole.planes.iter().any(|p| p.iter().any(|t| *t > 0 && *t < 255)), "the disc's edge is anti-aliased");
|
||
assert_eq!(joined, whole.planes, "no seam between bands");
|
||
}
|
||
|
||
#[test]
|
||
fn bands_reach_resolutions_past_the_plate_cap_and_can_stop() {
|
||
let pdf = disc_and_spot();
|
||
// 40 pt at 3700 dpi is 2055 pixels a side: 4.2 MP, past `MAX_PLATE_PIXELS`.
|
||
assert!(plates(&pdf, 0, 3700.0, &Options::default()).unwrap().dpi < 3700.0);
|
||
let mut bands = Vec::new();
|
||
plates_in_bands(&pdf, 0, 3700.0, &Options::default(), |band| {
|
||
let p = &band.plates;
|
||
assert!((p.width * p.height) as f32 <= MAX_PLATE_PIXELS);
|
||
bands.push((band.top, p.height, p.width, p.dpi, band.page_height));
|
||
ControlFlow::Continue(())
|
||
})
|
||
.unwrap();
|
||
let &(_, _, width, dpi, page_height) = bands.first().unwrap();
|
||
assert_eq!((width, page_height), (2055, 2055));
|
||
assert!((dpi - 3700.0).abs() < 0.01);
|
||
assert_eq!(bands.iter().map(|b| b.1).sum::<u32>(), 2055);
|
||
|
||
let mut seen = 0;
|
||
plates_in_bands(&pdf, 0, 3700.0, &Options::default(), |_| {
|
||
seen += 1;
|
||
ControlFlow::Break(())
|
||
})
|
||
.unwrap();
|
||
assert_eq!(seen, 1);
|
||
assert!(matches!(plates_in_bands(&pdf, 0, f32::NAN, &Options::default(), |_| ControlFlow::Continue(())), Err(Error::InvalidDpi)));
|
||
}
|
||
|
||
/// A 10 × 2000 pt strip, black only in its bottom 10 pt.
|
||
fn tall_strip() -> Vec<u8> {
|
||
let content = "0 0 0 1 k 0 0 10 10 re f";
|
||
let mut out = b"%PDF-1.7
|
||
1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj
|
||
"
|
||
.to_vec();
|
||
out.extend_from_slice(
|
||
b"2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj
|
||
",
|
||
);
|
||
out.extend_from_slice(
|
||
b"3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 10 2000] /Contents 4 0 R >> endobj
|
||
",
|
||
);
|
||
out.extend_from_slice(
|
||
format!(
|
||
"4 0 obj << /Length {} >> stream
|
||
{content}
|
||
endstream endobj
|
||
",
|
||
content.len()
|
||
)
|
||
.as_bytes(),
|
||
);
|
||
out.extend_from_slice(
|
||
b"trailer << /Root 1 0 R >>
|
||
%%EOF",
|
||
);
|
||
out
|
||
}
|
||
|
||
#[test]
|
||
fn a_page_past_the_renderers_height_limit_separates_in_bands() {
|
||
// At 600 dpi the strip is 83 × 16 666 pixels: past `MAX_SIDE` down the page.
|
||
let pdf = tall_strip();
|
||
let mut rows = 0;
|
||
let mut bands = 0;
|
||
let mut black_rows = Vec::new();
|
||
plates_in_bands(&pdf, 0, 600.0, &Options::default(), |band| {
|
||
let p = &band.plates;
|
||
assert_eq!((p.width, band.page_height), (83, 16_666));
|
||
let k = p.plane(InkId::process(crate::Process::Black)).unwrap();
|
||
for (y, row) in k.chunks(p.width as usize).enumerate() {
|
||
if row.iter().all(|t| *t == 255) {
|
||
black_rows.push(band.top + y as u32);
|
||
}
|
||
}
|
||
rows += p.height;
|
||
bands += 1;
|
||
ControlFlow::Continue(())
|
||
})
|
||
.unwrap();
|
||
assert_eq!((rows, bands), (16_666, 3), "bands of at most MAX_SIDE rows");
|
||
// The square's top edge is 1990 pt down, row 16 583.3: rows 16 584 to the last are solid.
|
||
assert_eq!(black_rows.first(), Some(&16_584), "{:?}", &black_rows[..black_rows.len().min(3)]);
|
||
assert_eq!(black_rows.len(), 82);
|
||
}
|
||
|
||
#[test]
|
||
fn banded_scale_keeps_the_side_and_area_limits() {
|
||
assert_eq!(banded_scale(40.0, 40.0, 10.0), 10.0);
|
||
assert!(612.0 * banded_scale(612.0, 792.0, 2400.0 / 72.0) <= MAX_SIDE as f32);
|
||
let s = banded_scale(100.0, 1.0e6, 10.0);
|
||
assert!(100.0 * 1.0e6 * s * s <= MAX_BANDED_PIXELS * 1.0001);
|
||
assert!(banded_scale(0.0, f32::NAN, 1.0) > 0.0);
|
||
// A 1 pt wide, very tall page: its width floors to one pixel, which the cap still counts.
|
||
let s = banded_scale(1.0, 1.0e9, 1.0);
|
||
let [width, height] = [1.0f32, 1.0e9].map(|side| (side * s).floor().max(1.0));
|
||
assert!(width * height <= MAX_BANDED_PIXELS);
|
||
// A page whose exact area scale rounds up in f32 by a pixel row.
|
||
let s = banded_scale(17.0, 15_058_824.0, 1.0);
|
||
let [width, height] = [17.0f32, 15_058_824.0].map(|side| u64::from((side * s).floor().max(1.0) as u32));
|
||
assert!(width * height <= MAX_BANDED_PIXELS as u64);
|
||
}
|
||
|
||
#[test]
|
||
fn plates_fit_the_pixel_and_side_caps() {
|
||
assert_eq!(plate_scale(40.0, 40.0, 1.0), 1.0);
|
||
// A4 at 2400 dpi would be 22 000 × 31 000 pixels.
|
||
let s = plate_scale(595.0, 842.0, 2400.0 / 72.0);
|
||
assert!((595.0 * s) * (842.0 * s) <= MAX_PLATE_PIXELS * 1.0001);
|
||
// A 1 × 10 000 pt strip fits the area cap but not the renderer's side limit.
|
||
assert!(10_000.0 * plate_scale(1.0, 10_000.0, 1.0) <= MAX_SIDE as f32);
|
||
assert!(plate_scale(0.0, f32::NAN, 1.0) > 0.0);
|
||
}
|
||
}
|