use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::content::{PageCompiler, SemanticPage};
use crate::document::{DocumentLimits, DocumentSnapshot, PageIndex, ParseContext};
use crate::page_ir::{
BlendMode, CompiledPage, DeviceRect, DeviceSize, DisplayOp, ImageCodecKind, ImageSMask, Matrix,
PageFeatures, Point,
};
use crate::render_api::{
AnnotationMode, Background, HostPage, OutputFormat, OutputResidency, PageTransform,
RenderColorPolicy, RenderLimits, RenderQuality, RenderRequest,
};
use crate::render_cpu::{
CpuBackend, CpuBackendOptions, CpuRenderOptions, CpuWorkerContext, DecodedBilevelSmask,
};
use crate::reader::intake::source;
use crate::reader::page_cache::PageCache;
#[derive(Debug)]
struct WorkerContexts {
parse: ParseContext,
raster: CpuWorkerContext,
}
#[derive(Debug, Default)]
struct WorkerPool {
idle: std::sync::Mutex<Vec<WorkerContexts>>,
}
impl WorkerPool {
fn lock(&self) -> std::sync::MutexGuard<'_, Vec<WorkerContexts>> {
self.idle
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
fn with<R>(&self, job: impl FnOnce(&mut WorkerContexts) -> R) -> R {
let recycled = self.lock().pop();
let mut worker = recycled.unwrap_or_else(|| WorkerContexts {
parse: ParseContext::new(),
raster: CpuWorkerContext::new(),
});
let result = job(&mut worker);
self.lock().push(worker);
result
}
fn clear(&self) {
self.lock().clear();
}
}
static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1);
#[derive(Debug, Clone, Default)]
pub struct CancellationToken(crate::render_api::CancellationToken);
impl CancellationToken {
pub fn new() -> Self {
Self::default()
}
pub fn cancel(&self) {
self.0.cancel();
}
pub fn is_cancelled(&self) -> bool {
self.0.is_cancelled()
}
}
#[derive(Debug, thiserror::Error)]
pub enum ReadError {
#[error("failed to open PDF document: {0}")]
Open(String),
#[error("page index {page} is out of range (document has {page_count} pages)")]
PageOutOfRange {
page: u32,
page_count: u32,
},
#[error("failed to compile PDF page {page}: {message}")]
Compile {
page: u32,
message: String,
},
#[error("invalid raster product: {0}")]
InvalidRasterProduct(&'static str),
#[error("failed to render PDF page {page}: {message}")]
Render {
page: u32,
message: String,
},
#[error("invalid export options: {0}")]
InvalidExportOptions(&'static str),
#[error("exporting a {width}x{height} image exceeds the {max_pixels}-pixel budget")]
ExportTooLarge {
width: u32,
height: u32,
max_pixels: u64,
},
#[error("failed to encode image: {0}")]
Encode(String),
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PageGeometry {
pub crop_box: [f64; 4],
pub media_box: [f64; 4],
pub bleed_box: [f64; 4],
pub trim_box: [f64; 4],
pub art_box: [f64; 4],
pub rotate: u16,
}
impl PageGeometry {
pub fn width(self) -> f64 {
(self.crop_box[2] - self.crop_box[0]).max(0.0)
}
pub fn height(self) -> f64 {
(self.crop_box[3] - self.crop_box[1]).max(0.0)
}
pub fn display_width(self) -> f64 {
display_extent(self.width(), self.height(), self.rotate).0
}
pub fn display_height(self) -> f64 {
display_extent(self.width(), self.height(), self.rotate).1
}
pub fn display_size_of_box(self, b: [f64; 4]) -> (f64, f64) {
display_extent((b[2] - b[0]).max(0.0), (b[3] - b[1]).max(0.0), self.rotate)
}
}
pub(crate) fn display_extent(width: f64, height: f64, rotate: u16) -> (f64, f64) {
if rotate % 180 == 0 {
(width, height)
} else {
(height, width)
}
}
#[derive(Debug, Clone)]
pub struct CompiledDocumentPage {
page_index: u32,
raster: Arc<CompiledPage>,
pub(crate) semantic: Arc<SemanticPage>,
}
impl CompiledDocumentPage {
pub fn page_index(&self) -> u32 {
self.page_index
}
pub fn operation_count(&self) -> usize {
self.raster.operations.len()
}
pub fn bilevel_raster_height(&self) -> Option<u32> {
bilevel_raster_height(&self.raster)
}
pub fn gray_suitability(&self) -> GraySuitability {
let risky = PageFeatures::TRANSPARENCY
| PageFeatures::SOFT_MASKS
| PageFeatures::ICC_COLOR
| PageFeatures::NONSEPARABLE_BLENDS
| PageFeatures::OVERPRINT;
if self.raster.features.intersects(risky) {
GraySuitability::ColorFallback
} else if self
.raster
.features
.intersects(PageFeatures::IMAGES | PageFeatures::PATTERNS | PageFeatures::SHADINGS)
{
GraySuitability::AcceptableForBilevel
} else {
GraySuitability::Exact
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RasterFormat {
Rgb8,
Gray8,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeviceCrop {
pub x: i32,
pub y: i32,
pub width: u32,
pub height: u32,
pub page_width: u32,
pub page_height: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RasterProduct {
pub width: u32,
pub height: u32,
pub format: RasterFormat,
pub crop: Option<DeviceCrop>,
pub decode_reference: Option<DecodeReference>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodeReference {
pub width: u32,
pub height: u32,
}
impl RasterProduct {
pub fn rgb8(width: u32, height: u32) -> Self {
Self {
width,
height,
format: RasterFormat::Rgb8,
crop: None,
decode_reference: None,
}
}
pub fn gray8(width: u32, height: u32) -> Self {
Self {
width,
height,
format: RasterFormat::Gray8,
crop: None,
decode_reference: None,
}
}
pub fn with_crop(mut self, crop: DeviceCrop) -> Self {
self.crop = Some(crop);
self
}
pub fn with_decode_reference(mut self, width: u32, height: u32) -> Self {
self.decode_reference = Some(DecodeReference { width, height });
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GraySuitability {
Exact,
AcceptableForBilevel,
ColorFallback,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnalysisTarget {
pub product: RasterProduct,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BaseTarget {
pub product: RasterProduct,
pub gray_suitability: GraySuitability,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RegionTarget {
pub product: RasterProduct,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OcrTarget {
pub product: RasterProduct,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PageOutputPlan {
pub analysis: Option<AnalysisTarget>,
pub base: BaseTarget,
pub regions: Vec<RegionTarget>,
pub ocr: Option<OcrTarget>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RgbSurface {
pub width: u32,
pub height: u32,
pub stride: usize,
pub pixels: Arc<[u8]>,
}
impl RgbSurface {
pub fn as_bytes(&self) -> &[u8] {
let len = self.stride.saturating_mul(self.height as usize);
self.pixels.get(..len).unwrap_or(&self.pixels)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GraySurface {
pub width: u32,
pub height: u32,
pub stride: usize,
pub pixels: Arc<[u8]>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RasterPlane {
Rgb8(RgbSurface),
Gray8(GraySurface),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderedRegion {
pub target: RegionTarget,
pub plane: RasterPlane,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PageRasterProducts {
pub base: RasterPlane,
pub regions: Vec<RenderedRegion>,
pub ocr: Option<RasterPlane>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Jbig2StencilPolarity {
PaintZero,
PaintOne,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PreservedJbig2Smask {
pub page_data: Arc<[u8]>,
pub global_data: Arc<[u8]>,
pub native_width: u32,
pub native_height: u32,
pub stencil_polarity: Jbig2StencilPolarity,
pub working_coverage: GraySurface,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct SessionOptions {
pub cached_pages: usize,
pub cached_page_bytes: usize,
pub image_cache_bytes: usize,
pub font_cache_bytes: usize,
pub glyph_cache_bytes: usize,
pub surface_pool_bytes: usize,
pub strip_bytes: usize,
}
impl Default for SessionOptions {
fn default() -> Self {
Self {
cached_pages: 8,
cached_page_bytes: 256 << 20,
image_cache_bytes: 96 << 20,
font_cache_bytes: 48 << 20,
glyph_cache_bytes: 32 << 20,
surface_pool_bytes: 256 << 20,
strip_bytes: crate::render_cpu::default_strip_target_bytes(),
}
}
}
fn retained_page_bytes(page: &CompiledDocumentPage) -> usize {
let semantic = &page.semantic;
page.raster
.approx_retained_bytes()
.saturating_add(semantic.ops.len() * std::mem::size_of::<crate::content::SemanticOp>())
.saturating_add(semantic.text_runs.len() * std::mem::size_of::<crate::content::TextRun>())
}
#[derive(Debug)]
pub struct RenderSession {
id: u64,
pub(crate) snapshot: Arc<DocumentSnapshot>,
pub(crate) compiler: Arc<PageCompiler>,
backend: Arc<CpuBackend>,
pages: PageCache<CompiledDocumentPage>,
workers: WorkerPool,
#[cfg(feature = "profiling")]
profile_detail: std::sync::Mutex<crate::profiling::ProfileDetail>,
}
impl RenderSession {
pub fn open(bytes: Arc<[u8]>, password: Option<&str>) -> Result<Self, ReadError> {
Self::open_with_cache_capacity(bytes, password, 8)
}
pub fn open_with_cache_capacity(
bytes: Arc<[u8]>,
password: Option<&str>,
cached_pages: usize,
) -> Result<Self, ReadError> {
Self::open_source_with_cache_capacity(source(bytes), password, cached_pages)
}
pub fn open_path(
path: impl AsRef<std::path::Path>,
password: Option<&str>,
) -> Result<Self, ReadError> {
let mapped = crate::source::MmapSource::open(path)
.map_err(|error| ReadError::Open(error.to_string()))?;
Self::open_source(Arc::new(mapped), password)
}
pub fn open_source(
source: Arc<dyn crate::source::PdfSource>,
password: Option<&str>,
) -> Result<Self, ReadError> {
Self::open_source_with_options(source, password, &SessionOptions::default())
}
pub fn open_source_with_options(
source: Arc<dyn crate::source::PdfSource>,
password: Option<&str>,
options: &SessionOptions,
) -> Result<Self, ReadError> {
let snapshot =
DocumentSnapshot::open_with_password(source, DocumentLimits::default(), password)
.map_err(|error| ReadError::Open(error.to_string()))?;
let backend = CpuBackend::new(CpuBackendOptions::default())
.with_cache_bytes(
options.image_cache_bytes,
options.font_cache_bytes,
options.glyph_cache_bytes,
)
.with_surface_pool_bytes(options.surface_pool_bytes)
.with_strip_target_bytes(options.strip_bytes);
Ok(Self {
id: NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed),
snapshot: Arc::new(snapshot),
compiler: Arc::new(PageCompiler::new().with_annotations(true)),
backend: Arc::new(backend),
pages: PageCache::with_byte_budget(
options.cached_pages,
options.cached_page_bytes,
retained_page_bytes,
),
workers: WorkerPool::default(),
#[cfg(feature = "profiling")]
profile_detail: std::sync::Mutex::new(crate::profiling::ProfileDetail::default()),
})
}
pub fn open_source_with_cache_capacity(
source: Arc<dyn crate::source::PdfSource>,
password: Option<&str>,
cached_pages: usize,
) -> Result<Self, ReadError> {
let options = SessionOptions {
cached_pages,
..SessionOptions::default()
};
Self::open_source_with_options(source, password, &options)
}
pub fn clear_resource_caches(&self) {
self.backend.clear_resource_caches();
}
pub fn cached_page_bytes(&self) -> usize {
self.pages.retained_bytes()
}
pub fn release_idle_memory(&self) {
self.workers.clear();
self.backend.release_idle_memory();
}
pub fn idle_surface_bytes(&self) -> usize {
self.backend.idle_surface_bytes()
}
pub(crate) fn id(&self) -> u64 {
self.id
}
pub fn page_count(&self) -> u32 {
self.snapshot.page_count()
}
pub fn page_geometry(&self, page: u32) -> Result<PageGeometry, ReadError> {
let page_ref = self
.snapshot
.page(PageIndex(page))
.map_err(|_| self.page_out_of_range(page))?;
Ok(PageGeometry {
crop_box: page_ref.crop_box,
media_box: page_ref.media_box,
bleed_box: page_ref.bleed_box,
trim_box: page_ref.trim_box,
art_box: page_ref.art_box,
rotate: page_ref.rotate,
})
}
pub fn compile(&self, page: u32) -> Result<Arc<CompiledDocumentPage>, ReadError> {
self.compile_cancellable(page, None)
}
pub fn compile_cancellable(
&self,
page: u32,
cancellation: Option<&CancellationToken>,
) -> Result<Arc<CompiledDocumentPage>, ReadError> {
if page >= self.page_count() {
return Err(self.page_out_of_range(page));
}
self.pages.get_or_compile(page, cancellation, || {
let artifacts = self
.workers
.with(|worker| {
worker.parse.begin_job();
worker
.parse
.set_cancellation_flag(cancellation.map(|token| token.0.shared_flag()));
let result = self.compiler.compile_artifacts(
&self.snapshot,
PageIndex(page),
&mut worker.parse,
);
worker.parse.set_cancellation_flag(None);
result
})
.map_err(|error| ReadError::Compile {
page,
message: error.to_string(),
})?;
Ok(Arc::new(CompiledDocumentPage {
page_index: page,
raster: artifacts.compiled,
semantic: artifacts.semantic,
}))
})
}
pub fn clear_page_cache(&self) {
self.pages.clear();
}
pub fn render(
&self,
page: &Arc<CompiledDocumentPage>,
product: &RasterProduct,
) -> Result<RasterPlane, ReadError> {
self.render_cancellable(page, product, None)
}
pub fn render_cancellable(
&self,
page: &Arc<CompiledDocumentPage>,
product: &RasterProduct,
cancellation: Option<&CancellationToken>,
) -> Result<RasterPlane, ReadError> {
self.render_inner(page, product, cancellation, false)
.map(|(plane, _stats)| plane)
}
pub fn render_in_place(
&self,
page: &Arc<CompiledDocumentPage>,
product: &RasterProduct,
) -> Result<RasterPlane, ReadError> {
self.render_in_place_cancellable(page, product, None)
}
pub fn render_in_place_cancellable(
&self,
page: &Arc<CompiledDocumentPage>,
product: &RasterProduct,
cancellation: Option<&CancellationToken>,
) -> Result<RasterPlane, ReadError> {
self.render_inner(page, product, cancellation, true)
.map(|(plane, _stats)| plane)
}
#[cfg(feature = "profiling")]
pub fn render_profiled(
&self,
page: &Arc<CompiledDocumentPage>,
product: &RasterProduct,
) -> Result<(RasterPlane, crate::profiling::ProfileReport), ReadError> {
let start = std::time::Instant::now();
let (plane, stats) = self.render_inner(page, product, None, false)?;
let profile = crate::render_cpu::profile_from_stats(&stats, start.elapsed());
Ok((plane, profile))
}
#[cfg(feature = "profiling")]
pub fn set_profile_detail(&self, detail: crate::profiling::ProfileDetail) {
*self
.profile_detail
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()) = detail;
}
fn render_inner(
&self,
page: &Arc<CompiledDocumentPage>,
product: &RasterProduct,
cancellation: Option<&CancellationToken>,
in_place: bool,
) -> Result<(RasterPlane, crate::render_cpu::RenderStats), ReadError> {
if product.width == 0 || product.height == 0 {
return Err(ReadError::InvalidRasterProduct(
"width and height must both be non-zero",
));
}
let output_format = match product.format {
RasterFormat::Rgb8 => OutputFormat::Rgba8PremultipliedSrgb,
RasterFormat::Gray8 => OutputFormat::Gray8,
};
let request = RenderRequest {
page: Arc::clone(&page.raster),
transform: PageTransform {
matrix: product_matrix(&page.raster, product),
},
crop: product.crop.map(|crop| DeviceRect {
x: crop.x,
y: crop.y,
width: crop.width,
height: crop.height,
}),
output_size: DeviceSize {
width: product.width,
height: product.height,
},
output_format,
background: Background::White,
color_policy: RenderColorPolicy::Original,
annotations: AnnotationMode::StaticAppearances,
quality: RenderQuality::Normal,
limits: render_limits(cancellation),
residency: OutputResidency::HostRequired,
};
let options = render_options(&page.raster, product);
let rgb = product.format == RasterFormat::Rgb8;
let rendered = catch_unwind(AssertUnwindSafe(|| {
self.workers.with(|worker| {
#[cfg(feature = "profiling")]
worker.raster.set_profile_detail(
*self
.profile_detail
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner()),
);
if rgb {
let rendered = if in_place {
self.backend.render_packed_rgb_with_options(
&request,
&options,
&mut worker.raster,
)
} else {
self.backend
.render_rgb_with_options(&request, &options, &mut worker.raster)
};
rendered.map(|(packed, stats)| {
(
HostPage {
width: packed.width,
height: packed.height,
stride: packed.stride,
format: output_format,
pixels: packed.pixels,
},
stats,
)
})
} else {
self.backend
.render_with_options(&request, &options, &mut worker.raster)
}
})
}))
.map_err(|payload| ReadError::Render {
page: page.page_index,
message: format!(
"renderer panicked: {}",
crate::render_api::panic_message(payload)
),
})?
.map_err(|error| ReadError::Render {
page: page.page_index,
message: error.to_string(),
})?;
let (rendered, stats) = rendered;
if rendered.format != output_format {
return Err(ReadError::Render {
page: page.page_index,
message: format!(
"renderer returned {:?} for a {:?} request",
rendered.format, output_format
),
});
}
match product.format {
RasterFormat::Gray8 => Ok((
RasterPlane::Gray8(GraySurface {
width: rendered.width,
height: rendered.height,
stride: rendered.stride,
pixels: rendered.pixels,
}),
stats,
)),
RasterFormat::Rgb8 => Ok((
RasterPlane::Rgb8(RgbSurface {
width: rendered.width,
height: rendered.height,
stride: rendered.stride,
pixels: rendered.pixels,
}),
stats,
)),
}
}
pub fn render_output_plan(
&self,
page: &Arc<CompiledDocumentPage>,
plan: &PageOutputPlan,
cancellation: Option<&CancellationToken>,
) -> Result<PageRasterProducts, ReadError> {
let base = self.render_cancellable(page, &plan.base.product, cancellation)?;
let regions = plan
.regions
.iter()
.map(|target| {
Ok(RenderedRegion {
target: target.clone(),
plane: self.render_cancellable(page, &target.product, cancellation)?,
})
})
.collect::<Result<Vec<_>, ReadError>>()?;
let ocr = plan
.ocr
.as_ref()
.map(|target| self.render_cancellable(page, &target.product, cancellation))
.transpose()?;
Ok(PageRasterProducts { base, regions, ocr })
}
pub fn preserved_jbig2_smask(
&self,
page: &Arc<CompiledDocumentPage>,
target_width: u32,
target_height: u32,
cancellation: Option<&CancellationToken>,
) -> Result<Option<PreservedJbig2Smask>, ReadError> {
if target_width == 0 || target_height == 0 {
return Err(ReadError::InvalidRasterProduct(
"preserved mask target dimensions must be non-zero",
));
}
let Some(candidate) = qualifying_jbig2_smask(&page.raster) else {
return Ok(None);
};
let decoded = self
.backend
.decode_bilevel_jbig2_smask(&candidate.smask, &render_limits(cancellation))
.map_err(|error| ReadError::Render {
page: page.page_index,
message: format!("JBIG2 SMask decode failed: {error}"),
})?;
let Some(decoded) = decoded else {
return Ok(None);
};
let working_coverage = resize_smask_coverage(decoded, target_width, target_height)
.ok_or_else(|| ReadError::Render {
page: page.page_index,
message: "JBIG2 SMask decoder returned a truncated opacity plane".to_string(),
})?;
Ok(Some(PreservedJbig2Smask {
page_data: candidate.page_data,
global_data: candidate
.smask
.codec_parms
.as_ref()
.and_then(|parms| parms.jbig2_globals.clone())
.unwrap_or_else(|| Arc::from([])),
native_width: candidate.smask.width,
native_height: candidate.smask.height,
stencil_polarity: candidate.stencil_polarity,
working_coverage,
}))
}
fn page_out_of_range(&self, page: u32) -> ReadError {
ReadError::PageOutOfRange {
page,
page_count: self.page_count(),
}
}
}
fn render_limits(cancellation: Option<&CancellationToken>) -> RenderLimits {
RenderLimits {
cancellation: cancellation.map(|token| token.0.clone()),
..RenderLimits::default()
}
}
fn resize_smask_coverage(
decoded: DecodedBilevelSmask,
target_width: u32,
target_height: u32,
) -> Option<GraySurface> {
let (source_width, source_height) = (decoded.width as usize, decoded.height as usize);
if decoded.stride != source_width
|| source_width == 0
|| source_height == 0
|| target_width == 0
|| target_height == 0
{
return None;
}
let source = decoded.opacity.get(..source_width * source_height)?;
if (target_width as usize, target_height as usize) == (source_width, source_height) {
return Some(GraySurface {
width: target_width,
height: target_height,
stride: source_width,
pixels: Arc::clone(&decoded.opacity),
});
}
let (tw, th) = (target_width as usize, target_height as usize);
let columns = coverage_spans(source_width, tw);
let rows = coverage_spans(source_height, th);
let mut horizontal = vec![0u32; source_height * tw];
for (source_row, sums) in source
.chunks_exact(source_width)
.zip(horizontal.chunks_exact_mut(tw))
{
for (sum, span) in sums.iter_mut().zip(&columns) {
*sum = span
.taps()
.map(|(i, weight)| weight * u32::from(source_row[i]))
.sum();
}
}
let denominator = (source_width * source_height) as u64;
let mut pixels = vec![0u8; tw * th];
for (out_row, span) in pixels.chunks_exact_mut(tw).zip(&rows) {
for (x, out) in out_row.iter_mut().enumerate() {
let sum: u64 = span
.taps()
.map(|(i, weight)| u64::from(weight) * u64::from(horizontal[i * tw + x]))
.sum();
*out = ((sum + denominator / 2) / denominator).min(255) as u8;
}
}
Some(GraySurface {
width: target_width,
height: target_height,
stride: tw,
pixels: Arc::from(pixels),
})
}
#[derive(Clone, Copy)]
struct CoverageSpan {
first: usize,
last: usize,
first_weight: u32,
last_weight: u32,
interior_weight: u32,
}
impl CoverageSpan {
fn taps(&self) -> impl Iterator<Item = (usize, u32)> + '_ {
(self.first..=self.last).map(move |i| {
let weight = if self.first == self.last {
self.first_weight
} else if i == self.first {
self.first_weight
} else if i == self.last {
self.last_weight
} else {
self.interior_weight
};
(i, weight)
})
}
}
fn coverage_spans(source: usize, target: usize) -> Vec<CoverageSpan> {
(0..target)
.map(|j| {
let start = j * source;
let end = (j + 1) * source;
let first = start / target;
let last = ((end - 1) / target).min(source - 1);
let overlap = |i: usize| -> u32 {
let lo = start.max(i * target);
let hi = end.min((i + 1) * target);
hi.saturating_sub(lo) as u32
};
CoverageSpan {
first,
last,
first_weight: overlap(first),
last_weight: overlap(last),
interior_weight: target as u32,
}
})
.collect()
}
#[derive(Clone)]
struct Jbig2SmaskCandidate {
smask: Arc<ImageSMask>,
page_data: Arc<[u8]>,
stencil_polarity: Jbig2StencilPolarity,
}
fn qualifying_jbig2_smask(page: &CompiledPage) -> Option<Jbig2SmaskCandidate> {
if page.bounds.rotate != 0 {
return None;
}
let mut ctm = Matrix::IDENTITY;
let mut stack = Vec::new();
let mut candidate = None;
let mut image_draws = 0usize;
for op in page.operations.iter() {
match op {
DisplayOp::Save => stack.push(ctm),
DisplayOp::Restore => ctm = stack.pop()?,
DisplayOp::ConcatTransform(matrix) => ctm = matrix.then(ctm),
DisplayOp::BeginPaintOrigin(_) | DisplayOp::EndPaintOrigin => {}
DisplayOp::DrawGlyphRun { run, .. }
if page.glyph_runs.get(run.index())?.render_mode == 3 => {}
DisplayOp::DrawImage {
image,
transform,
alpha,
blend,
..
} => {
image_draws += 1;
let image = page.images.get(image.index())?;
let placement = transform.then(ctm);
if *blend != BlendMode::Normal
|| (*alpha - 1.0).abs() > f32::EPSILON
|| !is_unflipped_full_page(placement, page, image.width, image.height)
|| image.is_stencil
|| image.lowering_degraded
|| image.mask.is_some()
|| image.smask_in_data != 0
{
return None;
}
if let Some(smask) = image.smask.as_ref() {
if candidate.is_some()
|| smask.width != image.width
|| smask.height != image.height
|| smask.bits_per_component != 1
|| smask.codec != Some(ImageCodecKind::Jbig2)
|| !smask.samples.is_empty()
{
return None;
}
let page_data = smask.codec_data.clone().filter(|data| !data.is_empty())?;
let stencil_polarity = match smask.decode.as_deref() {
None => Jbig2StencilPolarity::PaintOne,
Some([[lo, hi]]) if *lo == 0.0 && *hi == 1.0 => {
Jbig2StencilPolarity::PaintOne
}
Some([[lo, hi]]) if *lo == 1.0 && *hi == 0.0 => {
Jbig2StencilPolarity::PaintZero
}
_ => return None,
};
candidate = Some(Jbig2SmaskCandidate {
smask: Arc::clone(smask),
page_data: Arc::from(page_data.as_slice()),
stencil_polarity,
});
}
}
_ => return None,
}
}
if !stack.is_empty() || image_draws == 0 {
return None;
}
candidate
}
const PAGE_IMAGE_COVERAGE: f64 = 0.6;
fn bilevel_raster_height(page: &CompiledPage) -> Option<u32> {
let crop = page.bounds.crop;
let (page_w, page_h) = (crop.width().abs(), crop.height().abs());
if !(page_w > 0.0 && page_h > 0.0) {
return None;
}
let mut ctm = Matrix::IDENTITY;
let mut stack = Vec::new();
let mut ink: Option<u32> = None;
for op in page.operations.iter() {
match op {
DisplayOp::Save => stack.push(ctm),
DisplayOp::Restore => ctm = stack.pop().unwrap_or(Matrix::IDENTITY),
DisplayOp::ConcatTransform(matrix) => ctm = matrix.then(ctm),
DisplayOp::DrawImage {
image, transform, ..
} => {
let Some(image) = page.images.get(image.index()) else {
continue;
};
let placement = transform.then(ctm);
if !placement.is_finite() {
continue;
}
let drawn_w = placement.a.abs() + placement.c.abs();
let drawn_h = placement.b.abs() + placement.d.abs();
if drawn_h <= 0.0
|| drawn_w < page_w * PAGE_IMAGE_COVERAGE
|| drawn_h < page_h * PAGE_IMAGE_COVERAGE
{
continue;
}
let bilevel = if image.is_stencil || image.bits_per_component == 1 {
Some((image.width, image.height))
} else {
image
.smask
.as_ref()
.filter(|smask| smask.bits_per_component == 1)
.map(|smask| (smask.width, smask.height))
};
let Some((width, height)) = bilevel.filter(|(_, height)| *height > 0) else {
continue;
};
let along_page_height = if placement.b.abs() > placement.d.abs() {
width
} else {
height
};
let implied = (f64::from(along_page_height) * page_h / drawn_h).round();
if implied.is_finite() && implied >= 1.0 {
let implied = implied as u32;
ink = Some(ink.map_or(implied, |n: u32| n.max(implied)));
}
}
_ => {}
}
}
ink
}
fn is_unflipped_full_page(
matrix: Matrix,
page: &CompiledPage,
image_width: u32,
image_height: u32,
) -> bool {
if !matrix.is_finite()
|| matrix.a <= 0.0
|| matrix.d <= 0.0
|| matrix.b.abs() > 1e-7
|| matrix.c.abs() > 1e-7
{
return false;
}
let p0 = matrix.apply(Point { x: 0.0, y: 0.0 });
let p1 = matrix.apply(Point { x: 1.0, y: 1.0 });
let crop = page.bounds.crop;
let numeric_tolerance = (crop.width().abs().max(crop.height().abs()) * 1e-5).max(1e-4);
let tolerance_x = numeric_tolerance.max(matrix.a.abs() / f64::from(image_width.max(1)) * 0.5);
let tolerance_y = numeric_tolerance.max(matrix.d.abs() / f64::from(image_height.max(1)) * 0.5);
(p0.x - crop.x0).abs() <= tolerance_x
&& (p0.y - crop.y0).abs() <= tolerance_y
&& (p1.x - crop.x1).abs() <= tolerance_x
&& (p1.y - crop.y1).abs() <= tolerance_y
}
fn page_to_device_matrix(page: &CompiledPage, output_width: u32, output_height: u32) -> Matrix {
let crop = page.bounds.crop;
let rotation = page.bounds.rotate % 360;
let (display_width, display_height) = display_extent(crop.width(), crop.height(), rotation);
let scale_x = output_width as f64 / display_width.max(f64::EPSILON);
let scale_y = output_height as f64 / display_height.max(f64::EPSILON);
match rotation {
90 => Matrix {
a: 0.0,
b: scale_y,
c: scale_x,
d: 0.0,
e: -crop.y0 * scale_x,
f: -crop.x0 * scale_y,
},
180 => Matrix {
a: -scale_x,
b: 0.0,
c: 0.0,
d: scale_y,
e: crop.x1 * scale_x,
f: -crop.y0 * scale_y,
},
270 => Matrix {
a: 0.0,
b: -scale_y,
c: -scale_x,
d: 0.0,
e: crop.y1 * scale_x,
f: crop.x1 * scale_y,
},
_ => Matrix {
a: scale_x,
b: 0.0,
c: 0.0,
d: -scale_y,
e: -crop.x0 * scale_x,
f: crop.y1 * scale_y,
},
}
}
fn render_options(page: &CompiledPage, product: &RasterProduct) -> CpuRenderOptions {
CpuRenderOptions {
image_decode_reference: product
.decode_reference
.filter(|reference| reference.width > 0 && reference.height > 0)
.map(|reference| PageTransform {
matrix: page_to_device_matrix(page, reference.width, reference.height),
}),
}
}
fn product_matrix(page: &CompiledPage, product: &RasterProduct) -> Matrix {
let Some(crop) = product.crop else {
return page_to_device_matrix(page, product.width, product.height);
};
let mut matrix = page_to_device_matrix(page, crop.page_width.max(1), crop.page_height.max(1));
let sx = product.width as f64 / crop.width.max(1) as f64;
let sy = product.height as f64 / crop.height.max(1) as f64;
matrix.a *= sx;
matrix.c *= sx;
matrix.e = (matrix.e - crop.x as f64) * sx;
matrix.b *= sy;
matrix.d *= sy;
matrix.f = (matrix.f - crop.y as f64) * sy;
matrix
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use crate::page_ir::{
CodecParms, ImageColorSpace, ImageId, ImageIr, InterpolationMode, PageBounds, PaintId,
Rect, ResourceKey,
};
fn eligible_page() -> CompiledPage {
let smask = Arc::new(ImageSMask {
width: 12,
height: 5,
bits_per_component: 1,
decode: None,
samples: Arc::from([]),
codec: Some(ImageCodecKind::Jbig2),
codec_data: Some((&b"encoded mask"[..]).into()),
codec_parms: Some(CodecParms {
jbig2_globals: Some(Arc::from(&b"encoded globals"[..])),
..CodecParms::default()
}),
});
let image = ImageIr {
key: ResourceKey {
object_number: 1,
generation: 0,
variant: 0,
},
width: 12,
height: 5,
is_stencil: false,
interpolation: InterpolationMode::Nearest,
soft_mask: None,
bits_per_component: 8,
color_space: ImageColorSpace::Gray,
decode: None,
samples: Some(Arc::from(&b"base"[..])),
codec: None,
codec_data: None,
codec_parms: None,
smask: Some(smask),
mask: None,
smask_in_data: 0,
lowering_degraded: false,
};
let mut page = CompiledPage::empty(PageBounds {
crop: Rect {
x0: 0.0,
y0: 0.0,
x1: 120.0,
y1: 50.0,
},
rotate: 0,
});
page.images = Arc::from([image]);
page.operations = Arc::from([
DisplayOp::Save,
DisplayOp::ConcatTransform(Matrix::scale(120.0, 50.0)),
DisplayOp::DrawImage {
image: ImageId(0),
paint: PaintId(0),
transform: Matrix::IDENTITY,
alpha: 1.0,
blend: BlendMode::Normal,
},
DisplayOp::Restore,
]);
page
}
#[test]
fn qualifies_only_native_full_page_jbig2_smask() {
let page = eligible_page();
let candidate = qualifying_jbig2_smask(&page).expect("eligible mask");
assert_eq!(candidate.page_data.as_ref(), &b"encoded mask"[..]);
assert_eq!(
candidate
.smask
.codec_parms
.as_ref()
.and_then(|parms| parms.jbig2_globals.as_deref()),
Some(&b"encoded globals"[..])
);
assert_eq!(candidate.stencil_polarity, Jbig2StencilPolarity::PaintOne);
let mut maskless = page.clone();
let maskless_image = &mut Arc::make_mut(&mut maskless.images)[0];
maskless_image.smask = None;
maskless_image.codec = Some(ImageCodecKind::Dct);
maskless_image.codec_data = Some((&b"jpeg"[..]).into());
assert!(qualifying_jbig2_smask(&maskless).is_none());
let mut non_jbig2 = page.clone();
let smask = Arc::make_mut(&mut non_jbig2.images)[0]
.smask
.as_mut()
.unwrap();
Arc::make_mut(smask).codec = Some(ImageCodecKind::CcittFax);
assert!(qualifying_jbig2_smask(&non_jbig2).is_none());
let mut grayscale = page.clone();
let smask = Arc::make_mut(&mut grayscale.images)[0]
.smask
.as_mut()
.unwrap();
let smask = Arc::make_mut(smask);
smask.bits_per_component = 8;
smask.codec = None;
smask.codec_data = None;
smask.samples = Arc::from(&b"gray"[..]);
assert!(qualifying_jbig2_smask(&grayscale).is_none());
let mut image_mask = page.clone();
Arc::make_mut(&mut image_mask.images)[0].is_stencil = true;
assert!(qualifying_jbig2_smask(&image_mask).is_none());
let mut in_data = page.clone();
Arc::make_mut(&mut in_data.images)[0].smask_in_data = 1;
assert!(qualifying_jbig2_smask(&in_data).is_none());
let mut explicit_mask = page;
Arc::make_mut(&mut explicit_mask.images)[0].mask =
Some(crate::page_ir::ImageMask::ColorKey(Arc::from([[0, 0]])));
assert!(qualifying_jbig2_smask(&explicit_mask).is_none());
}
#[test]
fn source_decode_maps_to_opposite_stencil_polarity() {
let mut page = eligible_page();
{
let smask = Arc::make_mut(&mut page.images)[0].smask.as_mut().unwrap();
Arc::make_mut(smask).decode = Some(Arc::from([[1.0, 0.0]]));
}
assert_eq!(
qualifying_jbig2_smask(&page)
.expect("inverted source decode remains representable")
.stencil_polarity,
Jbig2StencilPolarity::PaintZero
);
let smask = Arc::make_mut(&mut page.images)[0].smask.as_mut().unwrap();
Arc::make_mut(smask).decode = Some(Arc::from([[0.2, 0.8]]));
assert!(qualifying_jbig2_smask(&page).is_none());
}
#[test]
fn rejects_ambiguous_or_unsupported_placement() {
let page = eligible_page();
let mut duplicate = page.clone();
let mut operations = duplicate.operations.to_vec();
operations.splice(3..3, duplicate.operations[0..3].iter().cloned());
duplicate.operations = Arc::from(operations);
assert!(qualifying_jbig2_smask(&duplicate).is_none());
let mut rotated = page.clone();
rotated.bounds.rotate = 90;
assert!(qualifying_jbig2_smask(&rotated).is_none());
let mut offset = page;
Arc::make_mut(&mut offset.operations)[1] =
DisplayOp::ConcatTransform(Matrix::scale(109.0, 50.0));
assert!(qualifying_jbig2_smask(&offset).is_none());
}
#[test]
fn accepts_full_page_placement_within_half_a_source_pixel() {
let mut page = eligible_page();
Arc::make_mut(&mut page.operations)[1] = DisplayOp::ConcatTransform(Matrix {
a: 112.0,
b: 0.0,
c: 0.0,
d: 42.0,
e: 4.0,
f: 4.0,
});
assert!(qualifying_jbig2_smask(&page).is_some());
Arc::make_mut(&mut page.operations)[1] = DisplayOp::ConcatTransform(Matrix {
a: 108.0,
b: 0.0,
c: 0.0,
d: 38.0,
e: 6.0,
f: 6.0,
});
assert!(qualifying_jbig2_smask(&page).is_none());
}
#[test]
fn working_plane_preserves_fractional_edge_coverage() {
let decoded = DecodedBilevelSmask {
width: 2,
height: 2,
stride: 2,
opacity: Arc::from([0, 255, 255, 0]),
};
let working = resize_smask_coverage(decoded, 7, 7).expect("valid coverage");
assert_eq!((working.width, working.height, working.stride), (7, 7, 7));
assert!(
working
.pixels
.iter()
.any(|&sample| sample > 0 && sample < 255),
"resized analysis mask must retain antialiased edge coverage"
);
assert_eq!(working.pixels[3], 128);
assert_eq!(working.pixels[0], 0);
assert_eq!(working.pixels[6], 255);
}
#[test]
fn working_plane_is_the_exact_area_average() {
let mut checker = [0u8; 16];
for (i, v) in checker.iter_mut().enumerate() {
if (i % 4 + i / 4) % 2 == 0 {
*v = 255;
}
}
let decoded = DecodedBilevelSmask {
width: 4,
height: 4,
stride: 4,
opacity: Arc::from(checker),
};
let working = resize_smask_coverage(decoded, 2, 2).expect("valid coverage");
assert_eq!(&working.pixels[..], &[128, 128, 128, 128]);
let decoded = DecodedBilevelSmask {
width: 3,
height: 1,
stride: 3,
opacity: Arc::from([0, 255, 255]),
};
let working = resize_smask_coverage(decoded, 2, 1).expect("valid coverage");
assert_eq!(&working.pixels[..], &[85, 255]);
let decoded = DecodedBilevelSmask {
width: 3,
height: 1,
stride: 3,
opacity: Arc::from([0, 255, 7]),
};
let working = resize_smask_coverage(decoded, 3, 1).expect("valid coverage");
assert_eq!(&working.pixels[..], &[0, 255, 7]);
}
#[test]
fn decode_reference_maps_to_the_whole_page_transform() {
let page = eligible_page();
let crop = DeviceCrop {
x: 3,
y: 4,
width: 5,
height: 6,
page_width: 40,
page_height: 60,
};
let region = RasterProduct::rgb8(10, 12)
.with_crop(crop)
.with_decode_reference(40, 60);
assert_eq!(
render_options(&page, ®ion)
.image_decode_reference
.map(|reference| reference.matrix),
Some(page_to_device_matrix(&page, 40, 60))
);
for product in [
RasterProduct::gray8(8, 8),
RasterProduct::gray8(8, 8).with_decode_reference(0, 60),
] {
assert!(
render_options(&page, &product)
.image_decode_reference
.is_none()
);
}
}
}