#[cfg(feature = "profiling")]
use std::collections::HashSet;
use std::collections::{BTreeMap, HashMap};
use std::sync::Arc;
use crate::font::FontProgram;
use crate::page_ir::{
CompiledPage, DeviceRect, DeviceSize, DisplayOp, GlyphRun, Matrix, Paint, PathData, PathVerb,
Point, ShadingKind, ShadingResource, StrokeStyle, TilingPattern,
};
use crate::render_cpu::raster::FillRule;
use crate::render_cpu::stroke;
use crate::render_cpu::surface::{unique_arc_mut, zeroed_arc};
#[derive(Debug, Default)]
pub(crate) struct FontProgramCache {
fonts: Option<std::sync::Weak<[crate::page_ir::FontResource]>>,
programs: HashMap<u32, Option<FontProgram>>,
}
impl FontProgramCache {
fn is_for(&self, page: &CompiledPage) -> bool {
self.fonts
.as_ref()
.is_some_and(|held| std::ptr::addr_eq(held.as_ptr(), Arc::as_ptr(&page.fonts)))
}
fn take_for_page(&mut self, page: &CompiledPage) -> (HashMap<u32, Option<FontProgram>>, bool) {
if self.is_for(page) {
(std::mem::take(&mut self.programs), true)
} else {
self.fonts = Some(Arc::downgrade(&page.fonts));
self.programs.clear();
(HashMap::new(), false)
}
}
fn store_for_page(
&mut self,
page: &CompiledPage,
mut programs: HashMap<u32, Option<FontProgram>>,
) {
programs.retain(|_, program| {
program
.as_ref()
.is_some_and(FontProgram::benefits_from_parse_cache)
});
if !self.is_for(page) {
self.fonts = Some(Arc::downgrade(&page.fonts));
}
self.programs = programs;
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct FontProgramKey {
h0: u64,
h1: u64,
len: usize,
face: u32,
}
impl FontProgramKey {
fn for_resource(resource: &crate::page_ir::FontResource) -> Self {
let (h0, h1) = content_hash_128(&resource.program);
Self {
h0,
h1,
len: resource.program.len(),
face: resource.face_index,
}
}
}
fn content_hash_128(bytes: &[u8]) -> (u64, u64) {
const P0: u64 = 0x9E37_79B9_7F4A_7C15;
const P1: u64 = 0xC2B2_AE3D_27D4_EB4F;
let mut a: u64 = 0xCBF2_9CE4_8422_2325 ^ (bytes.len() as u64).wrapping_mul(P0);
let mut b: u64 = 0x1000_0000_1B3 ^ (bytes.len() as u64).wrapping_mul(P1);
let mut chunks = bytes.chunks_exact(8);
for chunk in &mut chunks {
let w = u64::from_le_bytes(chunk.try_into().unwrap_or([0; 8]));
a = (a ^ w).wrapping_mul(P0).rotate_left(31);
b = (b.rotate_left(27) ^ w).wrapping_mul(P1);
}
let rem = chunks.remainder();
if !rem.is_empty() {
let mut buf = [0u8; 8];
buf[..rem.len()].copy_from_slice(rem);
let w = u64::from_le_bytes(buf);
a = (a ^ w).wrapping_mul(P0).rotate_left(31);
b = (b.rotate_left(27) ^ w).wrapping_mul(P1);
}
a ^= a >> 33;
a = a.wrapping_mul(P1);
a ^= a >> 29;
b ^= b >> 31;
b = b.wrapping_mul(P0);
b ^= b >> 27;
(a, b)
}
fn lock_unpoisoned<T>(m: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
}
#[derive(Debug)]
pub struct SharedFontProgramCache {
shards: Box<[std::sync::Mutex<FontCacheShard>]>,
per_shard_bytes: usize,
hits: std::sync::atomic::AtomicU64,
inserts: std::sync::atomic::AtomicU64,
}
#[derive(Debug, Default)]
struct FontCacheShard {
map: HashMap<FontProgramKey, FontCacheEntry>,
bytes: usize,
clock: u64,
lru: BTreeMap<u64, FontProgramKey>,
}
#[derive(Debug)]
struct FontCacheEntry {
program: FontProgram,
charge: usize,
last_used: u64,
}
impl SharedFontProgramCache {
const DEFAULT_TOTAL_BYTES: usize = 48 * 1024 * 1024;
const SHARDS: usize = 8;
pub fn new(total_bytes: usize) -> Self {
let shards = (0..Self::SHARDS)
.map(|_| std::sync::Mutex::new(FontCacheShard::default()))
.collect::<Vec<_>>()
.into_boxed_slice();
Self {
shards,
per_shard_bytes: (total_bytes / Self::SHARDS).max(1),
hits: std::sync::atomic::AtomicU64::new(0),
inserts: std::sync::atomic::AtomicU64::new(0),
}
}
pub fn stats(&self) -> (u64, u64) {
use std::sync::atomic::Ordering::Relaxed;
(self.hits.load(Relaxed), self.inserts.load(Relaxed))
}
fn shard(&self, key: &FontProgramKey) -> &std::sync::Mutex<FontCacheShard> {
&self.shards[(key.h0 >> 32) as usize % Self::SHARDS]
}
fn get(&self, key: &FontProgramKey) -> Option<FontProgram> {
let mut guard = lock_unpoisoned(self.shard(key));
let shard = &mut *guard;
shard.clock += 1;
let clock = shard.clock;
let entry = shard.map.get_mut(key)?;
shard.lru.remove(&entry.last_used);
entry.last_used = clock;
shard.lru.insert(clock, *key);
let program = entry.program.clone();
drop(guard);
self.hits.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
Some(program)
}
fn insert(&self, key: FontProgramKey, program: FontProgram, charge: usize) {
self.inserts
.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut shard = lock_unpoisoned(self.shard(&key));
shard.clock += 1;
let clock = shard.clock;
if let Some(prev) = shard.map.insert(
key,
FontCacheEntry {
program,
charge,
last_used: clock,
},
) {
shard.bytes = shard.bytes.saturating_sub(prev.charge);
shard.lru.remove(&prev.last_used);
}
shard.lru.insert(clock, key);
shard.bytes += charge;
while shard.bytes > self.per_shard_bytes && shard.map.len() > 1 {
let Some((_, victim)) = shard.lru.pop_first() else {
break;
};
if let Some(removed) = shard.map.remove(&victim) {
shard.bytes = shard.bytes.saturating_sub(removed.charge);
}
}
}
pub(crate) fn clear(&self) {
for shard in self.shards.iter() {
let mut shard = lock_unpoisoned(shard);
shard.map.clear();
shard.lru.clear();
shard.bytes = 0;
}
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.shards
.iter()
.map(|s| lock_unpoisoned(s).map.len())
.sum()
}
}
impl Default for SharedFontProgramCache {
fn default() -> Self {
Self::new(Self::DEFAULT_TOTAL_BYTES)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct GlyphCacheKey {
font: FontProgramKey,
glyph: u32,
la_bits: u64,
ld_bits: u64,
ppem_bits: u32,
sx: i16,
sy: i16,
hinted: bool,
}
#[derive(Debug)]
pub struct GlyphBitmap {
pub left: i32,
pub top: i32,
pub width: u32,
pub height: u32,
pub cov: Box<[u8]>,
}
impl GlyphBitmap {
fn charge(&self) -> usize {
self.cov.len() + std::mem::size_of::<Self>() + 64
}
}
#[derive(Debug)]
pub struct SharedGlyphCache {
shards: Box<[std::sync::Mutex<GlyphCacheShard>]>,
per_shard_bytes: usize,
inserts: std::sync::atomic::AtomicU64,
}
type GlyphHashState = foldhash::fast::SeedableRandomState;
fn glyph_hash_state() -> GlyphHashState {
use std::hash::{BuildHasher, Hasher};
let os_seed = std::collections::hash_map::RandomState::new()
.build_hasher()
.finish();
foldhash::fast::SeedableRandomState::with_seed(os_seed, foldhash::SharedSeed::global_random())
}
#[derive(Debug, Default)]
struct GlyphCacheShard {
map: HashMap<GlyphCacheKey, GlyphCacheEntry, GlyphHashState>,
bytes: usize,
clock: u64,
lru: BTreeMap<u64, GlyphCacheKey>,
hits: u64,
misses: u64,
}
#[derive(Debug)]
struct GlyphCacheEntry {
bitmap: Arc<GlyphBitmap>,
charge: usize,
last_used: u64,
}
impl SharedGlyphCache {
const DEFAULT_TOTAL_BYTES: usize = 32 * 1024 * 1024;
const SHARDS: usize = 8;
pub fn new(total_bytes: usize) -> Self {
let shards = (0..Self::SHARDS)
.map(|_| {
std::sync::Mutex::new(GlyphCacheShard {
map: HashMap::with_hasher(glyph_hash_state()),
..GlyphCacheShard::default()
})
})
.collect::<Vec<_>>()
.into_boxed_slice();
Self {
shards,
per_shard_bytes: (total_bytes / Self::SHARDS).max(1),
inserts: std::sync::atomic::AtomicU64::new(0),
}
}
pub fn stats(&self) -> (u64, u64, u64) {
use std::sync::atomic::Ordering::Relaxed;
let (mut hits, mut misses) = (0u64, 0u64);
for shard in self.shards.iter() {
let shard = lock_unpoisoned(shard);
hits += shard.hits;
misses += shard.misses;
}
(hits, misses, self.inserts.load(Relaxed))
}
fn shard(&self, key: &GlyphCacheKey) -> &std::sync::Mutex<GlyphCacheShard> {
let h = key.font.h0 ^ (key.glyph as u64).wrapping_mul(0x9E37_79B9_7F4A_7C15);
&self.shards[(h >> 29) as usize % Self::SHARDS]
}
fn get(&self, key: &GlyphCacheKey) -> Option<Arc<GlyphBitmap>> {
let mut guard = lock_unpoisoned(self.shard(key));
let shard = &mut *guard;
shard.clock += 1;
let clock = shard.clock;
let Some(entry) = shard.map.get_mut(key) else {
shard.misses += 1;
return None;
};
shard.lru.remove(&entry.last_used);
entry.last_used = clock;
shard.lru.insert(clock, *key);
let bitmap = entry.bitmap.clone();
shard.hits += 1;
Some(bitmap)
}
fn insert(&self, key: GlyphCacheKey, bitmap: Arc<GlyphBitmap>) {
use std::sync::atomic::Ordering::Relaxed;
self.inserts.fetch_add(1, Relaxed);
let charge = bitmap.charge();
let mut shard = lock_unpoisoned(self.shard(&key));
shard.clock += 1;
let clock = shard.clock;
if let Some(prev) = shard.map.insert(
key,
GlyphCacheEntry {
bitmap,
charge,
last_used: clock,
},
) {
shard.bytes = shard.bytes.saturating_sub(prev.charge);
shard.lru.remove(&prev.last_used);
}
shard.lru.insert(clock, key);
shard.bytes += charge;
while shard.bytes > self.per_shard_bytes && shard.map.len() > 1 {
let Some((_, victim)) = shard.lru.pop_first() else {
break;
};
if let Some(removed) = shard.map.remove(&victim) {
shard.bytes = shard.bytes.saturating_sub(removed.charge);
}
}
}
pub(crate) fn clear(&self) {
for shard in self.shards.iter() {
let mut shard = lock_unpoisoned(shard);
shard.map.clear();
shard.lru.clear();
shard.bytes = 0;
}
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.shards
.iter()
.map(|s| lock_unpoisoned(s).map.len())
.sum()
}
#[cfg(test)]
pub(crate) fn retained_bytes(&self) -> usize {
self.shards.iter().map(|s| lock_unpoisoned(s).bytes).sum()
}
}
impl Default for SharedGlyphCache {
fn default() -> Self {
Self::new(Self::DEFAULT_TOTAL_BYTES)
}
}
#[cfg(feature = "profiling")]
#[derive(Debug, Clone, Default)]
pub struct DecodedImageCache {
entries: Arc<std::sync::Mutex<HashMap<DecodeCacheKey, CodecSamples>>>,
}
#[cfg(feature = "profiling")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct DecodeCacheKey {
data_ptr: usize,
data_len: usize,
codec: u8,
width: u32,
height: u32,
bpc: u8,
is_mask: bool,
target: Option<(u32, u32)>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct ImageCacheKey {
h0: u64,
h1: u64,
len: usize,
codec: u8,
width: u32,
height: u32,
bpc: u8,
is_mask: bool,
space: Option<(u8, u8)>,
scale: DecodeScaleKey,
parms: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum DecodeScaleKey {
Level(u8),
Target(Option<(u32, u32)>),
}
impl ImageCacheKey {
#[allow(clippy::too_many_arguments)]
fn new(
kind: crate::page_ir::ImageCodecKind,
data: &[u8],
width: u32,
height: u32,
bpc: u8,
is_mask: bool,
space: Option<&crate::color::ColorSpaceDesc>,
parms: Option<&crate::page_ir::CodecParms>,
scale: DecodeScaleKey,
) -> Self {
let (h0, h1) = content_hash_128(data);
let space = space.map(|cs| (cs.family as u8, cs.components));
let parms_hash = match parms {
None => 0,
Some(p) => {
let scalars = [
p.k as u32 as u64,
p.columns as u64,
p.rows as u64,
(p.black_is_1 as u64)
| ((p.byte_align as u64) << 1)
| ((p.end_of_line as u64) << 2)
| ((p.end_of_block as u64) << 3),
];
let mut h: u64 = 0x9E37_79B9_7F4A_7C15;
for s in scalars {
h = (h ^ s).wrapping_mul(0xC2B2_AE3D_27D4_EB4F).rotate_left(29);
}
if let Some(globals) = p.jbig2_globals.as_deref() {
let (g0, g1) = content_hash_128(globals);
h ^= g0 ^ g1.rotate_left(17);
}
h | 1 }
};
Self {
h0,
h1,
len: data.len(),
codec: match kind {
crate::page_ir::ImageCodecKind::Dct => 0,
crate::page_ir::ImageCodecKind::Jpx => 1,
crate::page_ir::ImageCodecKind::Jbig2 => 2,
crate::page_ir::ImageCodecKind::CcittFax => 3,
},
width,
height,
bpc,
is_mask,
space,
scale,
parms: parms_hash,
}
}
}
#[derive(Debug)]
pub(crate) struct SharedImageCache {
shards: Box<[std::sync::Mutex<ImageCacheShard>]>,
total_budget_bytes: usize,
total_bytes: std::sync::Mutex<usize>,
clock: std::sync::atomic::AtomicU64,
flights: std::sync::Mutex<HashMap<ImageCacheKey, Arc<ImageDecodeFlight>>>,
hits: std::sync::atomic::AtomicU64,
misses: std::sync::atomic::AtomicU64,
inserts: std::sync::atomic::AtomicU64,
}
#[derive(Debug, Default)]
struct ImageCacheShard {
map: HashMap<ImageCacheKey, ImageCacheEntry>,
lru: BTreeMap<u64, ImageCacheKey>,
}
#[derive(Debug)]
struct ImageCacheEntry {
decoded: CodecSamples,
charge: usize,
last_used: u64,
}
#[derive(Debug)]
struct ImageDecodeFlight {
state: std::sync::Mutex<ImageDecodeFlightState>,
ready: std::sync::Condvar,
}
#[derive(Debug, Clone)]
enum ImageDecodeFlightState {
Running,
Succeeded(CodecSamples),
Failed,
}
impl ImageDecodeFlight {
fn new() -> Self {
Self {
state: std::sync::Mutex::new(ImageDecodeFlightState::Running),
ready: std::sync::Condvar::new(),
}
}
fn wait(&self) -> Option<CodecSamples> {
let mut state = lock_unpoisoned(&self.state);
while matches!(*state, ImageDecodeFlightState::Running) {
state = self
.ready
.wait(state)
.unwrap_or_else(|poisoned| poisoned.into_inner());
}
match &*state {
ImageDecodeFlightState::Succeeded(decoded) => Some(decoded.clone()),
ImageDecodeFlightState::Failed => None,
ImageDecodeFlightState::Running => unreachable!("wait loop exits only when resolved"),
}
}
}
enum ImageCacheProbe<'a> {
Hit(CodecSamples),
Leader(ImageDecodeFlightGuard<'a>),
}
struct ImageDecodeFlightGuard<'a> {
cache: &'a SharedImageCache,
key: ImageCacheKey,
flight: Arc<ImageDecodeFlight>,
resolved: bool,
}
impl ImageDecodeFlightGuard<'_> {
fn complete(mut self, decoded: &CodecSamples) {
self.cache.insert(self.key, decoded.clone());
self.cache
.resolve_flight(self.key, &self.flight, Some(decoded.clone()));
self.resolved = true;
}
}
impl Drop for ImageDecodeFlightGuard<'_> {
fn drop(&mut self) {
if !self.resolved {
self.cache.resolve_flight(self.key, &self.flight, None);
}
}
}
impl SharedImageCache {
const DEFAULT_TOTAL_BYTES: usize = 96 * 1024 * 1024;
const SHARDS: usize = 8;
pub(crate) fn new(total_bytes: usize) -> Self {
let shards = (0..Self::SHARDS)
.map(|_| std::sync::Mutex::new(ImageCacheShard::default()))
.collect::<Vec<_>>()
.into_boxed_slice();
Self {
shards,
total_budget_bytes: total_bytes,
total_bytes: std::sync::Mutex::new(0),
clock: std::sync::atomic::AtomicU64::new(0),
flights: std::sync::Mutex::new(HashMap::new()),
hits: std::sync::atomic::AtomicU64::new(0),
misses: std::sync::atomic::AtomicU64::new(0),
inserts: std::sync::atomic::AtomicU64::new(0),
}
}
pub(crate) fn stats(&self) -> (u64, u64, u64) {
use std::sync::atomic::Ordering::Relaxed;
(
self.hits.load(Relaxed),
self.misses.load(Relaxed),
self.inserts.load(Relaxed),
)
}
fn shard(&self, key: &ImageCacheKey) -> &std::sync::Mutex<ImageCacheShard> {
&self.shards[(key.h0 >> 32) as usize % Self::SHARDS]
}
fn get(&self, key: &ImageCacheKey) -> Option<CodecSamples> {
self.get_inner(key, true)
}
fn get_inner(&self, key: &ImageCacheKey, record_stats: bool) -> Option<CodecSamples> {
use std::sync::atomic::Ordering::Relaxed;
let mut guard = lock_unpoisoned(self.shard(key));
let shard = &mut *guard;
let clock = self.clock.fetch_add(1, Relaxed);
let Some(entry) = shard.map.get_mut(key) else {
drop(guard);
if record_stats {
self.misses.fetch_add(1, Relaxed);
}
return None;
};
shard.lru.remove(&entry.last_used);
entry.last_used = clock;
shard.lru.insert(clock, *key);
let decoded = entry.decoded.clone();
drop(guard);
if record_stats {
self.hits.fetch_add(1, Relaxed);
}
Some(decoded)
}
fn probe(&self, key: ImageCacheKey) -> ImageCacheProbe<'_> {
loop {
if let Some(decoded) = self.get(&key) {
return ImageCacheProbe::Hit(decoded);
}
let flight = {
let mut flights = lock_unpoisoned(&self.flights);
if let Some(flight) = flights.get(&key) {
Arc::clone(flight)
} else if let Some(decoded) = self.get_inner(&key, false) {
return ImageCacheProbe::Hit(decoded);
} else {
let flight = Arc::new(ImageDecodeFlight::new());
flights.insert(key, Arc::clone(&flight));
return ImageCacheProbe::Leader(ImageDecodeFlightGuard {
cache: self,
key,
flight,
resolved: false,
});
}
};
if let Some(decoded) = flight.wait() {
return ImageCacheProbe::Hit(decoded);
}
}
}
fn resolve_flight(
&self,
key: ImageCacheKey,
flight: &Arc<ImageDecodeFlight>,
decoded: Option<CodecSamples>,
) {
*lock_unpoisoned(&flight.state) = match decoded {
Some(decoded) => ImageDecodeFlightState::Succeeded(decoded),
None => ImageDecodeFlightState::Failed,
};
{
let mut flights = lock_unpoisoned(&self.flights);
if flights
.get(&key)
.is_some_and(|current| Arc::ptr_eq(current, flight))
{
flights.remove(&key);
}
}
flight.ready.notify_all();
}
fn insert(&self, key: ImageCacheKey, decoded: CodecSamples) {
use std::sync::atomic::Ordering::Relaxed;
self.inserts.fetch_add(1, Relaxed);
let charge = decoded
.samples
.len()
.saturating_add(decoded.alpha.as_ref().map_or(0, |alpha| alpha.len()))
.saturating_add(std::mem::size_of::<ImageCacheEntry>())
.saturating_add(64);
if charge > self.total_budget_bytes {
return;
}
let mut total_bytes = lock_unpoisoned(&self.total_bytes);
let clock = self.clock.fetch_add(1, Relaxed);
{
let mut shard = lock_unpoisoned(self.shard(&key));
if let Some(previous) = shard.map.insert(
key,
ImageCacheEntry {
decoded,
charge,
last_used: clock,
},
) {
*total_bytes = total_bytes.saturating_sub(previous.charge);
shard.lru.remove(&previous.last_used);
}
shard.lru.insert(clock, key);
*total_bytes = total_bytes.saturating_add(charge);
}
while *total_bytes > self.total_budget_bytes {
let mut victim: Option<(usize, u64, ImageCacheKey)> = None;
for (index, shard) in self.shards.iter().enumerate() {
let shard = lock_unpoisoned(shard);
if let Some((&clock, &key)) = shard.lru.first_key_value()
&& victim.is_none_or(|(_, oldest, _)| clock < oldest)
{
victim = Some((index, clock, key));
}
}
let Some((index, clock, key)) = victim else {
break;
};
let mut shard = lock_unpoisoned(&self.shards[index]);
if shard
.map
.get(&key)
.is_some_and(|entry| entry.last_used == clock)
{
shard.lru.remove(&clock);
if let Some(removed) = shard.map.remove(&key) {
*total_bytes = total_bytes.saturating_sub(removed.charge);
}
}
}
}
pub(crate) fn clear(&self) {
let mut total_bytes = lock_unpoisoned(&self.total_bytes);
for shard in self.shards.iter() {
let mut shard = lock_unpoisoned(shard);
shard.map.clear();
shard.lru.clear();
}
*total_bytes = 0;
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
self.shards
.iter()
.map(|s| lock_unpoisoned(s).map.len())
.sum()
}
pub(crate) fn retained_bytes(&self) -> usize {
*lock_unpoisoned(&self.total_bytes)
}
}
impl Default for SharedImageCache {
fn default() -> Self {
Self::new(Self::DEFAULT_TOTAL_BYTES)
}
}
#[derive(Debug, Clone)]
pub struct PreparedShading {
pub kind: ShadingSpanKind,
pub inv: Matrix,
pub ramp: Vec<[u8; 4]>,
pub extend: [bool; 2],
pub background: Option<[u8; 4]>,
pub bbox: Option<[f32; 4]>,
}
#[derive(Debug, Clone, Copy)]
pub enum ShadingSpanKind {
Axial {
p0: [f64; 2],
d: [f64; 2],
dd: f64,
},
Radial {
c0: [f64; 3],
c1: [f64; 3],
},
Grid {
domain: [f64; 4],
gw: usize,
gh: usize,
},
Layer {
x0: i32,
y0: i32,
w: usize,
h: usize,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DrawClass {
OpaqueRect,
SolidPath,
}
#[derive(Debug, Clone)]
pub struct PreparedCommand {
pub origin: crate::page_ir::PaintOrigin,
pub class: DrawClass,
pub subpath_range: (u32, u32),
pub rule: FillRule,
pub rgb: [u8; 3],
pub premul: [u8; 4],
pub alpha: u8,
pub opaque: bool,
pub bounds: DeviceRect,
pub clip: Option<u32>,
pub clip_has_mask: bool,
pub blend: crate::page_ir::BlendMode,
pub shading: Option<Box<PreparedShading>>,
pub stencil: Option<Box<crate::render_cpu::image::PreparedImage>>,
}
#[derive(Debug, Clone)]
pub struct GlyphPlacement {
pub bitmap: Arc<GlyphBitmap>,
pub dx: i32,
pub dy: i32,
}
#[derive(Debug, Clone)]
pub struct PreparedGlyphRun {
pub origin: crate::page_ir::PaintOrigin,
pub placements: Vec<GlyphPlacement>,
pub rgb: [u8; 3],
pub alpha: u8,
pub opaque: bool,
pub bounds: DeviceRect,
pub clip: Option<u32>,
pub clip_has_mask: bool,
pub blend: crate::page_ir::BlendMode,
pub shading: Option<Box<PreparedShading>>,
}
#[derive(Debug, Clone)]
pub struct PreparedClip {
pub parent: Option<u32>,
pub bounds: DeviceRect,
pub mask_bounds: DeviceRect,
pub kind: ClipKind,
pub has_mask: bool,
pub mask_source: Option<u32>,
}
#[derive(Debug, Clone)]
pub enum ClipKind {
Rect,
Path {
subpath_range: (u32, u32),
rule: FillRule,
},
}
#[derive(Debug, Clone)]
pub struct PreparedGroup {
pub bounds: DeviceRect,
pub opacity: u8,
pub blend: crate::page_ir::BlendMode,
pub isolated: bool,
pub knockout: bool,
}
#[derive(Debug, Clone)]
pub struct PreparedTiling {
pub origin: crate::page_ir::PaintOrigin,
pub bounds: DeviceRect,
pub clip: Option<u32>,
pub clip_has_mask: bool,
pub fill_subpaths: (u32, u32),
pub fill_rule: FillRule,
pub alpha: u8,
pub cell: Arc<CompiledPage>,
pub pattern_to_device: Matrix,
pub uncolored: bool,
pub under: [u8; 4],
pub color_policy: crate::render_api::RenderColorPolicy,
pub tiles: Vec<Matrix>,
pub blend: crate::page_ir::BlendMode,
pub stencil: Option<Box<crate::render_cpu::image::PreparedImage>>,
}
#[derive(Debug, Clone)]
pub enum PreparedOp {
Draw(PreparedCommand),
GlyphRun(Box<PreparedGlyphRun>),
TiledFill(Box<PreparedTiling>),
Image(Box<crate::render_cpu::image::PreparedImage>),
BeginGroup {
group: PreparedGroup,
end: u32,
},
EndGroup,
PushSoftMask {
kind: crate::page_ir::MaskKind,
transfer: Option<crate::page_ir::TransferLut>,
content_end: u32,
bounds: DeviceRect,
},
PushSoftMaskNone,
PopSoftMask,
}
#[derive(Debug, Default)]
pub struct RenderDiagnostics {
degraded_draws: std::cell::Cell<u32>,
notes: std::cell::RefCell<Vec<String>>,
}
impl RenderDiagnostics {
const MAX_NOTES: usize = 32;
pub(crate) fn note_degraded(&self, reason: String) {
self.degraded_draws.set(self.degraded_draws.get() + 1);
let mut notes = self.notes.borrow_mut();
if notes.len() < Self::MAX_NOTES {
notes.push(reason);
}
}
pub fn degraded_draws(&self) -> u32 {
self.degraded_draws.get()
}
pub fn notes(&self) -> std::cell::Ref<'_, Vec<String>> {
self.notes.borrow()
}
}
#[derive(Debug)]
pub struct CpuPreparedPage {
pub size: DeviceSize,
pub ops: Vec<PreparedOp>,
pub clips: Vec<PreparedClip>,
pub points: Vec<[f32; 2]>,
pub subpaths: Vec<(usize, usize)>,
pub codecs: crate::image::CodecRegistry,
pub decode_limits: crate::image::DecodeLimits,
pub hinting: crate::font::HintingPolicy,
pub color_policy: crate::render_api::RenderColorPolicy,
pub diagnostics: RenderDiagnostics,
pub(crate) image_cache: Option<Arc<SharedImageCache>>,
pub(crate) decode_floor: Option<Matrix>,
pub(crate) sanity_extent: f32,
pub(crate) rows: (u32, u32),
pub(crate) op_extent: Option<(i32, i32)>,
pub(crate) strip_decodes: Option<Arc<StripDecodes>>,
#[cfg(feature = "profiling")]
pub(crate) profile: std::cell::RefCell<crate::profiling::ProfileReport>,
#[cfg(feature = "profiling")]
pub(crate) decode_cache: Option<DecodedImageCache>,
#[cfg(feature = "profiling")]
pub(crate) lower_prof: LowerProf,
}
impl CpuPreparedPage {
#[cfg(feature = "profiling")]
pub(crate) fn profile_report(&self) -> crate::profiling::ProfileReport {
self.profile.borrow().clone()
}
}
#[cfg(feature = "profiling")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(usize)]
pub(crate) enum LowerBucket {
State = 0,
Clip,
FillFlatten,
FillFinish,
StrokeFlatten,
StrokeExpand,
StrokeFinish,
Glyph,
Image,
Other,
Census,
}
#[cfg(feature = "profiling")]
const LOWER_BUCKETS: usize = 11;
#[cfg(feature = "profiling")]
#[derive(Debug, Clone, Default)]
pub(crate) struct LowerProf {
disabled: bool,
lap: Option<crate::profiling::Lap>,
ns: [u64; LOWER_BUCKETS],
clock_reads: u64,
fill_ops: u64,
stroke_ops: u64,
clip_ops: u64,
fill_lines: u64,
fill_curves: u64,
fill_points: u64,
fill_curve_segments_adaptive: u64,
fill_curve_bins: [u64; 6],
clip_rects: u64,
clip_paths: u64,
clip_lines: u64,
clip_curves: u64,
clip_path_points: u64,
stroke_dashed_ops: u64,
stroke_lines: u64,
stroke_curves: u64,
stroke_curve_segments_adaptive: u64,
stroke_polylines: u64,
stroke_centerline_points: u64,
stroke_dash_pieces: u64,
stroke_out_subpaths: u64,
stroke_out_points: u64,
stroke_quads: u64,
stroke_tris: u64,
stroke_disks: u64,
stroke_other_polys: u64,
stroke_join_round: u64,
stroke_join_miter: u64,
stroke_join_bevel: u64,
stroke_hw_bins: [u64; 4],
stroke_vertices_interior: u64,
stroke_vertices_smooth: u64,
cull_fill_insane: u64,
cull_fill_clipped: u64,
cull_fill_clipped_points: u64,
cull_stroke_insane: u64,
cull_stroke_clipped: u64,
cull_stroke_clipped_points: u64,
}
#[cfg(feature = "profiling")]
impl LowerProf {
#[inline]
pub(crate) fn lap(&mut self, bucket: LowerBucket) {
if self.disabled {
return;
}
match self.lap.as_mut() {
Some(lap) => {
self.ns[bucket as usize] += lap.lap_ns();
self.clock_reads += 1;
}
None => self.lap = Some(crate::profiling::Lap::start()),
}
}
fn adaptive_segments(ctm: Matrix, p0: Point, c1: Point, c2: Point, p3: Point) -> u64 {
const TOLERANCE_PX: f64 = 0.125;
let dev = |dx: f64, dy: f64| {
let x = ctm.a * dx + ctm.c * dy;
let y = ctm.b * dx + ctm.d * dy;
(x * x + y * y).sqrt()
};
let d1 = dev(p0.x - 2.0 * c1.x + c2.x, p0.y - 2.0 * c1.y + c2.y);
let d2 = dev(c1.x - 2.0 * c2.x + p3.x, c1.y - 2.0 * c2.y + p3.y);
let d = d1.max(d2);
if !d.is_finite() {
return CURVE_SEGMENTS as u64;
}
((0.75 * d / TOLERANCE_PX).sqrt().ceil() as u64).clamp(1, 256)
}
fn path_census(path: &PathData, ctm: Matrix) -> (u64, u64, u64, [u64; 6]) {
let (mut lines, mut curves, mut adaptive) = (0u64, 0u64, 0u64);
let mut bins = [0u64; 6];
let mut pt = 0usize;
let mut last = Point::default();
for verb in path.verbs.iter() {
match verb {
PathVerb::MoveTo => {
if let Some(p) = path.points.get(pt) {
last = *p;
}
pt += 1;
}
PathVerb::LineTo => {
lines += 1;
if let Some(p) = path.points.get(pt) {
last = *p;
}
pt += 1;
}
PathVerb::CurveTo => {
curves += 1;
if let (Some(c1), Some(c2), Some(p3)) = (
path.points.get(pt),
path.points.get(pt + 1),
path.points.get(pt + 2),
) {
let n = Self::adaptive_segments(ctm, last, *c1, *c2, *p3);
adaptive += n;
let bin = match n {
1 => 0,
2 => 1,
3..=4 => 2,
5..=8 => 3,
9..=16 => 4,
_ => 5,
};
bins[bin] += 1;
last = *p3;
}
pt += 3;
}
PathVerb::Close => {}
}
}
(lines, curves, adaptive, bins)
}
fn vertex_census(&mut self, polylines: &[(Vec<[f32; 2]>, bool)], hw: f32) {
const TOLERANCE_PX: f64 = 0.125;
let hw = f64::from(hw);
for (poly, closed) in polylines {
let n = poly.len();
self.stroke_polylines += 1;
self.stroke_centerline_points += n as u64;
if n < 3 {
continue;
}
let range = if *closed { 0..n } else { 1..n - 1 };
for i in range {
let prev = poly[(i + n - 1) % n];
let v = poly[i];
let next = poly[(i + 1) % n];
let (ax, ay) = (f64::from(v[0] - prev[0]), f64::from(v[1] - prev[1]));
let (bx, by) = (f64::from(next[0] - v[0]), f64::from(next[1] - v[1]));
let (la, lb) = ((ax * ax + ay * ay).sqrt(), (bx * bx + by * by).sqrt());
self.stroke_vertices_interior += 1;
if la <= 1e-12 || lb <= 1e-12 {
continue;
}
let c = ((ax * bx + ay * by) / (la * lb)).clamp(-1.0, 1.0);
let q = (1.0 + c) / 2.0;
let ratio = TOLERANCE_PX / hw.max(1e-9);
let spread_ok = (1.0 - q) * (1.0 - q) <= ratio * ratio * q;
let min_len = la.min(lb);
let radius_ok =
c > -1.0 && hw * hw * (1.0 - c) / (1.0 + c) <= 0.25 * min_len * min_len;
if spread_ok && radius_ok {
self.stroke_vertices_smooth += 1;
}
}
}
}
fn stroke_output_census(&mut self, subpaths: &[(usize, usize)]) {
for &(start, end) in subpaths {
let n = end - start;
self.stroke_out_subpaths += 1;
self.stroke_out_points += n as u64;
match n {
4 => self.stroke_quads += 1,
3 => self.stroke_tris += 1,
16 => self.stroke_disks += 1,
_ => self.stroke_other_polys += 1,
}
}
}
fn flush_into(&mut self, out: &mut crate::profiling::ProfileReport) {
const BUCKET_NAMES: [&str; LOWER_BUCKETS] = [
"lower.x.state",
"lower.x.clip",
"lower.x.fill_flatten",
"lower.x.fill_finish",
"lower.x.stroke_flatten",
"lower.x.stroke_expand",
"lower.x.stroke_finish",
"lower.x.glyph",
"lower.x.image",
"lower.x.other",
"lower.x.census",
];
for (name, ns) in BUCKET_NAMES.iter().zip(self.ns) {
if ns != 0 {
out.add_duration(name, std::time::Duration::from_nanos(ns));
}
}
let counters: [(&'static str, u64); 45] = [
("lower.clock_reads", self.clock_reads),
("lower.in.fill_ops", self.fill_ops),
("lower.in.stroke_ops", self.stroke_ops),
("lower.in.clip_ops", self.clip_ops),
("lower.fill.lines", self.fill_lines),
("lower.fill.curves", self.fill_curves),
("lower.fill.points", self.fill_points),
(
"lower.fill.curve_segments_adaptive",
self.fill_curve_segments_adaptive,
),
("lower.fill.curves_n1", self.fill_curve_bins[0]),
("lower.fill.curves_n2", self.fill_curve_bins[1]),
("lower.fill.curves_n3_4", self.fill_curve_bins[2]),
("lower.fill.curves_n5_8", self.fill_curve_bins[3]),
("lower.fill.curves_n9_16", self.fill_curve_bins[4]),
("lower.fill.curves_n_gt16", self.fill_curve_bins[5]),
("lower.clip.rects", self.clip_rects),
("lower.clip.paths", self.clip_paths),
("lower.clip.lines", self.clip_lines),
("lower.clip.curves", self.clip_curves),
("lower.clip.path_points", self.clip_path_points),
("lower.stroke.dashed_ops", self.stroke_dashed_ops),
("lower.stroke.lines", self.stroke_lines),
("lower.stroke.curves", self.stroke_curves),
(
"lower.stroke.curve_segments_adaptive",
self.stroke_curve_segments_adaptive,
),
("lower.stroke.polylines", self.stroke_polylines),
(
"lower.stroke.centerline_points",
self.stroke_centerline_points,
),
("lower.stroke.dash_pieces", self.stroke_dash_pieces),
("lower.stroke.out_subpaths", self.stroke_out_subpaths),
("lower.stroke.out_points", self.stroke_out_points),
("lower.stroke.quads", self.stroke_quads),
("lower.stroke.tris", self.stroke_tris),
("lower.stroke.disks", self.stroke_disks),
("lower.stroke.other_polys", self.stroke_other_polys),
("lower.stroke.join_round_ops", self.stroke_join_round),
("lower.stroke.join_miter_ops", self.stroke_join_miter),
("lower.stroke.join_bevel_ops", self.stroke_join_bevel),
("lower.stroke.hw_le_0_5px_ops", self.stroke_hw_bins[0]),
("lower.stroke.hw_le_1_6px_ops", self.stroke_hw_bins[1]),
("lower.stroke.hw_le_6_5px_ops", self.stroke_hw_bins[2]),
("lower.stroke.hw_gt_6_5px_ops", self.stroke_hw_bins[3]),
(
"lower.stroke.vertices_interior",
self.stroke_vertices_interior,
),
("lower.stroke.vertices_smooth", self.stroke_vertices_smooth),
("lower.cull.fill_insane", self.cull_fill_insane),
("lower.cull.fill_clipped", self.cull_fill_clipped),
(
"lower.cull.fill_clipped_points",
self.cull_fill_clipped_points,
),
("lower.cull.stroke_clipped", self.cull_stroke_clipped),
];
for (name, count) in counters {
if count != 0 {
out.increment(name, count);
}
}
if self.cull_stroke_insane != 0 {
out.increment("lower.cull.stroke_insane", self.cull_stroke_insane);
}
if self.cull_stroke_clipped_points != 0 {
out.increment(
"lower.cull.stroke_clipped_points",
self.cull_stroke_clipped_points,
);
}
*self = Self::default();
}
}
const CURVE_SEGMENTS: usize = 16;
#[cfg_attr(not(feature = "profiling"), allow(dead_code))]
pub fn lower(
page: &CompiledPage,
base: Matrix,
size: DeviceSize,
codecs: &crate::image::CodecRegistry,
decode_limits: &crate::image::DecodeLimits,
hinting: crate::font::HintingPolicy,
) -> CpuPreparedPage {
lower_impl(
page,
base,
size,
codecs,
decode_limits,
hinting,
crate::render_api::RenderColorPolicy::Original,
None,
None,
None,
None,
None,
false,
None,
#[cfg(feature = "profiling")]
None,
#[cfg(feature = "profiling")]
true,
)
}
pub(crate) fn lower_cell(
page: &CompiledPage,
base: Matrix,
size: DeviceSize,
outer: &CpuPreparedPage,
color_policy: crate::render_api::RenderColorPolicy,
font_cache: &mut FontProgramCache,
) -> CpuPreparedPage {
lower_impl(
page,
base,
size,
&outer.codecs,
&outer.decode_limits,
outer.hinting,
color_policy,
Some(font_cache),
None,
None,
outer.image_cache.as_ref(),
outer.decode_floor,
false,
None,
#[cfg(feature = "profiling")]
outer.decode_cache.clone(),
#[cfg(feature = "profiling")]
false,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn lower_with_font_cache(
page: &CompiledPage,
base: Matrix,
size: DeviceSize,
codecs: &crate::image::CodecRegistry,
decode_limits: &crate::image::DecodeLimits,
hinting: crate::font::HintingPolicy,
color_policy: crate::render_api::RenderColorPolicy,
font_cache: &mut FontProgramCache,
shared_fonts: Option<&SharedFontProgramCache>,
shared_glyphs: Option<&SharedGlyphCache>,
shared_images: Option<&Arc<SharedImageCache>>,
decode_floor: Option<Matrix>,
sink: Option<&mut LowerSink<'_>>,
) -> CpuPreparedPage {
lower_impl(
page,
base,
size,
codecs,
decode_limits,
hinting,
color_policy,
Some(font_cache),
shared_fonts,
shared_glyphs,
shared_images,
decode_floor,
false,
sink,
#[cfg(feature = "profiling")]
None,
#[cfg(feature = "profiling")]
true,
)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn lower_for_external_raster(
page: &CompiledPage,
base: Matrix,
size: DeviceSize,
codecs: &crate::image::CodecRegistry,
decode_limits: &crate::image::DecodeLimits,
hinting: crate::font::HintingPolicy,
color_policy: crate::render_api::RenderColorPolicy,
font_cache: &mut FontProgramCache,
shared_fonts: Option<&SharedFontProgramCache>,
shared_images: Option<&Arc<SharedImageCache>>,
) -> CpuPreparedPage {
lower_impl(
page,
base,
size,
codecs,
decode_limits,
hinting,
color_policy,
Some(font_cache),
shared_fonts,
None,
shared_images,
None,
true,
None,
#[cfg(feature = "profiling")]
None,
#[cfg(feature = "profiling")]
true,
)
}
#[cfg(feature = "profiling")]
pub fn lower_with_decode_cache(
page: &CompiledPage,
base: Matrix,
size: DeviceSize,
codecs: &crate::image::CodecRegistry,
decode_limits: &crate::image::DecodeLimits,
hinting: crate::font::HintingPolicy,
decode_cache: DecodedImageCache,
) -> CpuPreparedPage {
lower_impl(
page,
base,
size,
codecs,
decode_limits,
hinting,
crate::render_api::RenderColorPolicy::Original,
None,
None,
None,
None,
None,
false,
None,
Some(decode_cache),
#[cfg(feature = "profiling")]
true,
)
}
#[cfg(feature = "profiling")]
pub fn decode_page(
page: &CompiledPage,
codecs: &crate::image::CodecRegistry,
decode_limits: &crate::image::DecodeLimits,
hinting: crate::font::HintingPolicy,
) -> crate::profiling::ProfileReport {
let start = std::time::Instant::now();
let out = CpuPreparedPage {
size: DeviceSize {
width: 1,
height: 1,
},
ops: Vec::new(),
clips: Vec::new(),
points: Vec::new(),
subpaths: Vec::new(),
codecs: codecs.clone(),
decode_limits: decode_limits.clone(),
hinting,
color_policy: crate::render_api::RenderColorPolicy::Original,
diagnostics: RenderDiagnostics::default(),
image_cache: None,
decode_floor: None,
sanity_extent: 1.0,
rows: (0, u32::MAX),
op_extent: None,
strip_decodes: None,
profile: std::cell::RefCell::new(crate::profiling::ProfileReport::new()),
decode_cache: None,
lower_prof: Default::default(),
};
let mut seen = HashSet::new();
decode_page_images(page, &out, &mut seen);
let mut profile = out.profile_report();
profile.add_duration("codec.decode_only.total", start.elapsed());
profile.increment("codec.decode_only.unique_payloads", seen.len() as u64);
profile
}
#[cfg(feature = "profiling")]
fn decode_page_images(
page: &CompiledPage,
out: &CpuPreparedPage,
seen: &mut HashSet<DecodeCacheKey>,
) {
for image in page.images.iter() {
decode_unique_payload(
out,
seen,
image.codec,
image.codec_data.as_deref(),
image.width,
image.height,
image.bits_per_component,
image.is_stencil,
image.codec_parms.clone(),
);
if let Some(mask) = image.smask.as_deref() {
decode_unique_mask(out, seen, mask);
}
if let Some(crate::page_ir::ImageMask::Stencil(mask)) = image.mask.as_ref() {
decode_unique_mask(out, seen, mask);
}
}
for tiling in page.tilings.iter() {
decode_page_images(&tiling.cell, out, seen);
}
}
#[cfg(feature = "profiling")]
fn decode_unique_mask(
out: &CpuPreparedPage,
seen: &mut HashSet<DecodeCacheKey>,
mask: &crate::page_ir::ImageSMask,
) {
decode_unique_payload(
out,
seen,
mask.codec,
mask.codec_data.as_deref(),
mask.width,
mask.height,
mask.bits_per_component,
true,
mask.codec_parms.clone(),
);
}
#[cfg(feature = "profiling")]
#[allow(clippy::too_many_arguments)]
fn decode_unique_payload(
out: &CpuPreparedPage,
seen: &mut HashSet<DecodeCacheKey>,
kind: Option<crate::page_ir::ImageCodecKind>,
data: Option<&[u8]>,
width: u32,
height: u32,
bpc: u8,
is_mask: bool,
parms: Option<crate::page_ir::CodecParms>,
) {
let (Some(kind), Some(data)) = (kind, data) else {
return;
};
let key = DecodeCacheKey {
data_ptr: data.as_ptr() as usize,
data_len: data.len(),
codec: match kind {
crate::page_ir::ImageCodecKind::Dct => 0,
crate::page_ir::ImageCodecKind::Jpx => 1,
crate::page_ir::ImageCodecKind::Jbig2 => 2,
crate::page_ir::ImageCodecKind::CcittFax => 3,
},
width,
height,
bpc,
is_mask,
target: None,
};
if seen.insert(key) {
if let Some(decoded) = decode_codec_samples(
out, kind, data, width, height, bpc, is_mask, parms, None, None,
) {
out.profile
.borrow_mut()
.release_bytes(decoded.samples.len() as u64);
}
}
}
pub(crate) struct LowerSink<'a> {
pub chunk_bytes: usize,
pub image_chunk_bytes: usize,
pub rows: (u32, u32),
pub extents: Option<&'a mut OpExtents>,
pub decodes: Option<Arc<StripDecodes>>,
pub flush: &'a mut dyn FnMut(&CpuPreparedPage, &[u32]) -> bool,
}
pub(crate) fn lower_chunk_bytes() -> usize {
lower_chunk_override().unwrap_or(16 << 20)
}
pub(crate) fn lower_image_chunk_bytes() -> usize {
lower_chunk_override().unwrap_or(SharedImageCache::DEFAULT_TOTAL_BYTES)
}
fn lower_chunk_override() -> Option<usize> {
use std::sync::OnceLock;
static BYTES: OnceLock<Option<usize>> = OnceLock::new();
*BYTES.get_or_init(|| {
std::env::var("PDF_RENDERER_LOWER_CHUNK_MB")
.ok()
.and_then(|v| v.trim().parse::<usize>().ok())
.map(|mb| mb.saturating_mul(1 << 20))
})
}
#[derive(Debug, Default)]
pub(crate) struct OpExtents {
complete: bool,
rows: Vec<(i32, i32)>,
}
#[derive(Debug, Default)]
pub(crate) struct StripDecodes {
held: std::sync::Mutex<HashMap<ImageCacheKey, (CodecSamples, i32)>>,
}
impl StripDecodes {
fn get(&self, key: &ImageCacheKey) -> Option<CodecSamples> {
lock_unpoisoned(&self.held)
.get(key)
.map(|(decoded, _)| decoded.clone())
}
fn hold(&self, key: ImageCacheKey, decoded: &CodecSamples, until_row: i32) {
let mut held = lock_unpoisoned(&self.held);
let entry = held
.entry(key)
.or_insert_with(|| (decoded.clone(), until_row));
entry.1 = entry.1.max(until_row);
}
pub(crate) fn release_through(&self, end_row: u32) {
lock_unpoisoned(&self.held).retain(|_, (_, until)| i64::from(*until) > i64::from(end_row));
}
#[cfg(test)]
pub(crate) fn len(&self) -> usize {
lock_unpoisoned(&self.held).len()
}
}
fn hold_for_later_strips(out: &CpuPreparedPage, key: ImageCacheKey, decoded: &CodecSamples) {
if let (Some(held), Some((_, end))) = (&out.strip_decodes, out.op_extent)
&& out.rows.1 != u32::MAX
&& i64::from(end) > i64::from(out.rows.1)
{
held.hold(key, decoded, end);
}
}
fn note_extent(out: &mut CpuPreparedPage, bounds: DeviceRect) {
if bounds.width == 0 || bounds.height == 0 {
return;
}
let (first, end) = (bounds.y, bounds.y.saturating_add(bounds.height as i32));
out.op_extent = Some(match out.op_extent {
Some((lo, hi)) => (lo.min(first), hi.max(end)),
None => (first, end),
});
}
fn row_window(out: &CpuPreparedPage) -> DeviceRect {
let first = out.rows.0.min(out.size.height);
let end = out.rows.1.min(out.size.height).max(first);
DeviceRect {
x: 0,
y: first as i32,
width: out.size.width,
height: end - first,
}
}
fn arena_len_bytes(out: &CpuPreparedPage) -> usize {
out.points.len() * std::mem::size_of::<[f32; 2]>()
+ out.subpaths.len() * std::mem::size_of::<(usize, usize)>()
}
fn retain_clip_geometry(out: &mut CpuPreparedPage) {
let mut points: Vec<[f32; 2]> = Vec::new();
let mut subpaths: Vec<(usize, usize)> = Vec::new();
let mut moved: HashMap<(u32, u32), (u32, u32)> = HashMap::new();
for clip in &mut out.clips {
let ClipKind::Path { subpath_range, .. } = &mut clip.kind else {
continue;
};
let old = *subpath_range;
let new = *moved.entry(old).or_insert_with(|| {
let start = subpaths.len() as u32;
for &(first, last) in &out.subpaths[old.0 as usize..old.1 as usize] {
let base = points.len();
points.extend_from_slice(&out.points[first..last]);
subpaths.push((base, base + (last - first)));
}
(start, subpaths.len() as u32)
});
*subpath_range = new;
}
out.points = points;
out.subpaths = subpaths;
}
#[allow(clippy::too_many_arguments)]
fn lower_impl(
page: &CompiledPage,
base: Matrix,
size: DeviceSize,
codecs: &crate::image::CodecRegistry,
decode_limits: &crate::image::DecodeLimits,
hinting: crate::font::HintingPolicy,
color_policy: crate::render_api::RenderColorPolicy,
mut font_cache: Option<&mut FontProgramCache>,
shared_fonts: Option<&SharedFontProgramCache>,
shared_glyphs: Option<&SharedGlyphCache>,
shared_images: Option<&Arc<SharedImageCache>>,
decode_floor: Option<Matrix>,
split_glyph_draws: bool,
mut sink: Option<&mut LowerSink<'_>>,
#[cfg(feature = "profiling")] decode_cache: Option<DecodedImageCache>,
#[cfg(feature = "profiling")] prof_enabled: bool,
) -> CpuPreparedPage {
#[cfg(feature = "profiling")]
let lower_start = std::time::Instant::now();
let mut out = CpuPreparedPage {
size,
ops: Vec::with_capacity(page.operations.len()),
clips: Vec::new(),
points: Vec::new(),
subpaths: Vec::new(),
codecs: codecs.clone(),
decode_limits: decode_limits.clone(),
hinting,
color_policy,
diagnostics: RenderDiagnostics::default(),
image_cache: shared_images.cloned(),
strip_decodes: sink.as_deref().and_then(|sink| sink.decodes.clone()),
decode_floor,
sanity_extent: sanity_extent(page.bounds.crop, base, size),
rows: (0, u32::MAX),
op_extent: None,
#[cfg(feature = "profiling")]
profile: std::cell::RefCell::new(crate::profiling::ProfileReport::new()),
#[cfg(feature = "profiling")]
decode_cache,
#[cfg(feature = "profiling")]
lower_prof: LowerProf {
disabled: !prof_enabled,
..LowerProf::default()
},
};
if let Some(sink) = sink.as_deref() {
out.rows = sink.rows;
}
#[cfg(feature = "profiling")]
let mut prof_bucket = LowerBucket::State;
#[cfg(feature = "profiling")]
out.lower_prof.lap(LowerBucket::State);
let mut ctm = base;
let mut ctm_stack: Vec<Matrix> = Vec::new();
let mut clip_stack: Vec<u32> = Vec::new();
let mut clip_share = ClipShare::default();
let mut scope_stack: Vec<ScopeBuilder> = Vec::new();
let mut soft_count: u32 = 0;
let mut soft_scope: Vec<u32> = Vec::new();
let mut soft_mask_content_depth = 0_u32;
let mut soft_at_group_entry: Vec<u32> = Vec::new();
let (mut font_programs, font_page_cache_hit) = match font_cache.as_deref_mut() {
Some(cache) => cache.take_for_page(page),
None => (HashMap::new(), false),
};
#[cfg(feature = "profiling")]
if font_page_cache_hit && !font_programs.is_empty() {
let mut profile = out.profile.borrow_mut();
profile.increment("lower.font.page_cache_hits", 1);
profile.increment(
"lower.font.page_cached_programs",
font_programs.len() as u64,
);
}
#[cfg(not(feature = "profiling"))]
let _ = font_page_cache_hit;
let mut glyph_raster = crate::render_cpu::raster::RasterKernel::default();
#[cfg(feature = "profiling")]
{
glyph_raster.prof.class = crate::render_cpu::raster::RasterClass::Glyph;
}
let mut glyph_font_ids: HashMap<u32, FontProgramKey> = HashMap::new();
let mut origin_stack: Vec<crate::page_ir::PaintOrigin> = Vec::new();
let mut retained_arena = 0usize;
let mut pending_image_bytes = 0usize;
#[cfg(feature = "profiling")]
let (mut flushed_ops, mut flushed_points, mut flushed_subpaths, mut peak_arena) =
(0u64, 0u64, 0u64, 0u64);
let mut stopped_early = false;
for (op_index, op) in page.operations.iter().enumerate() {
if out.decode_limits.is_cancelled() {
stopped_early = true;
break;
}
if let Some(sink) = sink.as_deref_mut()
&& scope_stack.is_empty()
&& !out.ops.is_empty()
&& (arena_len_bytes(&out).saturating_sub(retained_arena) > sink.chunk_bytes
|| pending_image_bytes > sink.image_chunk_bytes)
{
#[cfg(feature = "profiling")]
{
flushed_ops += out.ops.len() as u64;
flushed_points += out.points.len() as u64;
flushed_subpaths += out.subpaths.len() as u64;
peak_arena = peak_arena.max(
(out.points.capacity() * std::mem::size_of::<[f32; 2]>()
+ out.subpaths.capacity() * std::mem::size_of::<(usize, usize)>())
as u64,
);
}
if !(sink.flush)(&out, &clip_stack) {
stopped_early = true;
break;
}
out.ops.clear();
retain_clip_geometry(&mut out);
retained_arena = arena_len_bytes(&out);
pending_image_bytes = 0;
}
if matches!(
op,
DisplayOp::FillPath { .. }
| DisplayOp::StrokePath { .. }
| DisplayOp::DrawGlyphRun { .. }
| DisplayOp::DrawImage { .. }
| DisplayOp::DrawShading { .. }
) && let Some(extents) = sink.as_deref().and_then(|sink| sink.extents.as_deref())
&& extents.complete
&& let Some(&(first, end)) = extents.rows.get(op_index)
{
let window = row_window(&out);
if end <= window.y || first >= window.y.saturating_add(window.height as i32) {
continue;
}
}
out.op_extent = None;
#[cfg(feature = "profiling")]
{
out.lower_prof.lap(prof_bucket);
prof_bucket = match op {
DisplayOp::PushClip { .. } | DisplayOp::PushClipText { .. } => LowerBucket::Clip,
DisplayOp::FillPath { .. } => LowerBucket::FillFinish,
DisplayOp::StrokePath { .. } => LowerBucket::StrokeFinish,
DisplayOp::DrawGlyphRun { .. } => LowerBucket::Glyph,
DisplayOp::DrawImage { .. } => LowerBucket::Image,
DisplayOp::DrawShading { .. } => LowerBucket::Other,
_ => LowerBucket::State,
};
}
let ops_before = out.ops.len();
match op {
DisplayOp::BeginPaintOrigin(o) => origin_stack.push(*o),
DisplayOp::EndPaintOrigin => {
origin_stack.pop();
}
DisplayOp::Save => {
ctm_stack.push(ctm);
soft_scope.push(soft_count);
}
DisplayOp::Restore => {
if let Some(m) = ctm_stack.pop() {
ctm = m;
}
let target = soft_scope.pop().unwrap_or(0);
while soft_count > target {
out.ops.push(PreparedOp::PopSoftMask);
soft_count -= 1;
}
}
DisplayOp::ConcatTransform(m) => ctm = m.then(ctm),
DisplayOp::PushClip { path, rule } => {
push_clip(
&mut out,
&mut clip_stack,
&mut clip_share,
&page.paths[path.index()],
ctm,
*rule,
);
}
DisplayOp::PushClipText { runs } => {
push_text_clip(
&mut out,
&mut clip_stack,
&mut clip_share,
runs,
page,
ctm,
&mut font_programs,
shared_fonts,
);
}
DisplayOp::PopClip => {
clip_stack.pop();
}
DisplayOp::FillPath {
path,
paint,
rule,
alpha,
blend,
} => {
let paint_policy = if soft_mask_content_depth == 0 {
out.color_policy
} else {
crate::render_api::RenderColorPolicy::Original
};
let clip = clip_stack.last().copied();
let b = match &page.paints[paint.index()] {
Paint::Solid(color) => lower_fill(
&mut out,
&page.paths[path.index()],
ctm,
*rule,
recolor(*color, paint_policy),
*alpha,
clip,
*blend,
soft_count > 0,
None,
None,
),
Paint::Shading { shading, matrix } => {
match prepare_shading(
&page.shadings[shading.index()],
matrix.then(base),
size,
true,
paint_policy,
) {
Some(sh) => lower_fill(
&mut out,
&page.paths[path.index()],
ctm,
*rule,
crate::page_ir::Color::BLACK,
*alpha,
clip,
*blend,
soft_count > 0,
Some(Box::new(sh)),
None,
),
None => None,
}
}
Paint::Pattern { tiling, matrix } => lower_tiled(
&mut out,
&page.paths[path.index()],
ctm,
*rule,
&page.tilings[tiling.index()],
matrix.then(base),
*alpha,
clip,
*blend,
paint_policy,
None,
),
};
accumulate_scope_bounds(&mut scope_stack, b);
}
DisplayOp::StrokePath {
path,
paint,
style,
alpha,
blend,
} => {
let paint_policy = if soft_mask_content_depth == 0 {
out.color_policy
} else {
crate::render_api::RenderColorPolicy::Original
};
let (color, stroke_shading) = match &page.paints[paint.index()] {
Paint::Solid(color) => (recolor(*color, paint_policy), None),
Paint::Shading { shading, matrix } => {
match prepare_shading(
&page.shadings[shading.index()],
matrix.then(base),
size,
true,
paint_policy,
) {
Some(sh) => (crate::page_ir::Color::BLACK, Some(Box::new(sh))),
None => continue,
}
}
Paint::Pattern { tiling, matrix } => {
let b = lower_tiled_stroke(
&mut out,
&page.paths[path.index()],
ctm,
&page.stroke_styles[style.index()],
&page.tilings[tiling.index()],
matrix.then(base),
*alpha,
clip_stack.last().copied(),
*blend,
paint_policy,
);
accumulate_scope_bounds(&mut scope_stack, b);
continue;
}
};
let clip = clip_stack.last().copied();
let b = lower_stroke(
&mut out,
&page.paths[path.index()],
ctm,
&page.stroke_styles[style.index()],
color,
*alpha,
clip,
*blend,
stroke_shading,
);
accumulate_scope_bounds(&mut scope_stack, b);
}
DisplayOp::DrawGlyphRun {
run,
paint,
alpha,
blend,
stroke,
} => {
let paint_policy = if soft_mask_content_depth == 0 {
out.color_policy
} else {
crate::render_api::RenderColorPolicy::Original
};
let (color, run_shading, run_tiling) = match &page.paints[paint.index()] {
Paint::Solid(color) => (recolor(*color, paint_policy), None, None),
Paint::Shading { shading, matrix } => {
match prepare_shading(
&page.shadings[shading.index()],
matrix.then(base),
size,
true,
paint_policy,
) {
Some(sh) => (crate::page_ir::Color::BLACK, Some(Box::new(sh)), None),
None => continue,
}
}
Paint::Pattern { tiling, matrix } => (
crate::page_ir::Color::BLACK,
None,
Some((*tiling, matrix.then(base))),
),
};
let color = &color;
let glyph_op_start = out.ops.len();
let gr = &page.glyph_runs[run.index()];
let mode = gr.render_mode;
let do_fill = matches!(mode, 0 | 2 | 4 | 6);
let do_stroke = matches!(mode, 1 | 2 | 5 | 6) && stroke.is_some();
if !do_fill && !do_stroke {
continue;
}
#[cfg(feature = "profiling")]
let font_parse_start = std::time::Instant::now();
#[cfg(feature = "profiling")]
let font_was_cached = font_programs.contains_key(&gr.font.0);
let program = resolve_font_program(&mut font_programs, page, gr.font, shared_fonts);
#[cfg(feature = "profiling")]
{
let mut profile = out.profile.borrow_mut();
if font_was_cached {
profile.increment("lower.font.program_cache_hits", 1);
} else {
profile.add_duration("lower.font.parse", font_parse_start.elapsed());
profile.increment("lower.font.parses", 1);
}
}
let clip = clip_stack.last().copied();
let synth = GlyphSynthesis::for_font(&page.fonts[gr.font.index()]);
let mut bounds: Option<DeviceRect> = None;
if do_fill {
let b = if let Some((tiling, pattern_to_device)) = run_tiling {
lower_tiled_glyph_run(
&mut out,
gr,
program.as_ref(),
ctm,
synth,
&page.tilings[tiling.index()],
pattern_to_device,
*alpha,
clip,
*blend,
paint_policy,
)
} else {
match &program {
Some(prog) => {
let cached = match shared_glyphs {
Some(gc) if gr.render_mode == 0 && !synth.is_active() => {
let font_id =
*glyph_font_ids.entry(gr.font.0).or_insert_with(|| {
FontProgramKey::for_resource(
&page.fonts[gr.font.index()],
)
});
try_cached_glyph_run(
&mut out,
gr,
prog,
ctm,
*color,
*alpha,
clip,
*blend,
gc,
font_id,
&mut glyph_raster,
)
}
_ => None,
};
match cached {
Some(b) => b,
None if split_glyph_draws => lower_glyph_outlines_split(
&mut out, gr, prog, ctm, *color, *alpha, clip, *blend,
synth,
),
None => lower_glyph_outlines(
&mut out, gr, prog, ctm, *color, *alpha, clip, *blend,
synth,
),
}
}
None if split_glyph_draws => lower_glyph_boxes_split(
&mut out, gr, ctm, *color, *alpha, clip, *blend,
),
None => {
lower_glyph_boxes(&mut out, gr, ctm, *color, *alpha, clip, *blend)
}
}
};
if let Some(sh) = &run_shading {
for op in &mut out.ops[glyph_op_start..] {
if let PreparedOp::GlyphRun(g) = op {
g.shading = Some(sh.clone());
}
}
}
bounds = union_rect(bounds, b);
}
if do_stroke && let (Some(prog), Some(gs)) = (&program, stroke) {
let (stroke_color, stroke_shading) = match &page.paints[gs.paint.index()] {
Paint::Solid(c) => (recolor(*c, paint_policy), None),
Paint::Shading { shading, matrix } => {
match prepare_shading(
&page.shadings[shading.index()],
matrix.then(base),
size,
true,
paint_policy,
) {
Some(sh) => (crate::page_ir::Color::BLACK, Some(Box::new(sh))),
None => (crate::page_ir::Color::BLACK, None),
}
}
_ => (crate::page_ir::Color::BLACK, None),
};
let b = lower_glyph_stroke(
&mut out,
gr,
prog,
ctm,
&page.stroke_styles[gs.style.index()],
stroke_color,
gs.alpha,
clip,
*blend,
synth,
stroke_shading,
);
bounds = union_rect(bounds, b);
}
accumulate_scope_bounds(&mut scope_stack, bounds);
}
DisplayOp::BeginTransparencyGroup { group } => {
let g = &page.groups[group.index()];
let begin_index = out.ops.len();
out.ops.push(PreparedOp::BeginGroup {
group: PreparedGroup {
bounds: DeviceRect {
x: 0,
y: 0,
width: 0,
height: 0,
},
opacity: to_u8(g.opacity),
blend: g.blend,
isolated: g.isolated,
knockout: g.knockout,
},
end: 0,
});
soft_at_group_entry.push(soft_count);
out.ops.push(PreparedOp::PushSoftMaskNone);
soft_count += 1;
scope_stack.push(ScopeBuilder {
begin_index,
bounds: None,
});
}
DisplayOp::EndTransparencyGroup => {
if let Some(gb) = scope_stack.pop() {
let target = soft_at_group_entry.pop().unwrap_or(soft_count);
while soft_count > target {
out.ops.push(PreparedOp::PopSoftMask);
soft_count -= 1;
}
let end_index = out.ops.len() as u32;
out.ops.push(PreparedOp::EndGroup);
let bounds = intersect(
gb.bounds.unwrap_or(DeviceRect {
x: 0,
y: 0,
width: 0,
height: 0,
}),
row_window(&out),
);
if let PreparedOp::BeginGroup { group, end } = &mut out.ops[gb.begin_index] {
group.bounds = bounds;
*end = end_index;
}
accumulate_scope_bounds(&mut scope_stack, Some(bounds));
}
}
DisplayOp::BeginSoftMask { kind, transfer } => {
soft_mask_content_depth += 1;
let begin_index = out.ops.len();
out.ops.push(PreparedOp::PushSoftMask {
kind: *kind,
transfer: transfer.clone(),
content_end: 0,
bounds: DeviceRect {
x: 0,
y: 0,
width: 0,
height: 0,
},
});
scope_stack.push(ScopeBuilder {
begin_index,
bounds: None,
});
}
DisplayOp::EndSoftMask => {
soft_mask_content_depth = soft_mask_content_depth.saturating_sub(1);
if let Some(sb) = scope_stack.pop() {
let content_end = out.ops.len() as u32;
let bounds = intersect(
sb.bounds.unwrap_or(DeviceRect {
x: 0,
y: 0,
width: 0,
height: 0,
}),
row_window(&out),
);
if let PreparedOp::PushSoftMask {
content_end: ce,
bounds: b,
..
} = &mut out.ops[sb.begin_index]
{
*ce = content_end;
*b = bounds;
}
soft_count += 1;
}
}
DisplayOp::ClearSoftMask => {
out.ops.push(PreparedOp::PushSoftMaskNone);
soft_count += 1;
}
DisplayOp::DrawShading { shading, .. } => {
let clip = clip_stack.last().copied();
let policy = if soft_mask_content_depth == 0 {
out.color_policy
} else {
crate::render_api::RenderColorPolicy::Original
};
let b =
lower_shading_op(&mut out, &page.shadings[shading.index()], ctm, clip, policy);
accumulate_scope_bounds(&mut scope_stack, b);
}
DisplayOp::DrawImage {
image,
paint,
alpha,
blend,
..
} => {
let paint_policy = if soft_mask_content_depth == 0 {
out.color_policy
} else {
crate::render_api::RenderColorPolicy::Original
};
let ir = &page.images[image.index()];
let clip = clip_stack.last().copied();
if ir.is_stencil
&& let Paint::Pattern { tiling, matrix } = &page.paints[paint.index()]
{
let (tiling, matrix) = (*tiling, *matrix);
if let Some((stencil_img, _)) =
lower_image(&mut out, ir, [255, 255, 255], ctm, *alpha, *blend, None)
{
let unit = unit_square_path();
let b = lower_tiled(
&mut out,
&unit,
ctm,
crate::page_ir::FillRule::NonZero,
&page.tilings[tiling.index()],
matrix.then(base),
*alpha,
clip,
*blend,
paint_policy,
Some(stencil_img),
);
accumulate_scope_bounds(&mut scope_stack, b);
}
} else if ir.is_stencil
&& let Paint::Shading { shading, matrix } = &page.paints[paint.index()]
{
let prepared_shading = prepare_shading(
&page.shadings[shading.index()],
matrix.then(base),
size,
true,
paint_policy,
);
if let (Some(shading), Some((stencil, _))) = (
prepared_shading,
lower_image(
&mut out,
ir,
[255, 255, 255],
ctm,
1.0,
crate::page_ir::BlendMode::Normal,
None,
),
) {
let b = lower_fill(
&mut out,
&unit_square_path(),
ctm,
crate::page_ir::FillRule::NonZero,
crate::page_ir::Color::BLACK,
*alpha,
clip,
*blend,
soft_count > 0,
Some(Box::new(shading)),
Some(stencil),
);
accumulate_scope_bounds(&mut scope_stack, b);
}
} else {
let stencil_rgb = match &page.paints[paint.index()] {
Paint::Solid(c) => {
let c = recolor(*c, paint_policy);
[to_u8(c.r), to_u8(c.g), to_u8(c.b)]
}
_ => [0, 0, 0],
};
if let Some((img, b)) =
lower_image(&mut out, ir, stencil_rgb, ctm, *alpha, *blend, clip)
{
out.ops.push(PreparedOp::Image(img));
accumulate_scope_bounds(&mut scope_stack, Some(b));
}
}
}
DisplayOp::ApplySoftMask { .. } => {}
}
if let Some(extents) = sink
.as_deref_mut()
.and_then(|sink| sink.extents.as_deref_mut())
&& !extents.complete
{
for index in ops_before.min(out.ops.len())..out.ops.len() {
let bounds = match &out.ops[index] {
PreparedOp::Draw(cmd) => Some(cmd.bounds),
PreparedOp::GlyphRun(gr) => Some(gr.bounds),
PreparedOp::Image(img) => Some(img.bounds),
PreparedOp::TiledFill(t) => Some(t.bounds),
_ => None,
};
if let Some(bounds) = bounds {
note_extent(&mut out, bounds);
}
}
if extents.rows.len() <= op_index {
extents.rows.resize(op_index + 1, (i32::MIN, i32::MAX));
}
extents.rows[op_index] = out.op_extent.unwrap_or((0, 0));
}
if out.rows != (0, u32::MAX) && out.ops.len() > ops_before {
let window = row_window(&out);
for prepared in &mut out.ops[ops_before..] {
match prepared {
PreparedOp::Draw(cmd) => cmd.bounds = intersect(cmd.bounds, window),
PreparedOp::GlyphRun(gr) => gr.bounds = intersect(gr.bounds, window),
PreparedOp::Image(img) => img.bounds = intersect(img.bounds, window),
_ => {}
}
}
}
if sink.is_some() {
for prepared in &out.ops[ops_before.min(out.ops.len())..] {
if let PreparedOp::Image(img) = prepared {
pending_image_bytes = pending_image_bytes
.saturating_add(img.samples.len())
.saturating_add(img.smask.as_ref().map_or(0, |m| m.samples.len()));
}
}
}
if let Some(&origin) = origin_stack.last()
&& out.ops.len() > ops_before
{
for prepared in &mut out.ops[ops_before..] {
match prepared {
PreparedOp::Draw(cmd) => cmd.origin = origin,
PreparedOp::GlyphRun(gr) => gr.origin = origin,
PreparedOp::TiledFill(t) => t.origin = origin,
PreparedOp::Image(img) => img.origin = origin,
_ => {}
}
}
}
}
#[cfg(feature = "profiling")]
if prof_enabled {
out.lower_prof.lap(prof_bucket);
let mut profile = out.profile.borrow_mut();
out.lower_prof.flush_into(&mut profile);
glyph_raster.prof.drain_into(&mut profile);
profile.add_duration("render.lower.total", lower_start.elapsed());
profile.increment("render.lower.operations", page.operations.len() as u64);
profile.increment(
"render.lower.prepared_ops",
flushed_ops + out.ops.len() as u64,
);
profile.increment(
"render.lower.points",
flushed_points + out.points.len() as u64,
);
profile.increment(
"render.lower.subpaths",
flushed_subpaths + out.subpaths.len() as u64,
);
profile.increment(
"render.lower.arena_bytes",
peak_arena.max(
(out.points.capacity() * std::mem::size_of::<[f32; 2]>()
+ out.subpaths.capacity() * std::mem::size_of::<(usize, usize)>())
as u64,
),
);
}
if !stopped_early
&& !out.decode_limits.is_cancelled()
&& let Some(extents) = sink.and_then(|sink| sink.extents.as_deref_mut())
&& !extents.complete
{
extents.rows.resize(page.operations.len(), (0, 0));
extents.complete = true;
}
if let Some(cache) = font_cache {
cache.store_for_page(page, font_programs);
}
out
}
fn unit_square_path() -> PathData {
PathData {
verbs: std::sync::Arc::from(
[
PathVerb::MoveTo,
PathVerb::LineTo,
PathVerb::LineTo,
PathVerb::LineTo,
PathVerb::Close,
]
.as_slice(),
),
points: std::sync::Arc::from(
[
Point { x: 0.0, y: 0.0 },
Point { x: 1.0, y: 0.0 },
Point { x: 1.0, y: 1.0 },
Point { x: 0.0, y: 1.0 },
]
.as_slice(),
),
}
}
#[allow(clippy::too_many_arguments)]
fn lower_image(
out: &mut CpuPreparedPage,
ir: &crate::page_ir::ImageIr,
stencil_rgb: [u8; 3],
ctm: Matrix,
alpha: f32,
blend: crate::page_ir::BlendMode,
clip: Option<u32>,
) -> Option<(Box<crate::render_cpu::image::PreparedImage>, DeviceRect)> {
if ir.lowering_degraded {
out.diagnostics
.note_degraded("image draw degraded during IR lowering (lowering_degraded)".into());
}
let target_size = decode_target_size(ctm, out.decode_floor);
if !ctm.is_stably_invertible() {
return None;
}
let inv = ctm.invert()?;
let corners = [
ctm.apply(Point { x: 0.0, y: 0.0 }),
ctm.apply(Point { x: 1.0, y: 0.0 }),
ctm.apply(Point { x: 1.0, y: 1.0 }),
ctm.apply(Point { x: 0.0, y: 1.0 }),
];
let pts: Vec<[f32; 2]> = corners.iter().map(|p| [p.x as f32, p.y as f32]).collect();
let (bx0, by0, bx1, by1) = device_bounds(&pts, out.size);
let mut bounds = DeviceRect {
x: bx0,
y: by0,
width: (bx1 - bx0).max(0) as u32,
height: (by1 - by0).max(0) as u32,
};
let clip_has_mask = if let Some(cid) = clip {
let c = &out.clips[cid as usize];
bounds = intersect(bounds, c.bounds);
c.has_mask
} else {
false
};
note_extent(out, bounds);
bounds = intersect(bounds, row_window(out));
if bounds.width == 0 || bounds.height == 0 {
return None;
}
let mut in_data_smask: Option<std::sync::Arc<crate::page_ir::ImageSMask>> = None;
let (samples, img_w, img_h, bpc, color_space) = match ir.samples.clone() {
Some(s) => (
s,
ir.width,
ir.height,
ir.bits_per_component,
ir.color_space.clone(),
),
None => {
let (Some(_), Some(_)) = (ir.codec, ir.codec_data.as_ref()) else {
out.diagnostics.note_degraded(
"image draw dropped: no decodable samples (upstream filter decode failed)"
.into(),
);
return None;
};
let mut d = decode_codec_image(out, ir, target_size)?;
let cs = match &ir.color_space {
crate::page_ir::ImageColorSpace::Indexed { .. }
| crate::page_ir::ImageColorSpace::TintLut { .. } => {
if d.color_space == crate::page_ir::ImageColorSpace::Gray {
ir.color_space.clone()
} else {
out.diagnostics.note_degraded(format!(
"image draw dropped: {} color space over a multi-component {:?} \
codec output (palette/tint expects one component)",
reinterpreting_space_name(&ir.color_space),
d.color_space,
));
return None;
}
}
crate::page_ir::ImageColorSpace::Lab { .. }
if d.color_space == crate::page_ir::ImageColorSpace::Rgb =>
{
ir.color_space.clone()
}
crate::page_ir::ImageColorSpace::IccRgb { .. }
if d.color_space == crate::page_ir::ImageColorSpace::Rgb =>
{
ir.color_space.clone()
}
crate::page_ir::ImageColorSpace::IccCmyk { .. }
if d.color_space == crate::page_ir::ImageColorSpace::Cmyk =>
{
ir.color_space.clone()
}
crate::page_ir::ImageColorSpace::TintLut2 { .. }
if matches!(d.format, crate::image::DecodedFormat::Multi2) =>
{
ir.color_space.clone()
}
_ => d.color_space,
};
if let Some(opacity) = d.alpha.clone() {
match ir.smask_in_data {
1 => {
in_data_smask = Some(std::sync::Arc::new(crate::page_ir::ImageSMask {
width: d.width,
height: d.height,
bits_per_component: 8,
decode: None,
samples: opacity,
codec: None,
codec_data: None,
codec_parms: None,
}));
}
2 => {
let Some(unassociated) =
unpremultiply_in_data_alpha(&d.samples, &opacity, d.format)
else {
out.diagnostics.note_degraded(
"JPX premultiplied in-data alpha has an invalid decoded layout, draw skipped"
.into(),
);
return None;
};
d.samples = unassociated;
in_data_smask = Some(std::sync::Arc::new(crate::page_ir::ImageSMask {
width: d.width,
height: d.height,
bits_per_component: 8,
decode: None,
samples: opacity,
codec: None,
codec_data: None,
codec_parms: None,
}));
}
_ => {}
}
}
(d.samples, d.width, d.height, d.bpc, cs)
}
};
if img_w == 0 || img_h == 0 {
return None;
}
let sample_lut = crate::render_cpu::image::build_sample_lut(
bpc,
&color_space,
ir.decode.as_deref(),
ir.is_stencil,
);
let interpolation = if matches!(
ir.codec,
Some(crate::page_ir::ImageCodecKind::Dct | crate::page_ir::ImageCodecKind::Jpx)
) && !ir.is_stencil
&& ir.interpolation == crate::page_ir::InterpolationMode::Nearest
{
crate::page_ir::InterpolationMode::Bilinear
} else {
ir.interpolation
};
let prepared = Box::new(crate::render_cpu::image::PreparedImage {
origin: crate::page_ir::PaintOrigin::default(),
bounds,
clip,
clip_has_mask,
inv,
width: img_w,
height: img_h,
bpc,
color_space,
decode: ir.decode.clone(),
samples,
sample_lut,
smask: in_data_smask.or_else(|| resolve_smask(out, ir.smask.as_deref(), target_size)),
mask: resolve_mask(out, ir.mask.as_ref(), target_size),
interpolation,
footprint: [
(inv.a.abs() + inv.c.abs()) * img_w as f64,
(inv.b.abs() + inv.d.abs()) * img_h as f64,
],
is_stencil: ir.is_stencil,
stencil_rgb,
alpha: to_u8(alpha),
blend,
});
let ring_ok = placement_ring_unchanged_by_promotion(&ctm);
let prepared = promote_through_cache(out, prepared, ring_ok);
Some((prepared, bounds))
}
const PROMOTION_CACHE_CODEC: u8 = 0x80;
fn promote_through_cache(
out: &CpuPreparedPage,
prepared: Box<crate::render_cpu::image::PreparedImage>,
ring_ok: bool,
) -> Box<crate::render_cpu::image::PreparedImage> {
let indexed = prepared.indexed_promotion_eligible();
if !indexed && !prepared.generic_promotion_eligible() {
return prepared;
}
let unmasked_opaque =
prepared.smask.is_none() && prepared.mask.is_none() && prepared.alpha == 255;
if prepared.is_sixteen_bit_device_family() && unmasked_opaque && !ring_ok {
return prepared;
}
let key = (out.image_cache.is_some() || out.strip_decodes.is_some())
.then(|| promotion_cache_key(&prepared));
let cache = out.image_cache.as_ref().zip(key);
let expected = prepared.width as usize * prepared.height as usize * 3;
if let (Some(held), Some(key)) = (&out.strip_decodes, &key)
&& let Some(hit) = held.get(key)
&& hit.samples.len() == expected
{
return Box::new(prepared.with_rgb8_samples(hit.samples));
}
if let Some((cache, key)) = &cache
&& let Some(hit) = cache.get(key)
&& hit.samples.len() == expected
{
hold_for_later_strips(out, *key, &hit);
return Box::new(prepared.with_rgb8_samples(hit.samples));
}
let samples = if indexed {
prepared.indexed_source_as_rgb8()
} else {
prepared.generic_source_as_rgb8()
};
let Some(samples) = samples else {
return prepared;
};
if let Some(key) = key {
let resolved = CodecSamples {
samples: samples.clone(),
width: prepared.width,
height: prepared.height,
bpc: 8,
color_space: crate::page_ir::ImageColorSpace::Rgb,
format: crate::image::DecodedFormat::Rgb8,
alpha: None,
};
hold_for_later_strips(out, key, &resolved);
if let Some((cache, key)) = cache {
cache.insert(key, resolved);
}
}
Box::new(prepared.with_rgb8_samples(samples))
}
fn placement_ring_unchanged_by_promotion(ctm: &Matrix) -> bool {
let scale = ctm
.a
.abs()
.max(ctm.b.abs())
.max(ctm.c.abs())
.max(ctm.d.abs());
let tol = 1e-9 * scale.max(1.0);
let whole = |v: f64| (v - v.round()).abs() <= 1e-6;
if ctm.b.abs() <= tol && ctm.c.abs() <= tol {
whole(ctm.e) && whole(ctm.e + ctm.a) && whole(ctm.f) && whole(ctm.f + ctm.d)
} else if ctm.a.abs() <= tol && ctm.d.abs() <= tol {
whole(ctm.e) && whole(ctm.e + ctm.c) && whole(ctm.f) && whole(ctm.f + ctm.b)
} else {
true
}
}
fn promotion_cache_key(img: &crate::render_cpu::image::PreparedImage) -> ImageCacheKey {
let (h0, h1) = content_hash_128(&img.samples);
let mut h: u64 = 0x9E37_79B9_7F4A_7C15;
let mut mix = |bytes: &[u8]| {
let (a, b) = content_hash_128(bytes);
h = (h ^ a).wrapping_mul(0xC2B2_AE3D_27D4_EB4F).rotate_left(29) ^ b;
};
let f32s =
|v: &[f32]| -> Vec<u8> { v.iter().flat_map(|x| x.to_bits().to_le_bytes()).collect() };
mix_color_space_identity(&img.color_space, &mut mix);
if let Some(d) = &img.decode {
mix(b"decode");
mix(&f32s(&d.iter().flatten().copied().collect::<Vec<f32>>()));
}
ImageCacheKey {
h0,
h1,
len: img.samples.len(),
codec: PROMOTION_CACHE_CODEC,
width: img.width,
height: img.height,
bpc: img.bpc,
is_mask: false,
space: None,
scale: DecodeScaleKey::Level(0),
parms: h | 1,
}
}
fn mix_color_space_identity(space: &crate::page_ir::ImageColorSpace, mix: &mut impl FnMut(&[u8])) {
use crate::page_ir::ImageColorSpace;
let f32s =
|v: &[f32]| -> Vec<u8> { v.iter().flat_map(|x| x.to_bits().to_le_bytes()).collect() };
match space {
ImageColorSpace::Gray => mix(b"gray"),
ImageColorSpace::Rgb => mix(b"rgb"),
ImageColorSpace::Cmyk => mix(b"cmyk"),
ImageColorSpace::Indexed {
base,
hival,
lookup,
} => {
mix(b"indexed");
mix_color_space_identity(base, mix);
mix(&hival.to_le_bytes());
mix(lookup);
}
ImageColorSpace::IccRgb { trc, matrix } => {
mix(b"iccrgb");
mix(&f32s(trc));
mix(&f32s(matrix));
}
ImageColorSpace::IccCmyk { transform } => {
mix(b"icccmyk");
mix(&[transform.grid]);
for t in &transform.input_tables {
mix(&f32s(t));
}
mix(&f32s(
&transform
.clut
.iter()
.flatten()
.copied()
.collect::<Vec<f32>>(),
));
for t in &transform.output_tables {
mix(&f32s(t));
}
}
ImageColorSpace::Lab { white_point, range } => {
mix(b"lab");
mix(&f32s(white_point));
mix(&f32s(range));
}
ImageColorSpace::TintLut { rgb } => {
mix(b"tint");
mix(rgb);
}
ImageColorSpace::TintLut2 { rgb } => {
mix(b"tint2");
mix(rgb);
}
}
}
fn resolve_smask(
out: &CpuPreparedPage,
smask: Option<&crate::page_ir::ImageSMask>,
target_size: Option<(u32, u32)>,
) -> Option<std::sync::Arc<crate::page_ir::ImageSMask>> {
let smask = smask?;
if smask.codec.is_none() {
return Some(std::sync::Arc::new(smask.clone()));
}
let decoded = decode_codec_samples(
out,
smask.codec?,
smask.codec_data.as_deref()?,
smask.width,
smask.height,
smask.bits_per_component,
true,
smask.codec_parms.clone(),
target_size,
None,
)?;
Some(std::sync::Arc::new(crate::page_ir::ImageSMask {
width: decoded.width,
height: decoded.height,
bits_per_component: decoded.bpc,
decode: smask.decode.clone(),
samples: decoded.samples,
codec: None,
codec_data: None,
codec_parms: None,
}))
}
fn resolve_mask(
out: &CpuPreparedPage,
mask: Option<&crate::page_ir::ImageMask>,
target_size: Option<(u32, u32)>,
) -> Option<crate::page_ir::ImageMask> {
match mask? {
crate::page_ir::ImageMask::ColorKey(ranges) => {
Some(crate::page_ir::ImageMask::ColorKey(ranges.clone()))
}
crate::page_ir::ImageMask::Stencil(sm) => {
let resolved = resolve_smask(out, Some(sm), target_size)?;
Some(crate::page_ir::ImageMask::Stencil(resolved))
}
}
}
fn reinterpreting_space_name(cs: &crate::page_ir::ImageColorSpace) -> &'static str {
match cs {
crate::page_ir::ImageColorSpace::Indexed { .. } => "Indexed",
crate::page_ir::ImageColorSpace::TintLut { .. } => "TintLut",
crate::page_ir::ImageColorSpace::TintLut2 { .. } => "TintLut2",
crate::page_ir::ImageColorSpace::IccRgb { .. } => "IccRgb",
crate::page_ir::ImageColorSpace::IccCmyk { .. } => "IccCmyk",
_ => "reinterpreting",
}
}
#[derive(Debug, Clone)]
struct CodecSamples {
samples: std::sync::Arc<[u8]>,
width: u32,
height: u32,
bpc: u8,
color_space: crate::page_ir::ImageColorSpace,
format: crate::image::DecodedFormat,
alpha: Option<std::sync::Arc<[u8]>>,
}
fn unpremultiply_in_data_alpha(
samples: &[u8],
alpha: &[u8],
format: crate::image::DecodedFormat,
) -> Option<std::sync::Arc<[u8]>> {
let channels = match format {
crate::image::DecodedFormat::Rgba8 => 3,
crate::image::DecodedFormat::GrayA8 => 1,
_ => return None,
};
if samples.len() != alpha.len().checked_mul(channels)? {
return None;
}
let mut straight = zeroed_arc(samples.len());
unique_arc_mut(&mut straight).copy_from_slice(samples);
for (pixel, &a) in unique_arc_mut(&mut straight)
.chunks_exact_mut(channels)
.zip(alpha)
{
if a == 0 {
pixel.fill(0);
continue;
}
let a = u32::from(a);
for component in pixel {
let value = (u32::from(*component) * 255 + a / 2) / a;
*component = value.min(255) as u8;
}
}
Some(straight)
}
fn decode_codec_image(
out: &CpuPreparedPage,
ir: &crate::page_ir::ImageIr,
target_size: Option<(u32, u32)>,
) -> Option<CodecSamples> {
decode_codec_samples(
out,
ir.codec?,
ir.codec_data.as_deref()?,
ir.width,
ir.height,
ir.bits_per_component,
ir.is_stencil,
ir.codec_parms.clone(),
target_size,
Some(&ir.color_space),
)
}
fn declared_space_family(
space: &crate::page_ir::ImageColorSpace,
) -> crate::color::ColorSpaceFamily {
match space {
crate::page_ir::ImageColorSpace::Gray => crate::color::ColorSpaceFamily::DeviceGray,
crate::page_ir::ImageColorSpace::Rgb => crate::color::ColorSpaceFamily::DeviceRgb,
crate::page_ir::ImageColorSpace::Cmyk => crate::color::ColorSpaceFamily::DeviceCmyk,
crate::page_ir::ImageColorSpace::Indexed { .. } => crate::color::ColorSpaceFamily::Indexed,
crate::page_ir::ImageColorSpace::TintLut { .. }
| crate::page_ir::ImageColorSpace::TintLut2 { .. } => {
crate::color::ColorSpaceFamily::DeviceN
}
crate::page_ir::ImageColorSpace::Lab { .. } => crate::color::ColorSpaceFamily::Lab,
crate::page_ir::ImageColorSpace::IccRgb { .. }
| crate::page_ir::ImageColorSpace::IccCmyk { .. } => {
crate::color::ColorSpaceFamily::IccBased
}
}
}
#[allow(clippy::too_many_arguments)]
fn decode_codec_samples(
out: &CpuPreparedPage,
kind: crate::page_ir::ImageCodecKind,
data: &[u8],
width: u32,
height: u32,
bits_per_component: u8,
is_mask: bool,
parms: Option<crate::page_ir::CodecParms>,
target_size: Option<(u32, u32)>,
declared_space: Option<&crate::page_ir::ImageColorSpace>,
) -> Option<CodecSamples> {
use crate::image::{DecodeParameters, DecodedFormat, ImageDescriptor, StreamFilter};
if out.decode_limits.is_cancelled() {
return None;
}
#[cfg(feature = "profiling")]
let cache_key = DecodeCacheKey {
data_ptr: data.as_ptr() as usize,
data_len: data.len(),
codec: match kind {
crate::page_ir::ImageCodecKind::Dct => 0,
crate::page_ir::ImageCodecKind::Jpx => 1,
crate::page_ir::ImageCodecKind::Jbig2 => 2,
crate::page_ir::ImageCodecKind::CcittFax => 3,
},
width,
height,
bpc: bits_per_component,
is_mask,
target: target_size,
};
#[cfg(feature = "profiling")]
if let Some(cache) = &out.decode_cache {
if let Some(cached) = lock_unpoisoned(&cache.entries).get(&cache_key).cloned() {
let mut profile = out.profile.borrow_mut();
profile.increment("codec.decode_cache.hits", 1);
profile.increment("codec.decode_cache.hit_bytes", cached.samples.len() as u64);
return Some(cached);
}
out.profile
.borrow_mut()
.increment("codec.decode_cache.misses", 1);
}
let filter = match kind {
crate::page_ir::ImageCodecKind::Dct => StreamFilter::DctDecode,
crate::page_ir::ImageCodecKind::Jpx => StreamFilter::Jpx,
crate::page_ir::ImageCodecKind::Jbig2 => StreamFilter::Jbig2,
crate::page_ir::ImageCodecKind::CcittFax => StreamFilter::CcittFax,
};
let Some(codec) = out.codecs.get(filter) else {
out.diagnostics.note_degraded(format!(
"{filter:?} image draw skipped: no codec registered"
));
return None;
};
let descriptor = ImageDescriptor {
width,
height,
bits_per_component,
color_space: declared_space.map(|space| crate::color::ColorSpaceDesc {
family: declared_space_family(space),
components: space.components() as u8,
object: None,
}),
is_mask,
interpolate: false,
filters: vec![filter],
object: None,
};
let params = match &parms {
Some(p) => DecodeParameters {
decode: None,
jbig2_globals: p.jbig2_globals.clone(),
ccitt: Some(crate::image::CcittParams {
k: p.k,
columns: p.columns,
rows: p.rows,
black_is_1: p.black_is_1,
byte_align: p.byte_align,
end_of_line: p.end_of_line,
end_of_block: p.end_of_block,
}),
target_size,
},
None => DecodeParameters {
target_size,
..DecodeParameters::default()
},
};
let image_key = (out.image_cache.is_some() || out.strip_decodes.is_some()).then(|| {
let scale = match codec.reduction_level(data, &descriptor, ¶ms, &out.decode_limits) {
Some(level) => DecodeScaleKey::Level(level),
None => DecodeScaleKey::Target(target_size),
};
ImageCacheKey::new(
kind,
data,
width,
height,
bits_per_component,
is_mask,
descriptor.color_space.as_ref(),
parms.as_ref(),
scale,
)
});
if let (Some(held), Some(key)) = (&out.strip_decodes, &image_key)
&& let Some(decoded) = held.get(key)
{
return Some(decoded);
}
let image_decode_flight = match out.image_cache.as_ref().zip(image_key) {
Some((cache, key)) => match cache.probe(key) {
ImageCacheProbe::Hit(cached) => {
hold_for_later_strips(out, key, &cached);
return Some(cached);
}
ImageCacheProbe::Leader(flight) => Some(flight),
},
None => None,
};
#[cfg(feature = "profiling")]
let decode_start = std::time::Instant::now();
let img = match codec.decode(data, &descriptor, ¶ms, &out.decode_limits) {
Ok(img) => img,
Err(crate::image::ImageError::Cancelled) => return None,
Err(e) => {
out.diagnostics.note_degraded(format!(
"{filter:?} {} image decode failed, draw skipped: {e}",
if is_mask { "mask" } else { "base" }
));
return None;
}
};
if let Err(e) = img.validate(&out.decode_limits) {
if !matches!(e, crate::image::ImageError::Cancelled) {
out.diagnostics.note_degraded(format!(
"{filter:?} {} codec returned an invalid raster, draw skipped: {e}",
if is_mask { "mask" } else { "base" }
));
}
return None;
}
#[cfg(feature = "profiling")]
{
let mut profile = out.profile.borrow_mut();
profile.add_duration(
match filter {
StreamFilter::DctDecode => "codec.dct.decode",
StreamFilter::Jpx => "codec.jpx.decode",
StreamFilter::Jbig2 => "codec.jbig2.decode",
StreamFilter::CcittFax => "codec.ccitt.decode",
_ => "codec.other.decode",
},
decode_start.elapsed(),
);
profile.increment("codec.decode.calls", 1);
profile.increment("codec.encoded_bytes", data.len() as u64);
profile.increment("codec.decoded_pixels", img.width as u64 * img.height as u64);
profile.increment("codec.decoded_bytes", img.data.len() as u64);
profile.allocate_bytes(img.data.len() as u64);
}
#[cfg(feature = "profiling")]
let decoded_allocation_bytes = img.data.len() as u64;
let (color_space, comps, bpc, output_format_counter) = match img.format {
DecodedFormat::Mono1 => (
crate::page_ir::ImageColorSpace::Gray,
1,
1u8,
"codec.output.mono1",
),
DecodedFormat::Gray8 => (
crate::page_ir::ImageColorSpace::Gray,
1,
8,
"codec.output.gray8",
),
DecodedFormat::Gray16 => (
crate::page_ir::ImageColorSpace::Gray,
1,
16,
"codec.output.gray16",
),
DecodedFormat::GrayA8 => (
crate::page_ir::ImageColorSpace::Gray,
2,
8,
"codec.output.graya8",
),
DecodedFormat::Multi2 => (
crate::page_ir::ImageColorSpace::Gray,
2,
8,
"codec.output.multi2",
),
DecodedFormat::Rgb8 => (
crate::page_ir::ImageColorSpace::Rgb,
3,
8,
"codec.output.rgb8",
),
DecodedFormat::Rgba8 => (
crate::page_ir::ImageColorSpace::Rgb,
4,
8,
"codec.output.rgba8",
),
DecodedFormat::Cmyk8 => (
crate::page_ir::ImageColorSpace::Cmyk,
4,
8,
"codec.output.cmyk8",
),
};
#[cfg(feature = "profiling")]
out.profile.borrow_mut().increment(output_format_counter, 1);
#[cfg(not(feature = "profiling"))]
let _ = output_format_counter;
let tight = (img.width as usize * comps * bpc as usize).div_ceil(8);
#[cfg(feature = "profiling")]
let repack_start = std::time::Instant::now();
let samples: std::sync::Arc<[u8]> = if img.stride == tight {
img.data
} else {
let mut packed = zeroed_arc(tight * img.height as usize);
let packed_data = unique_arc_mut(&mut packed);
for y in 0..img.height as usize {
let src = &img.data[y * img.stride..y * img.stride + tight];
packed_data[y * tight..(y + 1) * tight].copy_from_slice(src);
}
packed
};
#[cfg(feature = "profiling")]
{
let mut profile = out.profile.borrow_mut();
profile.add_duration("codec.repack", repack_start.elapsed());
if img.stride != tight {
profile.increment("codec.repacked_rows", img.height as u64);
profile.increment("codec.repacked_bytes", samples.len() as u64);
profile.allocate_bytes(samples.len() as u64);
profile.release_bytes(decoded_allocation_bytes);
}
}
let (samples, alpha) = match img.format {
DecodedFormat::Rgba8 | DecodedFormat::GrayA8 => {
let n = if matches!(img.format, DecodedFormat::Rgba8) {
4
} else {
2
};
let base_n = n - 1;
let px = img.width as usize * img.height as usize;
let mut base = zeroed_arc(px * base_n);
let mut opacity = zeroed_arc(px);
let base_data = unique_arc_mut(&mut base);
let opacity_data = unique_arc_mut(&mut opacity);
for i in 0..px {
base_data[i * base_n..(i + 1) * base_n]
.copy_from_slice(&samples[i * n..i * n + base_n]);
opacity_data[i] = samples[i * n + base_n];
}
(base, Some(opacity))
}
_ => (samples, None),
};
let decoded = CodecSamples {
samples,
format: img.format,
width: img.width,
height: img.height,
bpc,
color_space,
alpha,
};
if let Some(flight) = image_decode_flight {
flight.complete(&decoded);
}
if let Some(key) = image_key {
hold_for_later_strips(out, key, &decoded);
}
#[cfg(feature = "profiling")]
if let Some(cache) = &out.decode_cache {
lock_unpoisoned(&cache.entries).insert(cache_key, decoded.clone());
}
Some(decoded)
}
struct ScopeBuilder {
begin_index: usize,
bounds: Option<DeviceRect>,
}
fn accumulate_scope_bounds(scope_stack: &mut [ScopeBuilder], bounds: Option<DeviceRect>) {
if let (Some(gb), Some(b)) = (scope_stack.last_mut(), bounds) {
if b.width == 0 || b.height == 0 {
return;
}
gb.bounds = Some(match gb.bounds {
Some(cur) => union(cur, b),
None => b,
});
}
}
fn union_rect(a: Option<DeviceRect>, b: Option<DeviceRect>) -> Option<DeviceRect> {
match (a, b) {
(Some(a), Some(b)) => Some(union(a, b)),
(some, None) | (None, some) => some,
}
}
fn union(a: DeviceRect, b: DeviceRect) -> DeviceRect {
if a.width == 0 || a.height == 0 {
return b;
}
if b.width == 0 || b.height == 0 {
return a;
}
let x0 = a.x.min(b.x);
let y0 = a.y.min(b.y);
let x1 = (a.x + a.width as i32).max(b.x + b.width as i32);
let y1 = (a.y + a.height as i32).max(b.y + b.height as i32);
DeviceRect {
x: x0,
y: y0,
width: (x1 - x0) as u32,
height: (y1 - y0) as u32,
}
}
fn push_clip(
out: &mut CpuPreparedPage,
clip_stack: &mut Vec<u32>,
share: &mut ClipShare,
path: &PathData,
ctm: Matrix,
rule: crate::page_ir::FillRule,
) {
let pt_start = out.points.len();
let range_start = out.subpaths.len() as u32;
flatten_into(path, ctm, &mut out.points, &mut out.subpaths);
let range_end = out.subpaths.len() as u32;
#[cfg(feature = "profiling")]
let prof_clip_points = (out.points.len() - pt_start) as u64;
let (bx0, by0, bx1, by1) = device_bounds(&out.points[pt_start..], out.size);
let path_rect = DeviceRect {
x: bx0,
y: by0,
width: (bx1 - bx0).max(0) as u32,
height: (by1 - by0).max(0) as u32,
};
let parent = clip_stack.last().copied();
let parent_bounds = parent.map(|p| out.clips[p as usize].bounds);
let bounds = match parent_bounds {
Some(pb) => intersect(pb, path_rect),
None => path_rect,
};
let is_rect = range_end - range_start == 1 && is_axis_aligned_rect(&out.points[pt_start..]);
let kind = if is_rect {
out.points.truncate(pt_start);
out.subpaths.truncate(range_start as usize);
ClipKind::Rect
} else {
let krule = match rule {
crate::page_ir::FillRule::NonZero => FillRule::NonZero,
crate::page_ir::FillRule::EvenOdd => FillRule::EvenOdd,
};
ClipKind::Path {
subpath_range: (range_start, range_end),
rule: krule,
}
};
#[cfg(feature = "profiling")]
if !out.lower_prof.disabled {
let prof = &mut out.lower_prof;
prof.clip_ops += 1;
if is_rect {
prof.clip_rects += 1;
} else {
let (lines, curves, _, _) = LowerProf::path_census(path, ctm);
prof.clip_paths += 1;
prof.clip_lines += lines;
prof.clip_curves += curves;
prof.clip_path_points += prof_clip_points;
}
}
let has_mask = matches!(kind, ClipKind::Path { .. })
|| parent
.map(|p| out.clips[p as usize].has_mask)
.unwrap_or(false);
let (kind, mask_source) = share.resolve(out, kind, bounds, parent);
let cid = out.clips.len() as u32;
out.clips.push(PreparedClip {
parent,
bounds,
mask_bounds: intersect(bounds, row_window(out)),
kind,
has_mask,
mask_source,
});
clip_stack.push(cid);
}
fn clip_share_enabled() -> bool {
#[cfg(test)]
if CLIP_SHARE_OFF_FOR_TEST.with(std::cell::Cell::get) {
return false;
}
use std::sync::OnceLock;
static ENABLED: OnceLock<bool> = OnceLock::new();
*ENABLED.get_or_init(|| match std::env::var("PDF_RENDERER_CLIPSHARE") {
Ok(v) => {
let v = v.trim().to_ascii_lowercase();
v != "off" && v != "0" && v != "false"
}
Err(_) => true,
})
}
#[cfg(test)]
thread_local! {
pub(crate) static CLIP_SHARE_OFF_FOR_TEST: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct ClipShareKey {
geometry: u64,
even_odd: bool,
bounds: (i32, i32, u32, u32),
above: Option<u32>,
}
#[derive(Debug, Default)]
struct ClipShare {
by_key: HashMap<ClipShareKey, Vec<u32>>,
}
impl ClipShare {
const MAX_PER_KEY: usize = 4;
fn resolve(
&mut self,
out: &mut CpuPreparedPage,
kind: ClipKind,
bounds: DeviceRect,
parent: Option<u32>,
) -> (ClipKind, Option<u32>) {
let above = parent.and_then(|p| out.clips[p as usize].mask_source);
let ClipKind::Path {
subpath_range,
rule,
} = kind
else {
return (kind, above);
};
let cid = out.clips.len() as u32;
if bounds.width == 0 || bounds.height == 0 || !clip_share_enabled() {
return (kind, Some(cid));
}
let (first, last) = (subpath_range.0 as usize, subpath_range.1 as usize);
let mut geometry: u64 = 0x9E37_79B9_7F4A_7C15 ^ (last - first) as u64;
let mut mix = |word: u64| {
geometry = (geometry ^ word)
.wrapping_mul(0xC2B2_AE3D_27D4_EB4F)
.rotate_left(31);
};
for &(start, end) in &out.subpaths[first..last] {
mix((end - start) as u64);
for p in &out.points[start..end] {
mix((u64::from(p[0].to_bits()) << 32) | u64::from(p[1].to_bits()));
}
}
let key = ClipShareKey {
geometry,
even_odd: matches!(rule, FillRule::EvenOdd),
bounds: (bounds.x, bounds.y, bounds.width, bounds.height),
above,
};
let known = self.by_key.entry(key).or_default();
for &candidate in known.iter() {
let ClipKind::Path {
subpath_range: shared,
..
} = out.clips[candidate as usize].kind
else {
continue;
};
if same_clip_geometry(out, subpath_range, shared) {
if let Some(&(tail, _)) = out.subpaths.get(first) {
out.points.truncate(tail);
}
out.subpaths.truncate(first);
return (
ClipKind::Path {
subpath_range: shared,
rule,
},
Some(candidate),
);
}
}
if known.len() < Self::MAX_PER_KEY {
known.push(cid);
}
(kind, Some(cid))
}
}
fn same_clip_geometry(out: &CpuPreparedPage, a: (u32, u32), b: (u32, u32)) -> bool {
let (sa, sb) = (
&out.subpaths[a.0 as usize..a.1 as usize],
&out.subpaths[b.0 as usize..b.1 as usize],
);
sa.len() == sb.len()
&& sa.iter().zip(sb).all(|(&(s0, e0), &(s1, e1))| {
let (pa, pb) = (&out.points[s0..e0], &out.points[s1..e1]);
pa.len() == pb.len()
&& pa.iter().zip(pb).all(|(p, q)| {
p[0].to_bits() == q[0].to_bits() && p[1].to_bits() == q[1].to_bits()
})
})
}
#[allow(clippy::too_many_arguments)]
fn lower_fill(
out: &mut CpuPreparedPage,
path: &PathData,
ctm: Matrix,
rule: crate::page_ir::FillRule,
color: crate::page_ir::Color,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
soft_active: bool,
shading: Option<Box<PreparedShading>>,
stencil: Option<Box<crate::render_cpu::image::PreparedImage>>,
) -> Option<DeviceRect> {
let range_start = out.subpaths.len() as u32;
let pt_start = out.points.len();
#[cfg(feature = "profiling")]
if !out.lower_prof.disabled {
out.lower_prof.lap(LowerBucket::FillFinish);
let (lines, curves, adaptive, bins) = LowerProf::path_census(path, ctm);
let prof = &mut out.lower_prof;
prof.fill_ops += 1;
prof.fill_lines += lines;
prof.fill_curves += curves;
prof.fill_curve_segments_adaptive += adaptive;
for (total, bin) in prof.fill_curve_bins.iter_mut().zip(bins) {
*total += bin;
}
prof.lap(LowerBucket::Census);
}
flatten_into(path, ctm, &mut out.points, &mut out.subpaths);
#[cfg(feature = "profiling")]
{
out.lower_prof.lap(LowerBucket::FillFlatten);
out.lower_prof.fill_points += (out.points.len() - pt_start) as u64;
}
let range_end = out.subpaths.len() as u32;
if range_end == range_start {
return None; }
let Some((bx0, by0, bx1, by1)) =
device_bounds_sane(&out.points[pt_start..], out.size, out.sanity_extent)
else {
#[cfg(feature = "profiling")]
{
out.lower_prof.cull_fill_insane += 1;
}
out.points.truncate(pt_start);
out.subpaths.truncate(range_start as usize);
return None;
};
let mut bounds = DeviceRect {
x: bx0,
y: by0,
width: (bx1 - bx0).max(0) as u32,
height: (by1 - by0).max(0) as u32,
};
let clip_has_mask = if let Some(cid) = clip {
let c = &out.clips[cid as usize];
bounds = intersect(bounds, c.bounds);
c.has_mask
} else {
false
};
if let Some(stencil) = &stencil {
bounds = intersect(bounds, stencil.bounds);
}
if bounds.width == 0 || bounds.height == 0 {
#[cfg(feature = "profiling")]
{
out.lower_prof.cull_fill_clipped += 1;
out.lower_prof.cull_fill_clipped_points += (out.points.len() - pt_start) as u64;
}
out.points.truncate(pt_start);
out.subpaths.truncate(range_start as usize);
return None;
}
let alpha = to_u8(op_alpha * color.a);
let rgb = [to_u8(color.r), to_u8(color.g), to_u8(color.b)];
let opaque = alpha == 255;
let krule = match rule {
crate::page_ir::FillRule::NonZero => FillRule::NonZero,
crate::page_ir::FillRule::EvenOdd => FillRule::EvenOdd,
};
let class = if shading.is_none()
&& opaque
&& !clip_has_mask
&& !soft_active
&& matches!(blend, crate::page_ir::BlendMode::Normal)
&& range_end - range_start == 1
&& is_integer_rect(
&out.points[pt_start..],
bx0 as f32,
by0 as f32,
bx1 as f32,
by1 as f32,
) {
DrawClass::OpaqueRect
} else {
DrawClass::SolidPath
};
out.ops.push(PreparedOp::Draw(PreparedCommand {
origin: crate::page_ir::PaintOrigin::default(),
class,
subpath_range: (range_start, range_end),
rule: krule,
rgb,
premul: [rgb[0], rgb[1], rgb[2], 255],
alpha,
opaque,
bounds,
clip,
clip_has_mask,
blend,
shading,
stencil,
}));
Some(bounds)
}
const MAX_TILES: usize = 1 << 14;
#[allow(clippy::too_many_arguments)]
fn lower_tiled(
out: &mut CpuPreparedPage,
path: &PathData,
ctm: Matrix,
rule: crate::page_ir::FillRule,
tiling: &TilingPattern,
pattern_to_device: Matrix,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
color_policy: crate::render_api::RenderColorPolicy,
stencil: Option<Box<crate::render_cpu::image::PreparedImage>>,
) -> Option<DeviceRect> {
let range_start = out.subpaths.len() as u32;
let pt_start = out.points.len();
flatten_into(path, ctm, &mut out.points, &mut out.subpaths);
finish_tiled_fill(
out,
range_start,
pt_start,
rule,
tiling,
pattern_to_device,
op_alpha,
clip,
blend,
color_policy,
stencil,
)
}
#[allow(clippy::too_many_arguments)]
fn finish_tiled_fill(
out: &mut CpuPreparedPage,
range_start: u32,
pt_start: usize,
rule: crate::page_ir::FillRule,
tiling: &TilingPattern,
pattern_to_device: Matrix,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
color_policy: crate::render_api::RenderColorPolicy,
stencil: Option<Box<crate::render_cpu::image::PreparedImage>>,
) -> Option<DeviceRect> {
let range_end = out.subpaths.len() as u32;
if range_end == range_start {
return None;
}
let (bx0, by0, bx1, by1) = device_bounds(&out.points[pt_start..], out.size);
let mut bounds = DeviceRect {
x: bx0,
y: by0,
width: (bx1 - bx0).max(0) as u32,
height: (by1 - by0).max(0) as u32,
};
let clip_has_mask = if let Some(cid) = clip {
let c = &out.clips[cid as usize];
bounds = intersect(bounds, c.bounds);
c.has_mask
} else {
false
};
if bounds.width == 0 || bounds.height == 0 {
out.points.truncate(pt_start);
out.subpaths.truncate(range_start as usize);
return None;
}
let x_step = tiling.x_step.abs() as f64;
let y_step = tiling.y_step.abs() as f64;
let tiles = enumerate_tiles(bounds, pattern_to_device, tiling, x_step, y_step);
if tiles.is_empty() {
out.points.truncate(pt_start);
out.subpaths.truncate(range_start as usize);
return None;
}
let krule = match rule {
crate::page_ir::FillRule::NonZero => FillRule::NonZero,
crate::page_ir::FillRule::EvenOdd => FillRule::EvenOdd,
};
out.ops.push(PreparedOp::TiledFill(Box::new(PreparedTiling {
origin: crate::page_ir::PaintOrigin::default(),
bounds,
clip,
clip_has_mask,
fill_subpaths: (range_start, range_end),
fill_rule: krule,
alpha: to_u8(op_alpha),
cell: tiling.cell.clone(),
pattern_to_device,
uncolored: tiling.uncolored,
under: recolored_bytes(&tiling.under_color, color_policy),
color_policy,
tiles,
blend,
stencil,
})));
Some(bounds)
}
#[allow(clippy::too_many_arguments)]
fn lower_tiled_stroke(
out: &mut CpuPreparedPage,
path: &PathData,
ctm: Matrix,
style: &StrokeStyle,
tiling: &TilingPattern,
pattern_to_device: Matrix,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
color_policy: crate::render_api::RenderColorPolicy,
) -> Option<DeviceRect> {
let (range_start, pt_start, _) = append_stroke_outline(out, path, ctm, style)?;
finish_tiled_fill(
out,
range_start,
pt_start,
crate::page_ir::FillRule::NonZero,
tiling,
pattern_to_device,
op_alpha,
clip,
blend,
color_policy,
None,
)
}
fn enumerate_tiles(
bounds: DeviceRect,
pattern_to_device: Matrix,
tiling: &TilingPattern,
x_step: f64,
y_step: f64,
) -> Vec<Matrix> {
if x_step <= 1e-6 || y_step <= 1e-6 {
return Vec::new();
}
if !pattern_to_device.is_stably_invertible() {
return Vec::new();
}
let Some(inv) = pattern_to_device.invert() else {
return Vec::new();
};
let (dx0, dy0) = (bounds.x as f64, bounds.y as f64);
let (dx1, dy1) = (
(bounds.x + bounds.width as i32) as f64,
(bounds.y + bounds.height as i32) as f64,
);
let corners = [
inv.apply(Point { x: dx0, y: dy0 }),
inv.apply(Point { x: dx1, y: dy0 }),
inv.apply(Point { x: dx1, y: dy1 }),
inv.apply(Point { x: dx0, y: dy1 }),
];
let (mut px0, mut py0, mut px1, mut py1) = (
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
);
for c in corners {
px0 = px0.min(c.x);
py0 = py0.min(c.y);
px1 = px1.max(c.x);
py1 = py1.max(c.y);
}
let [bbx0, bby0, bbx1, bby1] = [
tiling.bbox[0] as f64,
tiling.bbox[1] as f64,
tiling.bbox[2] as f64,
tiling.bbox[3] as f64,
];
let i0 = ((px0 - bbx1) / x_step).floor() as i64;
let i1 = ((px1 - bbx0) / x_step).ceil() as i64;
let j0 = ((py0 - bby1) / y_step).floor() as i64;
let j1 = ((py1 - bby0) / y_step).ceil() as i64;
let (ni, nj) = ((i1 - i0 + 1).max(0) as u64, (j1 - j0 + 1).max(0) as u64);
if ni.saturating_mul(nj) > MAX_TILES as u64 {
return Vec::new();
}
let mut tiles = Vec::new();
for j in j0..=j1 {
for i in i0..=i1 {
let t = Matrix::translate(i as f64 * x_step, j as f64 * y_step).then(pattern_to_device);
tiles.push(t);
}
}
tiles
}
fn x_unit(m: Matrix) -> f64 {
if m.b == 0.0 {
m.a.abs()
} else if m.a == 0.0 {
m.b.abs()
} else {
m.a.hypot(m.b)
}
}
fn y_unit(m: Matrix) -> f64 {
if m.c == 0.0 {
m.d.abs()
} else if m.d == 0.0 {
m.c.abs()
} else {
m.c.hypot(m.d)
}
}
fn decompose_pen(ctm: Matrix) -> Option<(Matrix, Matrix)> {
if !ctm.is_finite() {
return None;
}
let s = ctm.a.abs().max(ctm.b.abs());
if s == 0.0 || !s.is_finite() {
return None;
}
let m2 = Matrix {
a: ctm.a / s,
b: ctm.b / s,
c: ctm.c / s,
d: ctm.d / s,
e: 0.0,
f: 0.0,
};
let m1 = ctm.then(m2.invert()?);
Some((m1, m2))
}
fn append_stroke_outline(
out: &mut CpuPreparedPage,
path: &PathData,
ctm: Matrix,
style: &StrokeStyle,
) -> Option<(u32, usize, (i32, i32, i32, i32))> {
let (m1, m2) = decompose_pen(ctm)?;
let scale = m1.a as f32;
let unit = 1.0 / ((x_unit(m2) + y_unit(m2)) / 2.0);
let raw_dw = (style.width as f32 * scale).max(unit as f32);
let pen_axis = x_unit(m2).max(y_unit(m2)) as f32;
let device_extent = raw_dw * pen_axis;
let max_output = out
.sanity_extent
.max(out.size.width.max(out.size.height).max(1) as f32);
let dw = if device_extent.is_finite() && device_extent <= max_output {
raw_dw
} else {
unit as f32
};
let hw = dw * 0.5;
let miter = style.miter_limit as f32;
let dash: Vec<f32> = style
.dash_pattern
.iter()
.map(|d| *d as f32 * scale)
.collect();
let phase = style.dash_phase as f32 * scale;
let dashed = dash.iter().any(|d| *d > 0.0);
let range_start = out.subpaths.len() as u32;
let pt_start = out.points.len();
#[cfg(feature = "profiling")]
if !out.lower_prof.disabled {
out.lower_prof.lap(LowerBucket::StrokeFinish);
let (lines, curves, adaptive, _) = LowerProf::path_census(path, m1);
let prof = &mut out.lower_prof;
prof.stroke_ops += 1;
prof.stroke_lines += lines;
prof.stroke_curves += curves;
prof.stroke_curve_segments_adaptive += adaptive;
if dashed {
prof.stroke_dashed_ops += 1;
}
match style.join {
crate::page_ir::LineJoin::Round => prof.stroke_join_round += 1,
crate::page_ir::LineJoin::Miter => prof.stroke_join_miter += 1,
crate::page_ir::LineJoin::Bevel => prof.stroke_join_bevel += 1,
}
let device_hw = hw * pen_axis;
let bin = if device_hw <= 0.5 {
0
} else if device_hw <= 1.6 {
1
} else if device_hw <= 6.5 {
2
} else {
3
};
prof.stroke_hw_bins[bin] += 1;
prof.lap(LowerBucket::Census);
}
let polylines = flatten_polylines(path, m1);
#[cfg(feature = "profiling")]
if !out.lower_prof.disabled {
out.lower_prof.lap(LowerBucket::StrokeFlatten);
out.lower_prof.vertex_census(&polylines, hw);
out.lower_prof.lap(LowerBucket::Census);
}
for (poly, closed) in polylines {
if dashed {
for piece in stroke::dash_polyline(&poly, closed, &dash, phase) {
#[cfg(feature = "profiling")]
{
out.lower_prof.stroke_dash_pieces += 1;
}
stroke::expand_stroke(
&piece,
false,
hw,
style.cap,
style.join,
miter,
&mut out.points,
&mut out.subpaths,
);
}
} else {
stroke::expand_stroke(
&poly,
closed,
hw,
style.cap,
style.join,
miter,
&mut out.points,
&mut out.subpaths,
);
}
}
let range_end = out.subpaths.len() as u32;
#[cfg(feature = "profiling")]
if !out.lower_prof.disabled {
out.lower_prof.lap(LowerBucket::StrokeExpand);
let appended = &out.subpaths[range_start as usize..];
out.lower_prof.stroke_output_census(appended);
out.lower_prof.lap(LowerBucket::Census);
}
if range_end == range_start {
return None;
}
if m2 != Matrix::IDENTITY {
for p in &mut out.points[pt_start..] {
let q = m2.apply(Point {
x: p[0] as f64,
y: p[1] as f64,
});
*p = [q.x as f32, q.y as f32];
}
}
let Some((bx0, by0, bx1, by1)) =
device_bounds_sane(&out.points[pt_start..], out.size, out.sanity_extent)
else {
#[cfg(feature = "profiling")]
{
out.lower_prof.cull_stroke_insane += 1;
}
out.points.truncate(pt_start);
out.subpaths.truncate(range_start as usize);
return None;
};
Some((range_start, pt_start, (bx0, by0, bx1, by1)))
}
#[allow(clippy::too_many_arguments)]
fn lower_stroke(
out: &mut CpuPreparedPage,
path: &PathData,
ctm: Matrix,
style: &StrokeStyle,
color: crate::page_ir::Color,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
shading: Option<Box<PreparedShading>>,
) -> Option<DeviceRect> {
let (range_start, pt_start, (bx0, by0, bx1, by1)) =
append_stroke_outline(out, path, ctm, style)?;
let range_end = out.subpaths.len() as u32;
let mut bounds = DeviceRect {
x: bx0,
y: by0,
width: (bx1 - bx0).max(0) as u32,
height: (by1 - by0).max(0) as u32,
};
let clip_has_mask = if let Some(cid) = clip {
let c = &out.clips[cid as usize];
bounds = intersect(bounds, c.bounds);
c.has_mask
} else {
false
};
if bounds.width == 0 || bounds.height == 0 {
#[cfg(feature = "profiling")]
{
out.lower_prof.cull_stroke_clipped += 1;
out.lower_prof.cull_stroke_clipped_points += (out.points.len() - pt_start) as u64;
}
out.points.truncate(pt_start);
out.subpaths.truncate(range_start as usize);
return None;
}
let alpha = to_u8(op_alpha * color.a);
let rgb = [to_u8(color.r), to_u8(color.g), to_u8(color.b)];
out.ops.push(PreparedOp::Draw(PreparedCommand {
origin: crate::page_ir::PaintOrigin::default(),
class: DrawClass::SolidPath,
subpath_range: (range_start, range_end),
rule: FillRule::NonZero, rgb,
premul: [rgb[0], rgb[1], rgb[2], 255],
alpha,
opaque: alpha == 255,
bounds,
clip,
clip_has_mask,
blend,
shading,
stencil: None,
}));
Some(bounds)
}
#[allow(clippy::too_many_arguments)]
fn lower_glyph_boxes(
out: &mut CpuPreparedPage,
run: &GlyphRun,
ctm: Matrix,
color: crate::page_ir::Color,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
) -> Option<DeviceRect> {
if run.glyphs.is_empty() {
return None;
}
let range_start = out.subpaths.len() as u32;
let pt_start = out.points.len();
append_glyph_boxes(out, run, ctm);
finish_glyph_fill(out, range_start, pt_start, clip, color, op_alpha, blend)
}
#[allow(clippy::too_many_arguments)]
fn lower_glyph_boxes_split(
out: &mut CpuPreparedPage,
run: &GlyphRun,
ctm: Matrix,
color: crate::page_ir::Color,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
) -> Option<DeviceRect> {
let mut bounds = None;
for glyphs in run.glyphs.chunks(8) {
let batch = GlyphRun {
glyphs: Arc::from(glyphs),
..run.clone()
};
bounds = union_rect(
bounds,
lower_glyph_boxes(out, &batch, ctm, color, op_alpha, clip, blend),
);
}
bounds
}
fn append_glyph_boxes(out: &mut CpuPreparedPage, run: &GlyphRun, ctm: Matrix) {
let m = run.transform.then(ctm);
let fs = run.font_size;
let pad = fs * 0.07;
let asc = fs * 0.60;
for (i, gph) in run.glyphs.iter().enumerate() {
if gph.glyph == 32 {
continue; }
let adv = if i + 1 < run.glyphs.len() {
run.glyphs[i + 1].x - gph.x
} else {
fs * 0.5
};
let box_w = (adv * 0.85).clamp(fs * 0.12, fs * 0.7);
let (x0, y0) = (gph.x + pad, gph.y);
let (x1, y1) = (x0 + box_w, gph.y + asc);
let start = out.points.len();
for p in [
Point { x: x0, y: y0 },
Point { x: x1, y: y0 },
Point { x: x1, y: y1 },
Point { x: x0, y: y1 },
] {
let d = m.apply(p);
out.points.push([d.x as f32, d.y as f32]);
}
out.subpaths.push((start, out.points.len()));
}
}
fn append_glyph_run_clip(
out: &mut CpuPreparedPage,
run: &GlyphRun,
program: Option<&FontProgram>,
ctm: Matrix,
synth: GlyphSynthesis,
) {
if run.glyphs.is_empty() {
return;
}
match program {
Some(prog) => {
let upem = prog.units_per_em().max(1) as f64;
let scale = run.font_size / upem;
let m = run.transform.then(ctm);
let gids: Vec<u32> = run.glyphs.iter().map(|g| g.glyph).collect();
let mut outlines = prog.outlines(&gids);
synth.apply(&mut outlines, prog);
for (gph, outline) in run.glyphs.iter().zip(&outlines) {
if let Some(outline) = outline {
append_outline(out, outline, gph.x, gph.y, scale, m);
}
}
}
None => append_glyph_boxes(out, run, ctm),
}
}
#[allow(clippy::too_many_arguments)]
fn push_text_clip(
out: &mut CpuPreparedPage,
clip_stack: &mut Vec<u32>,
share: &mut ClipShare,
runs: &[crate::page_ir::GlyphRunId],
page: &CompiledPage,
ctm: Matrix,
font_programs: &mut HashMap<u32, Option<FontProgram>>,
shared: Option<&SharedFontProgramCache>,
) {
let pt_start = out.points.len();
let range_start = out.subpaths.len() as u32;
for run_id in runs {
let gr = &page.glyph_runs[run_id.index()];
let program = resolve_font_program(font_programs, page, gr.font, shared);
let synth = GlyphSynthesis::for_font(&page.fonts[gr.font.index()]);
append_glyph_run_clip(out, gr, program.as_ref(), ctm, synth);
}
let range_end = out.subpaths.len() as u32;
let parent = clip_stack.last().copied();
let (kind, bounds) = if range_end == range_start {
(
ClipKind::Rect,
DeviceRect {
x: 0,
y: 0,
width: 0,
height: 0,
},
)
} else {
let (bx0, by0, bx1, by1) = device_bounds(&out.points[pt_start..], out.size);
let path_rect = DeviceRect {
x: bx0,
y: by0,
width: (bx1 - bx0).max(0) as u32,
height: (by1 - by0).max(0) as u32,
};
let bounds = match parent.map(|p| out.clips[p as usize].bounds) {
Some(pb) => intersect(pb, path_rect),
None => path_rect,
};
(
ClipKind::Path {
subpath_range: (range_start, range_end),
rule: FillRule::NonZero,
},
bounds,
)
};
let has_mask = matches!(kind, ClipKind::Path { .. })
|| parent
.map(|p| out.clips[p as usize].has_mask)
.unwrap_or(false);
let (kind, mask_source) = share.resolve(out, kind, bounds, parent);
let cid = out.clips.len() as u32;
out.clips.push(PreparedClip {
parent,
bounds,
mask_bounds: intersect(bounds, row_window(out)),
kind,
has_mask,
mask_source,
});
clip_stack.push(cid);
}
fn resolve_font_program(
local: &mut HashMap<u32, Option<FontProgram>>,
page: &CompiledPage,
font: crate::page_ir::FontId,
shared: Option<&SharedFontProgramCache>,
) -> Option<FontProgram> {
if let Some(program) = local.get(&font.0) {
return program.clone();
}
let resource = &page.fonts[font.index()];
let program = resolve_program_bytes(resource, shared);
local.insert(font.0, program.clone());
program
}
const MIN_PARSE_TO_CACHE: std::time::Duration = std::time::Duration::from_micros(400);
#[inline]
fn should_retain_font_program(program: &FontProgram, parse_cost: std::time::Duration) -> bool {
program.is_type1() || (program.benefits_from_parse_cache() && parse_cost >= MIN_PARSE_TO_CACHE)
}
fn resolve_program_bytes(
resource: &crate::page_ir::FontResource,
shared: Option<&SharedFontProgramCache>,
) -> Option<FontProgram> {
let Some(shared) = shared else {
return parse_font_program(resource);
};
if resource.program.is_empty() {
return None;
}
let key = FontProgramKey::for_resource(resource);
if let Some(program) = shared.get(&key) {
return Some(program);
}
let start = std::time::Instant::now();
let program = parse_font_program(resource);
let parse_cost = start.elapsed();
if let Some(prog) = &program
&& should_retain_font_program(prog, parse_cost)
{
shared.insert(key, prog.clone(), prog.retained_bytes());
}
program
}
fn parse_font_program(resource: &crate::page_ir::FontResource) -> Option<FontProgram> {
if resource.program.is_empty() {
None
} else {
FontProgram::parse_indexed(resource.program.clone(), resource.face_index)
}
}
const MAX_CACHED_PPEM: f64 = 200.0;
const MAX_GLYPH_CELLS: usize = 1 << 20;
fn glyph_subpixel_steps() -> (i32, i32) {
use std::sync::OnceLock;
static STEPS: OnceLock<(i32, i32)> = OnceLock::new();
*STEPS.get_or_init(|| match std::env::var("PDF_RENDERER_GLYPH_SUBPIXEL") {
Ok(v) => {
let mut it = v.split(',').map(|s| s.trim().parse::<i32>().ok());
let nx = it.next().flatten().unwrap_or(4).clamp(1, 64);
let ny = it.next().flatten().unwrap_or(nx).clamp(1, 64);
(nx, ny)
}
Err(_) => (4, 4),
})
}
#[inline]
fn quantize_origin(v: f64, n: i32) -> (i32, i16) {
let base = v.floor();
let frac = v - base;
let mut bucket = (frac * n as f64).round() as i32;
let mut base = base as i32;
if bucket >= n {
bucket -= n;
base += 1;
}
(base, bucket as i16)
}
#[allow(clippy::too_many_arguments)]
fn try_cached_glyph_run(
out: &mut CpuPreparedPage,
run: &GlyphRun,
prog: &FontProgram,
ctm: Matrix,
color: crate::page_ir::Color,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
cache: &SharedGlyphCache,
font_id: FontProgramKey,
raster: &mut crate::render_cpu::raster::RasterKernel,
) -> Option<Option<DeviceRect>> {
if run.glyphs.is_empty() {
return Some(None);
}
const EPS: f64 = 1e-6;
let upem = prog.units_per_em().max(1) as f64;
let scale = run.font_size / upem;
let m = run.transform.then(ctm);
let axis_aligned = m.b.abs() < EPS && m.c.abs() < EPS;
if !axis_aligned {
return None;
}
let ppem = run.font_size * m.d.abs();
if !ppem.is_finite() || ppem <= 0.0 || ppem > MAX_CACHED_PPEM {
return None;
}
let (la, ld) = (m.a * scale, m.d * scale);
let uniform = (m.a.abs() - m.d.abs()).abs() < 1e-4 * m.a.abs().max(1.0);
let hinted = uniform && !prog.is_type1() && out.hinting.should_hint(ppem as f32, axis_aligned);
let flip_x = m.a.signum();
let flip_y = m.d.signum();
let n = run.glyphs.len();
let (nx, ny) = glyph_subpixel_steps();
let placed: Vec<(i32, i32, i16, i16)> = run
.glyphs
.iter()
.map(|g| {
let o = m.apply(Point { x: g.x, y: g.y });
let (ox, sx) = quantize_origin(o.x, nx);
let (oy, sy) = quantize_origin(o.y, ny);
(ox, oy, sx, sy)
})
.collect();
let mut slots: Vec<Option<GlyphPlacement>> = vec![None; n];
let mut miss_keys: Vec<(usize, GlyphCacheKey)> = Vec::new();
let mut hits = 0u64;
for (gi, gph) in run.glyphs.iter().enumerate() {
let (ox, oy, sx, sy) = placed[gi];
let key = GlyphCacheKey {
font: font_id,
glyph: gph.glyph,
la_bits: la.to_bits(),
ld_bits: ld.to_bits(),
ppem_bits: if hinted { (ppem as f32).to_bits() } else { 0 },
sx,
sy,
hinted,
};
match cache.get(&key) {
Some(bitmap) => {
hits += 1;
slots[gi] = place_glyph(bitmap, (ox, oy));
}
None => miss_keys.push((gi, key)),
}
}
if !miss_keys.is_empty() {
let miss_gids: Vec<u32> = miss_keys
.iter()
.map(|&(gi, _)| run.glyphs[gi].glyph)
.collect();
let extracted: Vec<Option<crate::font::Outline>> = if hinted {
match prog.outlines_hinted(&miss_gids, ppem as f32) {
Some(v) => v,
None => return None,
}
} else {
prog.outlines(&miss_gids)
};
for (&(gi, key), outline) in miss_keys.iter().zip(&extracted) {
let (ox, oy, sx, sy) = placed[gi];
let fox = sx as f64 / nx as f64;
let foy = sy as f64 / ny as f64;
let bitmap = match outline {
Some(outline) if hinted => rasterize_glyph_bitmap(
outline,
|p| {
[
(flip_x * p[0] as f64 + fox) as f32,
(flip_y * p[1] as f64 + foy) as f32,
]
},
raster,
),
Some(outline) => rasterize_glyph_bitmap(
outline,
|p| {
[
(la * p[0] as f64 + fox) as f32,
(ld * p[1] as f64 + foy) as f32,
]
},
raster,
),
None => empty_glyph_bitmap(),
};
cache.insert(key, bitmap.clone());
slots[gi] = place_glyph(bitmap, (ox, oy));
}
}
#[cfg(feature = "profiling")]
{
let mut profile = out.profile.borrow_mut();
profile.increment("lower.glyph.count", n as u64);
profile.increment("lower.glyph.cache_hits", hits);
profile.increment("lower.glyph.cache_misses", miss_keys.len() as u64);
profile.increment("lower.glyph.cached_runs", 1);
}
#[cfg(not(feature = "profiling"))]
let _ = hits;
let placements: Vec<GlyphPlacement> = slots.into_iter().flatten().collect();
if placements.is_empty() {
return Some(None);
}
let (mut x0, mut y0, mut x1, mut y1) = (i32::MAX, i32::MAX, i32::MIN, i32::MIN);
for p in &placements {
x0 = x0.min(p.dx);
y0 = y0.min(p.dy);
x1 = x1.max(p.dx + p.bitmap.width as i32);
y1 = y1.max(p.dy + p.bitmap.height as i32);
}
x0 = x0.max(0);
y0 = y0.max(0);
x1 = x1.min(out.size.width as i32);
y1 = y1.min(out.size.height as i32);
if x1 <= x0 || y1 <= y0 {
return Some(None);
}
let mut bounds = DeviceRect {
x: x0,
y: y0,
width: (x1 - x0) as u32,
height: (y1 - y0) as u32,
};
let clip_has_mask = if let Some(cid) = clip {
let c = &out.clips[cid as usize];
bounds = intersect(bounds, c.bounds);
c.has_mask
} else {
false
};
if bounds.width == 0 || bounds.height == 0 {
return Some(None);
}
let alpha = to_u8(op_alpha * color.a);
let rgb = [to_u8(color.r), to_u8(color.g), to_u8(color.b)];
out.ops
.push(PreparedOp::GlyphRun(Box::new(PreparedGlyphRun {
origin: crate::page_ir::PaintOrigin::default(),
placements,
rgb,
alpha,
opaque: alpha == 255,
bounds,
clip,
clip_has_mask,
blend,
shading: None,
})));
Some(Some(bounds))
}
fn place_glyph(bitmap: Arc<GlyphBitmap>, origin: (i32, i32)) -> Option<GlyphPlacement> {
if bitmap.width == 0 || bitmap.height == 0 {
return None;
}
let (ox, oy) = origin;
Some(GlyphPlacement {
dx: ox + bitmap.left,
dy: oy + bitmap.top,
bitmap,
})
}
fn empty_glyph_bitmap() -> Arc<GlyphBitmap> {
Arc::new(GlyphBitmap {
left: 0,
top: 0,
width: 0,
height: 0,
cov: Box::from([] as [u8; 0]),
})
}
fn rasterize_glyph_bitmap(
outline: &crate::font::Outline,
map: impl Fn([f32; 2]) -> [f32; 2],
raster: &mut crate::render_cpu::raster::RasterKernel,
) -> Arc<GlyphBitmap> {
let mut points: Vec<[f32; 2]> = Vec::new();
let mut subpaths: Vec<(usize, usize)> = Vec::new();
flatten_outline_into(outline, map, &mut points, &mut subpaths);
if points.is_empty() || subpaths.is_empty() {
return empty_glyph_bitmap();
}
let (mut minx, mut miny, mut maxx, mut maxy) = (
f32::INFINITY,
f32::INFINITY,
f32::NEG_INFINITY,
f32::NEG_INFINITY,
);
for p in &points {
minx = minx.min(p[0]);
miny = miny.min(p[1]);
maxx = maxx.max(p[0]);
maxy = maxy.max(p[1]);
}
if !minx.is_finite() || !miny.is_finite() || !maxx.is_finite() || !maxy.is_finite() {
return empty_glyph_bitmap();
}
let left = minx.floor() as i32;
let top = miny.floor() as i32;
let width = ((maxx.ceil() as i32) - left).max(1) as usize;
let height = ((maxy.ceil() as i32) - top).max(1) as usize;
if width.saturating_mul(height) > MAX_GLYPH_CELLS {
return empty_glyph_bitmap();
}
for p in &mut points {
p[0] -= left as f32;
p[1] -= top as f32;
}
let mut cov = vec![0u8; width * height];
raster.fill(
&points,
&subpaths,
width,
height,
FillRule::NonZero,
|y, x0, x1, row: &mut [u8]| {
let base = y * width;
cov[base + x0..=base + x1].copy_from_slice(&row[x0..=x1]);
},
);
Arc::new(GlyphBitmap {
left,
top,
width: width as u32,
height: height as u32,
cov: cov.into_boxed_slice(),
})
}
fn flatten_outline_into(
outline: &crate::font::Outline,
dev: impl Fn([f32; 2]) -> [f32; 2],
points: &mut Vec<[f32; 2]>,
subpaths: &mut Vec<(usize, usize)>,
) {
let flatness = outline_flatness();
let mut pt = 0usize;
let mut start = points.len();
let mut cur = [0f32; 2];
for verb in &outline.verbs {
match verb {
crate::font::OutlineVerb::MoveTo => {
if points.len() > start {
subpaths.push((start, points.len()));
}
start = points.len();
cur = dev(outline.points[pt]);
points.push(cur);
pt += 1;
}
crate::font::OutlineVerb::LineTo => {
cur = dev(outline.points[pt]);
points.push(cur);
pt += 1;
}
crate::font::OutlineVerb::QuadTo => {
let c = dev(outline.points[pt]);
let e = dev(outline.points[pt + 1]);
pt += 2;
flatten_quad(points, cur, c, e, flatness);
cur = e;
}
crate::font::OutlineVerb::CurveTo => {
let c1 = dev(outline.points[pt]);
let c2 = dev(outline.points[pt + 1]);
let e = dev(outline.points[pt + 2]);
pt += 3;
flatten_cubic(points, cur, c1, c2, e, flatness);
cur = e;
}
crate::font::OutlineVerb::Close => {
if points.len() > start {
subpaths.push((start, points.len()));
}
start = points.len();
}
}
}
if points.len() > start {
subpaths.push((start, points.len()));
}
}
#[derive(Debug, Clone, Copy, PartialEq, Default)]
struct GlyphSynthesis {
shear: f32,
embolden_em: f32,
}
impl GlyphSynthesis {
fn for_font(res: &crate::page_ir::FontResource) -> Self {
Self {
shear: res.synthetic_shear,
embolden_em: res.synthetic_embolden_em,
}
}
fn is_active(&self) -> bool {
self.shear != 0.0 || self.embolden_em > 0.0
}
fn apply(&self, outlines: &mut [Option<crate::font::Outline>], prog: &FontProgram) {
if !self.is_active() {
return;
}
let strength = self.embolden_em * prog.units_per_em().max(1) as f32;
for outline in outlines.iter_mut().flatten() {
if strength > 0.0 {
outline.embolden(strength);
}
outline.oblique(self.shear);
}
}
}
#[allow(clippy::too_many_arguments)]
fn lower_glyph_outlines(
out: &mut CpuPreparedPage,
run: &GlyphRun,
prog: &FontProgram,
ctm: Matrix,
color: crate::page_ir::Color,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
synth: GlyphSynthesis,
) -> Option<DeviceRect> {
if run.glyphs.is_empty() {
return None;
}
let range_start = out.subpaths.len() as u32;
let pt_start = out.points.len();
append_glyph_outlines(out, run, prog, ctm, synth);
finish_glyph_fill(out, range_start, pt_start, clip, color, op_alpha, blend)
}
#[allow(clippy::too_many_arguments)]
fn lower_glyph_outlines_split(
out: &mut CpuPreparedPage,
run: &GlyphRun,
prog: &FontProgram,
ctm: Matrix,
color: crate::page_ir::Color,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
synth: GlyphSynthesis,
) -> Option<DeviceRect> {
let mut bounds = None;
for glyphs in run.glyphs.chunks(8) {
let batch = GlyphRun {
glyphs: Arc::from(glyphs),
..run.clone()
};
bounds = union_rect(
bounds,
lower_glyph_outlines(out, &batch, prog, ctm, color, op_alpha, clip, blend, synth),
);
}
bounds
}
#[allow(clippy::too_many_arguments)]
fn lower_tiled_glyph_run(
out: &mut CpuPreparedPage,
run: &GlyphRun,
program: Option<&FontProgram>,
ctm: Matrix,
synth: GlyphSynthesis,
tiling: &TilingPattern,
pattern_to_device: Matrix,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
color_policy: crate::render_api::RenderColorPolicy,
) -> Option<DeviceRect> {
if run.glyphs.is_empty() {
return None;
}
let range_start = out.subpaths.len() as u32;
let pt_start = out.points.len();
match program {
Some(prog) => append_glyph_outlines(out, run, prog, ctm, synth),
None => append_glyph_boxes(out, run, ctm),
}
finish_tiled_fill(
out,
range_start,
pt_start,
crate::page_ir::FillRule::NonZero,
tiling,
pattern_to_device,
op_alpha,
clip,
blend,
color_policy,
None,
)
}
fn append_glyph_outlines(
out: &mut CpuPreparedPage,
run: &GlyphRun,
prog: &FontProgram,
ctm: Matrix,
synth: GlyphSynthesis,
) {
let upem = prog.units_per_em().max(1) as f64;
let scale = run.font_size / upem;
let m = run.transform.then(ctm);
let gids: Vec<u32> = run.glyphs.iter().map(|g| g.glyph).collect();
let hinted = if synth.is_active() {
None
} else {
try_hinted_glyphs(out, run, prog, m, &gids)
};
if let Some(hinted) = hinted {
for (gph, outline) in run.glyphs.iter().zip(&hinted.outlines) {
if let Some(outline) = outline {
append_hinted_outline(out, outline, gph.x, gph.y, m, hinted.flip_x, hinted.flip_y);
}
}
} else {
#[cfg(feature = "profiling")]
let outline_start = std::time::Instant::now();
let mut outlines = prog.outlines(&gids);
synth.apply(&mut outlines, prog);
#[cfg(feature = "profiling")]
{
out.profile
.borrow_mut()
.add_duration("lower.glyph.outline_extract", outline_start.elapsed());
out.profile
.borrow_mut()
.increment("lower.glyph.count", gids.len() as u64);
}
#[cfg(feature = "profiling")]
let emit_start = std::time::Instant::now();
for (gph, outline) in run.glyphs.iter().zip(&outlines) {
if let Some(outline) = outline {
append_outline(out, outline, gph.x, gph.y, scale, m);
}
}
#[cfg(feature = "profiling")]
out.profile
.borrow_mut()
.add_duration("lower.glyph.emit", emit_start.elapsed());
}
}
#[allow(clippy::too_many_arguments)]
fn lower_glyph_stroke(
out: &mut CpuPreparedPage,
run: &GlyphRun,
prog: &FontProgram,
ctm: Matrix,
style: &StrokeStyle,
color: crate::page_ir::Color,
op_alpha: f32,
clip: Option<u32>,
blend: crate::page_ir::BlendMode,
synth: GlyphSynthesis,
shading: Option<Box<PreparedShading>>,
) -> Option<DeviceRect> {
if run.glyphs.is_empty() {
return None;
}
let upem = prog.units_per_em().max(1) as f64;
let scale = run.font_size / upem;
let gids: Vec<u32> = run.glyphs.iter().map(|g| g.glyph).collect();
let mut outlines = prog.outlines(&gids);
synth.apply(&mut outlines, prog);
let mut verbs: Vec<crate::page_ir::PathVerb> = Vec::new();
let mut points: Vec<Point> = Vec::new();
for (gph, outline) in run.glyphs.iter().zip(&outlines) {
if let Some(outline) = outline {
append_glyph_stroke_path(
&mut verbs,
&mut points,
outline,
gph.x,
gph.y,
scale,
run.transform,
);
}
}
if verbs.is_empty() {
return None;
}
let path = PathData {
verbs: verbs.into(),
points: points.into(),
};
lower_stroke(
out, &path, ctm, style, color, op_alpha, clip, blend, shading,
)
}
fn append_glyph_stroke_path(
verbs: &mut Vec<crate::page_ir::PathVerb>,
points: &mut Vec<Point>,
outline: &crate::font::Outline,
gx: f64,
gy: f64,
scale: f64,
tm: Matrix,
) {
use crate::page_ir::PathVerb;
let map = |o: [f32; 2]| -> Point {
tm.apply(Point {
x: gx + o[0] as f64 * scale,
y: gy + o[1] as f64 * scale,
})
};
let flatness = outline_flatness();
let mut pt = 0usize;
let mut cur = Point::default();
for verb in &outline.verbs {
match verb {
crate::font::OutlineVerb::MoveTo => {
cur = map(outline.points[pt]);
pt += 1;
verbs.push(PathVerb::MoveTo);
points.push(cur);
}
crate::font::OutlineVerb::LineTo => {
cur = map(outline.points[pt]);
pt += 1;
verbs.push(PathVerb::LineTo);
points.push(cur);
}
crate::font::OutlineVerb::QuadTo => {
let c = map(outline.points[pt]);
let e = map(outline.points[pt + 1]);
pt += 2;
let n = curve_segments(
flatness,
quad_deviation([cur.x, cur.y], [c.x, c.y], [e.x, e.y]),
0.25,
);
for i in 1..=n {
let t = i as f64 / n as f64;
let u = 1.0 - t;
verbs.push(PathVerb::LineTo);
points.push(Point {
x: u * u * cur.x + 2.0 * u * t * c.x + t * t * e.x,
y: u * u * cur.y + 2.0 * u * t * c.y + t * t * e.y,
});
}
cur = e;
}
crate::font::OutlineVerb::CurveTo => {
let c1 = map(outline.points[pt]);
let c2 = map(outline.points[pt + 1]);
let e = map(outline.points[pt + 2]);
pt += 3;
let n = curve_segments(
flatness,
cubic_deviation([cur.x, cur.y], [c1.x, c1.y], [c2.x, c2.y], [e.x, e.y]),
0.75,
);
for i in 1..=n {
let t = i as f64 / n as f64;
let u = 1.0 - t;
let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
verbs.push(PathVerb::LineTo);
points.push(Point {
x: w0 * cur.x + w1 * c1.x + w2 * c2.x + w3 * e.x,
y: w0 * cur.y + w1 * c1.y + w2 * c2.y + w3 * e.y,
});
}
cur = e;
}
crate::font::OutlineVerb::Close => verbs.push(PathVerb::Close),
}
}
}
struct HintedGlyphs {
outlines: Vec<Option<crate::font::Outline>>,
flip_x: f64,
flip_y: f64,
}
fn try_hinted_glyphs(
out: &CpuPreparedPage,
run: &GlyphRun,
prog: &FontProgram,
m: Matrix,
gids: &[u32],
) -> Option<HintedGlyphs> {
const EPS: f64 = 1e-6;
let axis_aligned = m.b.abs() < EPS && m.c.abs() < EPS;
let uniform = (m.a.abs() - m.d.abs()).abs() < 1e-4 * m.a.abs().max(1.0);
let ppem = (run.font_size * m.d.abs()) as f32;
if !axis_aligned || !uniform || !out.hinting.should_hint(ppem, axis_aligned) {
return None;
}
let outlines = prog.outlines_hinted(gids, ppem)?;
Some(HintedGlyphs {
outlines,
flip_x: m.a.signum(),
flip_y: m.d.signum(),
})
}
fn append_hinted_outline(
out: &mut CpuPreparedPage,
outline: &crate::font::Outline,
ox: f64,
oy: f64,
m: Matrix,
flip_x: f64,
flip_y: f64,
) {
let origin = m.apply(Point { x: ox, y: oy });
let (ox, oy) = (origin.x, origin.y.round());
let map = |p: &[f32; 2]| -> [f32; 2] {
[
(ox + flip_x * p[0] as f64) as f32,
(oy + flip_y * p[1] as f64) as f32,
]
};
emit_outline_points(out, outline, map);
}
fn append_outline(
out: &mut CpuPreparedPage,
outline: &crate::font::Outline,
gx: f64,
gy: f64,
scale: f64,
m: Matrix,
) {
emit_outline_points(out, outline, |o: &[f32; 2]| {
let d = m.apply(Point {
x: gx + o[0] as f64 * scale,
y: gy + o[1] as f64 * scale,
});
[d.x as f32, d.y as f32]
});
}
fn emit_outline_points(
out: &mut CpuPreparedPage,
outline: &crate::font::Outline,
dev: impl Fn(&[f32; 2]) -> [f32; 2],
) {
let dev = |p: [f32; 2]| dev(&p);
let flatness = outline_flatness();
let mut pt = 0usize;
let mut start = out.points.len();
let mut cur = [0f32; 2];
for verb in &outline.verbs {
match verb {
crate::font::OutlineVerb::MoveTo => {
if out.points.len() > start {
out.subpaths.push((start, out.points.len()));
}
start = out.points.len();
cur = dev(outline.points[pt]);
out.points.push(cur);
pt += 1;
}
crate::font::OutlineVerb::LineTo => {
cur = dev(outline.points[pt]);
out.points.push(cur);
pt += 1;
}
crate::font::OutlineVerb::QuadTo => {
let c = dev(outline.points[pt]);
let e = dev(outline.points[pt + 1]);
pt += 2;
flatten_quad(&mut out.points, cur, c, e, flatness);
cur = e;
}
crate::font::OutlineVerb::CurveTo => {
let c1 = dev(outline.points[pt]);
let c2 = dev(outline.points[pt + 1]);
let e = dev(outline.points[pt + 2]);
pt += 3;
flatten_cubic(&mut out.points, cur, c1, c2, e, flatness);
cur = e;
}
crate::font::OutlineVerb::Close => {
if out.points.len() > start {
out.subpaths.push((start, out.points.len()));
}
start = out.points.len();
}
}
}
if out.points.len() > start {
out.subpaths.push((start, out.points.len()));
}
}
#[derive(Clone, Copy)]
enum OutlineFlatness {
Fixed(usize),
Adaptive,
}
const OUTLINE_FLATNESS_PX: f64 = 1.0 / 16.0;
const OUTLINE_MAX_SEGMENTS: usize = 64;
fn outline_flatness() -> OutlineFlatness {
use std::sync::OnceLock;
static POLICY: OnceLock<OutlineFlatness> = OnceLock::new();
*POLICY.get_or_init(|| {
match std::env::var("PDF_RENDERER_OUTLINE_SEGMENTS")
.ok()
.and_then(|v| v.trim().parse::<usize>().ok())
{
Some(n) if n > 0 => OutlineFlatness::Fixed(n.min(OUTLINE_MAX_SEGMENTS)),
_ => OutlineFlatness::Adaptive,
}
})
}
#[inline]
fn curve_segments(flatness: OutlineFlatness, deviation: f64, scale: f64) -> usize {
match flatness {
OutlineFlatness::Fixed(n) => n,
OutlineFlatness::Adaptive => {
let n = (scale * deviation / OUTLINE_FLATNESS_PX).sqrt().ceil();
if n.is_finite() {
(n as usize).clamp(1, OUTLINE_MAX_SEGMENTS)
} else {
OUTLINE_MAX_SEGMENTS
}
}
}
}
#[inline]
fn quad_deviation(p: [f64; 2], c: [f64; 2], e: [f64; 2]) -> f64 {
(p[0] - 2.0 * c[0] + e[0])
.abs()
.max((p[1] - 2.0 * c[1] + e[1]).abs())
}
#[inline]
fn cubic_deviation(p: [f64; 2], c1: [f64; 2], c2: [f64; 2], e: [f64; 2]) -> f64 {
quad_deviation(p, c1, c2).max(quad_deviation(c1, c2, e))
}
fn flatten_quad(
points: &mut Vec<[f32; 2]>,
p: [f32; 2],
c: [f32; 2],
e: [f32; 2],
flatness: OutlineFlatness,
) {
let wide = |v: [f32; 2]| [v[0] as f64, v[1] as f64];
let n = curve_segments(flatness, quad_deviation(wide(p), wide(c), wide(e)), 0.25);
for i in 1..=n {
let t = i as f32 / n as f32;
let u = 1.0 - t;
let x = u * u * p[0] + 2.0 * u * t * c[0] + t * t * e[0];
let y = u * u * p[1] + 2.0 * u * t * c[1] + t * t * e[1];
points.push([x, y]);
}
}
fn flatten_cubic(
points: &mut Vec<[f32; 2]>,
p: [f32; 2],
c1: [f32; 2],
c2: [f32; 2],
e: [f32; 2],
flatness: OutlineFlatness,
) {
let wide = |v: [f32; 2]| [v[0] as f64, v[1] as f64];
let n = curve_segments(
flatness,
cubic_deviation(wide(p), wide(c1), wide(c2), wide(e)),
0.75,
);
for i in 1..=n {
let t = i as f32 / n as f32;
let u = 1.0 - t;
let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
let x = w0 * p[0] + w1 * c1[0] + w2 * c2[0] + w3 * e[0];
let y = w0 * p[1] + w1 * c1[1] + w2 * c2[1] + w3 * e[1];
points.push([x, y]);
}
}
fn finish_glyph_fill(
out: &mut CpuPreparedPage,
range_start: u32,
pt_start: usize,
clip: Option<u32>,
color: crate::page_ir::Color,
op_alpha: f32,
blend: crate::page_ir::BlendMode,
) -> Option<DeviceRect> {
let range_end = out.subpaths.len() as u32;
if range_end == range_start {
return None;
}
let (bx0, by0, bx1, by1) = device_bounds(&out.points[pt_start..], out.size);
let mut bounds = DeviceRect {
x: bx0,
y: by0,
width: (bx1 - bx0).max(0) as u32,
height: (by1 - by0).max(0) as u32,
};
let clip_has_mask = if let Some(cid) = clip {
let c = &out.clips[cid as usize];
bounds = intersect(bounds, c.bounds);
c.has_mask
} else {
false
};
note_extent(out, bounds);
bounds = intersect(bounds, row_window(out));
if bounds.width == 0 || bounds.height == 0 {
out.points.truncate(pt_start);
out.subpaths.truncate(range_start as usize);
return None;
}
let alpha = to_u8(op_alpha * color.a);
let rgb = [to_u8(color.r), to_u8(color.g), to_u8(color.b)];
out.ops.push(PreparedOp::Draw(PreparedCommand {
origin: crate::page_ir::PaintOrigin::default(),
class: DrawClass::SolidPath,
subpath_range: (range_start, range_end),
rule: FillRule::NonZero,
rgb,
premul: [rgb[0], rgb[1], rgb[2], 255],
alpha,
opaque: alpha == 255,
bounds,
clip,
clip_has_mask,
blend,
shading: None,
stencil: None,
}));
Some(bounds)
}
fn flatten_polylines(path: &PathData, ctm: Matrix) -> Vec<(Vec<[f32; 2]>, bool)> {
let mut out: Vec<(Vec<[f32; 2]>, bool)> = Vec::new();
let mut cur: Vec<[f32; 2]> = Vec::new();
let mut closed = false;
let mut pt = 0usize;
let mut last = Point::default();
let map = |p: Point| {
let d = ctm.apply(p);
[d.x as f32, d.y as f32]
};
for verb in path.verbs.iter() {
match verb {
PathVerb::MoveTo => {
if !cur.is_empty() {
out.push((std::mem::take(&mut cur), closed));
closed = false;
}
last = path.points[pt];
cur.push(map(last));
pt += 1;
}
PathVerb::LineTo => {
last = path.points[pt];
cur.push(map(last));
pt += 1;
}
PathVerb::CurveTo => {
let p0 = last;
let (c1, c2, p3) = (path.points[pt], path.points[pt + 1], path.points[pt + 2]);
pt += 3;
for i in 1..=CURVE_SEGMENTS {
let t = i as f64 / CURVE_SEGMENTS as f64;
cur.push(map(cubic(p0, c1, c2, p3, t)));
}
last = p3;
}
PathVerb::Close => closed = true,
}
}
if !cur.is_empty() {
out.push((cur, closed));
}
out
}
fn jpx_reduce_disabled() -> bool {
use std::sync::OnceLock;
static DISABLED: OnceLock<bool> = OnceLock::new();
*DISABLED.get_or_init(|| {
std::env::var_os("PDF_RENDERER_JPX_REDUCE")
.map(|v| v == "0" || v == "off" || v == "false")
.unwrap_or(false)
})
}
fn codec_target_size(ctm: Matrix) -> Option<(u32, u32)> {
if jpx_reduce_disabled() {
return None;
}
if !ctm.is_stably_invertible() {
return None;
}
let origin = ctm.apply(Point { x: 0.0, y: 0.0 });
let x_edge = ctm.apply(Point { x: 1.0, y: 0.0 });
let y_edge = ctm.apply(Point { x: 0.0, y: 1.0 });
let w = ((x_edge.x - origin.x).abs() + (x_edge.y - origin.y).abs()).ceil();
let h = ((y_edge.x - origin.x).abs() + (y_edge.y - origin.y).abs()).ceil();
if !w.is_finite() || !h.is_finite() || w < 1.0 || h < 1.0 {
return None;
}
let headroom = jpx_headroom() as f64;
Some((
(w * headroom).ceil().min(u32::MAX as f64) as u32,
(h * headroom).ceil().min(u32::MAX as f64) as u32,
))
}
pub(crate) fn decode_floor_map(base: Matrix, reference: Matrix) -> Option<Matrix> {
if !base.is_stably_invertible() {
return None;
}
let map = Matrix {
e: 0.0,
f: 0.0,
..base.invert()?.then(reference)
};
map.is_finite().then_some(map)
}
fn decode_target_size(ctm: Matrix, floor: Option<Matrix>) -> Option<(u32, u32)> {
let own = codec_target_size(ctm)?;
let Some(floor) = floor else {
return Some(own);
};
match codec_target_size(ctm.then(floor)) {
Some((w, h)) => Some((own.0.max(w), own.1.max(h))),
None => Some(own),
}
}
fn jpx_headroom() -> f32 {
use std::sync::OnceLock;
static HEADROOM: OnceLock<f32> = OnceLock::new();
*HEADROOM.get_or_init(|| {
std::env::var("PDF_RENDERER_JPX_HEADROOM")
.ok()
.and_then(|v| v.trim().parse::<f32>().ok())
.filter(|h| h.is_finite() && *h >= 1.0)
.unwrap_or(1.0)
})
}
fn sanity_extent(crop: crate::page_ir::Rect, base: Matrix, size: DeviceSize) -> f32 {
let r = base.transform_rect(crop);
let page = [r.x0, r.y0, r.x1, r.y1]
.into_iter()
.filter(|v| v.is_finite())
.fold(0.0f64, |m, v| m.max(v.abs()));
let out = f64::from(size.width.max(size.height).max(1));
page.max(out).min(f64::from(f32::MAX)) as f32
}
fn device_bounds_sane(
points: &[[f32; 2]],
size: DeviceSize,
extent: f32,
) -> Option<(i32, i32, i32, i32)> {
const SANE_FACTOR: f32 = 64.0;
let limit = SANE_FACTOR * extent.max(size.width.max(size.height).max(1) as f32);
let (mut x0, mut y0, mut x1, mut y1) = (
f32::INFINITY,
f32::INFINITY,
f32::NEG_INFINITY,
f32::NEG_INFINITY,
);
for p in points {
if !p[0].is_finite() || !p[1].is_finite() || p[0].abs() > limit || p[1].abs() > limit {
return None;
}
x0 = x0.min(p[0]);
y0 = y0.min(p[1]);
x1 = x1.max(p[0]);
y1 = y1.max(p[1]);
}
Some((
x0.floor().clamp(0.0, size.width as f32) as i32,
y0.floor().clamp(0.0, size.height as f32) as i32,
x1.ceil().clamp(0.0, size.width as f32) as i32,
y1.ceil().clamp(0.0, size.height as f32) as i32,
))
}
fn device_bounds(points: &[[f32; 2]], size: DeviceSize) -> (i32, i32, i32, i32) {
let (mut x0, mut y0, mut x1, mut y1) = (
f32::INFINITY,
f32::INFINITY,
f32::NEG_INFINITY,
f32::NEG_INFINITY,
);
for p in points {
x0 = x0.min(p[0]);
y0 = y0.min(p[1]);
x1 = x1.max(p[0]);
y1 = y1.max(p[1]);
}
(
x0.floor().clamp(0.0, size.width as f32) as i32,
y0.floor().clamp(0.0, size.height as f32) as i32,
x1.ceil().clamp(0.0, size.width as f32) as i32,
y1.ceil().clamp(0.0, size.height as f32) as i32,
)
}
fn intersect(a: DeviceRect, b: DeviceRect) -> DeviceRect {
let x0 = a.x.max(b.x);
let y0 = a.y.max(b.y);
let x1 = (a.x + a.width as i32).min(b.x + b.width as i32);
let y1 = (a.y + a.height as i32).min(b.y + b.height as i32);
if x1 <= x0 || y1 <= y0 {
DeviceRect {
x: x0,
y: y0,
width: 0,
height: 0,
}
} else {
DeviceRect {
x: x0,
y: y0,
width: (x1 - x0) as u32,
height: (y1 - y0) as u32,
}
}
}
fn is_integer_rect(points: &[[f32; 2]], x0: f32, y0: f32, x1: f32, y1: f32) -> bool {
if points.len() != 4 {
return false;
}
let near_int = |v: f32| (v - v.round()).abs() < 1e-4;
for p in points {
if !near_int(p[0]) || !near_int(p[1]) {
return false;
}
let on_x = (p[0] - x0).abs() < 1e-4 || (p[0] - x1).abs() < 1e-4;
let on_y = (p[1] - y0).abs() < 1e-4 || (p[1] - y1).abs() < 1e-4;
if !on_x || !on_y {
return false;
}
}
true
}
fn is_axis_aligned_rect(points: &[[f32; 2]]) -> bool {
if points.len() != 4 {
return false;
}
let (mut x0, mut y0, mut x1, mut y1) = (
f32::INFINITY,
f32::INFINITY,
f32::NEG_INFINITY,
f32::NEG_INFINITY,
);
for p in points {
if !p[0].is_finite() || !p[1].is_finite() {
return false;
}
x0 = x0.min(p[0]);
y0 = y0.min(p[1]);
x1 = x1.max(p[0]);
y1 = y1.max(p[1]);
}
if (x1 - x0) < 1e-3 || (y1 - y0) < 1e-3 {
return false;
}
let near = |a: f32, b: f32| (a - b).abs() < 1e-3;
points
.iter()
.all(|p| (near(p[0], x0) || near(p[0], x1)) && (near(p[1], y0) || near(p[1], y1)))
}
fn flatten_into(
path: &PathData,
ctm: Matrix,
points: &mut Vec<[f32; 2]>,
subpaths: &mut Vec<(usize, usize)>,
) {
let mut pt = 0usize;
let mut start = points.len();
let mut last = Point::default();
let map = |p: Point| {
let d = ctm.apply(p);
[d.x as f32, d.y as f32]
};
for verb in path.verbs.iter() {
match verb {
PathVerb::MoveTo => {
if points.len() > start {
subpaths.push((start, points.len()));
}
start = points.len();
last = path.points[pt];
points.push(map(last));
pt += 1;
}
PathVerb::LineTo => {
last = path.points[pt];
points.push(map(last));
pt += 1;
}
PathVerb::CurveTo => {
let p0 = last;
let (c1, c2, p3) = (path.points[pt], path.points[pt + 1], path.points[pt + 2]);
pt += 3;
for i in 1..=CURVE_SEGMENTS {
let t = i as f64 / CURVE_SEGMENTS as f64;
points.push(map(cubic(p0, c1, c2, p3, t)));
}
last = p3;
}
PathVerb::Close => {}
}
}
if points.len() > start {
subpaths.push((start, points.len()));
}
}
#[inline]
fn cubic(p0: Point, c1: Point, c2: Point, p3: Point, t: f64) -> Point {
let u = 1.0 - t;
let (w0, w1, w2, w3) = (u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t);
Point {
x: w0 * p0.x + w1 * c1.x + w2 * c2.x + w3 * p3.x,
y: w0 * p0.y + w1 * c1.y + w2 * c2.y + w3 * p3.y,
}
}
#[inline]
fn to_u8(v: f32) -> u8 {
(v * 255.0 + 0.5).clamp(0.0, 255.0) as u8
}
fn color_to_bytes(c: &crate::page_ir::Color) -> [u8; 4] {
[to_u8(c.r), to_u8(c.g), to_u8(c.b), to_u8(c.a)]
}
fn srgb_to_linear(value: f32) -> f32 {
if value <= 0.04045 {
value / 12.92
} else {
((value + 0.055) / 1.055).powf(2.4)
}
}
fn linear_to_srgb(value: f32) -> f32 {
let value = value.clamp(0.0, 1.0);
if value <= 0.003_130_8 {
value * 12.92
} else {
1.055 * value.powf(1.0 / 2.4) - 0.055
}
}
fn rgb8_linear(rgb: [u8; 3]) -> [f32; 3] {
rgb.map(|component| srgb_to_linear(component as f32 / 255.0))
}
fn recolor(
color: crate::page_ir::Color,
policy: crate::render_api::RenderColorPolicy,
) -> crate::page_ir::Color {
use crate::render_api::RenderColorPolicy;
let source = [
srgb_to_linear(color.r),
srgb_to_linear(color.g),
srgb_to_linear(color.b),
];
let mapped = match policy {
RenderColorPolicy::Original => return color,
RenderColorPolicy::WarmPaper { paper_rgb } => {
let paper = rgb8_linear(paper_rgb);
[
source[0] * paper[0],
source[1] * paper[1],
source[2] * paper[2],
]
}
RenderColorPolicy::Night {
paper_rgb,
text_rgb,
} => {
let paper = rgb8_linear(paper_rgb);
let text = rgb8_linear(text_rgb);
let luma =
(source[0] * 0.2126 + source[1] * 0.7152 + source[2] * 0.0722).clamp(0.0, 1.0);
[
text[0] + (paper[0] - text[0]) * luma + (source[0] - luma) * 0.35,
text[1] + (paper[1] - text[1]) * luma + (source[1] - luma) * 0.35,
text[2] + (paper[2] - text[2]) * luma + (source[2] - luma) * 0.35,
]
}
};
crate::page_ir::Color {
r: linear_to_srgb(mapped[0]),
g: linear_to_srgb(mapped[1]),
b: linear_to_srgb(mapped[2]),
a: color.a,
}
}
fn recolored_bytes(
color: &crate::page_ir::Color,
policy: crate::render_api::RenderColorPolicy,
) -> [u8; 4] {
color_to_bytes(&recolor(*color, policy))
}
fn prepare_shading(
res: &ShadingResource,
to_device: Matrix,
out_size: DeviceSize,
honor_background: bool,
color_policy: crate::render_api::RenderColorPolicy,
) -> Option<PreparedShading> {
let device_bbox = res.bbox.and_then(|bb| bbox_to_device_aabb(bb, to_device));
match &res.kind {
ShadingKind::MeshTriangles {
triangles,
background,
} => {
let bg = background_bytes(background, honor_background, color_policy);
return prepare_mesh_layer(
triangles.iter().map(|t| {
[
device_vertex(&t[0], to_device, color_policy),
device_vertex(&t[1], to_device, color_policy),
device_vertex(&t[2], to_device, color_policy),
]
}),
bg,
out_size,
)
.map(|mut sh| {
sh.bbox = device_bbox;
sh
});
}
ShadingKind::MeshPatches {
patches,
background,
} => {
let bg = background_bytes(background, honor_background, color_policy);
let mut triangles: Vec<[DevVertex; 3]> = Vec::new();
for p in patches.iter() {
tessellate_patch(p, to_device, color_policy, &mut triangles);
}
return prepare_mesh_layer(triangles.into_iter(), bg, out_size).map(|mut sh| {
sh.bbox = device_bbox;
sh
});
}
_ => {}
}
if !to_device.is_stably_invertible() {
return None;
}
let inv = to_device.invert()?;
match &res.kind {
ShadingKind::FunctionGrid {
domain,
matrix,
grid_w,
grid_h,
colors,
background,
} => {
let full = matrix.then(to_device);
if !full.is_stably_invertible() {
return None;
}
let (gw, gh) = (*grid_w as usize, *grid_h as usize);
if gw == 0 || gh == 0 || colors.len() < gw * gh {
return None;
}
Some(PreparedShading {
kind: ShadingSpanKind::Grid {
domain: [
domain[0] as f64,
domain[1] as f64,
domain[2] as f64,
domain[3] as f64,
],
gw,
gh,
},
inv: full.invert()?,
ramp: colors
.iter()
.map(|color| recolored_bytes(color, color_policy))
.collect(),
extend: [false, false],
background: background_bytes(background, honor_background, color_policy),
bbox: device_bbox,
})
}
ShadingKind::Axial {
coords,
extend,
ramp,
background,
..
} => {
let d = [
(coords[2] - coords[0]) as f64,
(coords[3] - coords[1]) as f64,
];
let dd = (d[0] * d[0] + d[1] * d[1]).max(1e-12);
Some(PreparedShading {
kind: ShadingSpanKind::Axial {
p0: [coords[0] as f64, coords[1] as f64],
d,
dd,
},
inv,
ramp: ramp
.iter()
.map(|color| recolored_bytes(color, color_policy))
.collect(),
extend: *extend,
background: background_bytes(background, honor_background, color_policy),
bbox: device_bbox,
})
}
ShadingKind::Radial {
coords,
extend,
ramp,
background,
..
} => Some(PreparedShading {
kind: ShadingSpanKind::Radial {
c0: [coords[0] as f64, coords[1] as f64, coords[2] as f64],
c1: [coords[3] as f64, coords[4] as f64, coords[5] as f64],
},
inv,
ramp: ramp
.iter()
.map(|color| recolored_bytes(color, color_policy))
.collect(),
extend: *extend,
background: background_bytes(background, honor_background, color_policy),
bbox: device_bbox,
}),
ShadingKind::Unsupported { .. } => None,
ShadingKind::MeshTriangles { .. } | ShadingKind::MeshPatches { .. } => None,
}
}
fn background_bytes(
background: &Option<crate::page_ir::Color>,
honor_background: bool,
color_policy: crate::render_api::RenderColorPolicy,
) -> Option<[u8; 4]> {
if !honor_background {
return None;
}
background
.as_ref()
.map(|color| recolored_bytes(color, color_policy))
}
#[derive(Debug, Clone, Copy)]
struct DevVertex {
x: f64,
y: f64,
rgba: [f32; 4],
}
fn device_vertex(
v: &crate::page_ir::MeshVertex,
to_device: Matrix,
color_policy: crate::render_api::RenderColorPolicy,
) -> DevVertex {
let p = to_device.apply(Point {
x: v.x as f64,
y: v.y as f64,
});
let color = recolor(v.color, color_policy);
DevVertex {
x: p.x,
y: p.y,
rgba: [
color.r.clamp(0.0, 1.0),
color.g.clamp(0.0, 1.0),
color.b.clamp(0.0, 1.0),
color.a.clamp(0.0, 1.0),
],
}
}
fn prepare_mesh_layer(
triangles: impl Iterator<Item = [DevVertex; 3]>,
background: Option<[u8; 4]>,
out_size: DeviceSize,
) -> Option<PreparedShading> {
let tris: Vec<[DevVertex; 3]> = triangles.collect();
if tris.is_empty() && background.is_none() {
return None;
}
let (ow, oh) = (out_size.width as f64, out_size.height as f64);
let (mut x0, mut y0, mut x1, mut y1) = if background.is_some() {
(0.0f64, 0.0f64, ow, oh)
} else {
let (mut ax0, mut ay0, mut ax1, mut ay1) = (
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
);
for t in &tris {
for v in t {
ax0 = ax0.min(v.x);
ay0 = ay0.min(v.y);
ax1 = ax1.max(v.x);
ay1 = ay1.max(v.y);
}
}
(ax0, ay0, ax1, ay1)
};
x0 = x0.max(0.0).floor();
y0 = y0.max(0.0).floor();
x1 = x1.min(ow).ceil();
y1 = y1.min(oh).ceil();
if !(x1 > x0 && y1 > y0) {
return None;
}
let (lx0, ly0) = (x0 as i32, y0 as i32);
let (w, h) = ((x1 - x0) as usize, (y1 - y0) as usize);
let fill = background.unwrap_or([0, 0, 0, 0]);
let mut layer = vec![fill; w * h];
for t in &tris {
fill_gouraud_triangle(&mut layer, w, h, lx0, ly0, t);
}
Some(PreparedShading {
kind: ShadingSpanKind::Layer {
x0: lx0,
y0: ly0,
w,
h,
},
inv: Matrix::IDENTITY,
ramp: layer,
extend: [false, false],
background,
bbox: None,
})
}
fn bbox_to_device_aabb(bb: [f32; 4], to_device: Matrix) -> Option<[f32; 4]> {
let corners = [
(bb[0], bb[1]),
(bb[2], bb[1]),
(bb[2], bb[3]),
(bb[0], bb[3]),
];
let (mut x0, mut y0, mut x1, mut y1) = (
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
);
for (cx, cy) in corners {
let p = to_device.apply(Point {
x: cx as f64,
y: cy as f64,
});
if !p.x.is_finite() || !p.y.is_finite() {
return None;
}
x0 = x0.min(p.x);
y0 = y0.min(p.y);
x1 = x1.max(p.x);
y1 = y1.max(p.y);
}
Some([x0 as f32, y0 as f32, x1 as f32, y1 as f32])
}
fn fill_gouraud_triangle(
layer: &mut [[u8; 4]],
w: usize,
h: usize,
lx0: i32,
ly0: i32,
t: &[DevVertex; 3],
) {
let (ax, ay) = (t[0].x, t[0].y);
let (bx, by) = (t[1].x, t[1].y);
let (cx, cy) = (t[2].x, t[2].y);
let area = (bx - ax) * (cy - ay) - (cx - ax) * (by - ay);
if area.abs() < 1e-12 {
return;
}
let inv_area = 1.0 / area;
let px0 = (ax.min(bx).min(cx).floor() as i64 - lx0 as i64).max(0) as usize;
let py0 = (ay.min(by).min(cy).floor() as i64 - ly0 as i64).max(0) as usize;
let px1 = ((ax.max(bx).max(cx).ceil() as i64 - lx0 as i64).max(0) as usize).min(w);
let py1 = ((ay.max(by).max(cy).ceil() as i64 - ly0 as i64).max(0) as usize).min(h);
for py in py0..py1 {
let yc = (ly0 + py as i32) as f64 + 0.5;
for px in px0..px1 {
let xc = (lx0 + px as i32) as f64 + 0.5;
let wa = ((bx - xc) * (cy - yc) - (cx - xc) * (by - yc)) * inv_area;
let wb = ((cx - xc) * (ay - yc) - (ax - xc) * (cy - yc)) * inv_area;
let wc = 1.0 - wa - wb;
if wa < 0.0 || wb < 0.0 || wc < 0.0 {
continue;
}
let mut rgba = [0u8; 4];
for ch in 0..4 {
let v = wa * t[0].rgba[ch] as f64
+ wb * t[1].rgba[ch] as f64
+ wc * t[2].rgba[ch] as f64;
rgba[ch] = (v * 255.0 + 0.5).clamp(0.0, 255.0) as u8;
}
layer[py * w + px] = rgba;
}
}
}
fn tessellate_patch(
patch: &crate::page_ir::MeshPatch,
to_device: Matrix,
color_policy: crate::render_api::RenderColorPolicy,
out: &mut Vec<[DevVertex; 3]>,
) {
let mut p = [[0.0f64; 2]; 16];
let (mut dx0, mut dy0, mut dx1, mut dy1) = (
f64::INFINITY,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NEG_INFINITY,
);
for (i, cp) in patch.points.iter().enumerate() {
let q = to_device.apply(Point {
x: cp[0] as f64,
y: cp[1] as f64,
});
p[i] = [q.x, q.y];
dx0 = dx0.min(q.x);
dy0 = dy0.min(q.y);
dx1 = dx1.max(q.x);
dy1 = dy1.max(q.y);
}
let extent = (dx1 - dx0).max(dy1 - dy0).max(0.0);
let n = ((extent / 6.0).ceil() as usize).clamp(4, 32);
let bez = |k: f64, a: f64, b: f64, c: f64, d: f64| {
let mk = 1.0 - k;
mk * mk * mk * a + 3.0 * mk * mk * k * b + 3.0 * mk * k * k * c + k * k * k * d
};
let eval = |u: f64, v: f64| -> [f64; 2] {
let mut out_p = [0.0f64; 2];
for (axis, val) in out_p.iter_mut().enumerate() {
let mut row = [0.0f64; 4];
for (i, r) in row.iter_mut().enumerate() {
*r = bez(
v,
p[i * 4][axis],
p[i * 4 + 1][axis],
p[i * 4 + 2][axis],
p[i * 4 + 3][axis],
);
}
*val = bez(u, row[0], row[1], row[2], row[3]);
}
out_p
};
let corner = |c: &crate::page_ir::Color| -> [f32; 4] {
let c = recolor(*c, color_policy);
[
c.r.clamp(0.0, 1.0),
c.g.clamp(0.0, 1.0),
c.b.clamp(0.0, 1.0),
c.a.clamp(0.0, 1.0),
]
};
let c00 = corner(&patch.colors[0]); let c01 = corner(&patch.colors[1]); let c11 = corner(&patch.colors[2]); let c10 = corner(&patch.colors[3]); let color_at = |u: f64, v: f64| -> [f32; 4] {
let mut c = [0.0f32; 4];
for ch in 0..4 {
let e0 = (1.0 - v) * c00[ch] as f64 + v * c01[ch] as f64;
let e1 = (1.0 - v) * c10[ch] as f64 + v * c11[ch] as f64;
c[ch] = ((1.0 - u) * e0 + u * e1) as f32;
}
c
};
let mut grid: Vec<DevVertex> = Vec::with_capacity((n + 1) * (n + 1));
for iv in 0..=n {
let v = iv as f64 / n as f64;
for iu in 0..=n {
let u = iu as f64 / n as f64;
let q = eval(u, v);
grid.push(DevVertex {
x: q[0],
y: q[1],
rgba: color_at(u, v),
});
}
}
let idx = |iu: usize, iv: usize| iv * (n + 1) + iu;
for iv in 0..n {
for iu in 0..n {
let a = grid[idx(iu, iv)];
let b = grid[idx(iu + 1, iv)];
let c = grid[idx(iu + 1, iv + 1)];
let d = grid[idx(iu, iv + 1)];
out.push([a, b, c]);
out.push([a, c, d]);
}
}
}
fn lower_shading_op(
out: &mut CpuPreparedPage,
res: &ShadingResource,
ctm: Matrix,
clip: Option<u32>,
color_policy: crate::render_api::RenderColorPolicy,
) -> Option<DeviceRect> {
let shading = prepare_shading(res, ctm, out.size, false, color_policy)?;
let full = DeviceRect {
x: 0,
y: 0,
width: out.size.width,
height: out.size.height,
};
let (region, clip_has_mask) = match clip {
Some(cid) => {
let c = &out.clips[cid as usize];
(intersect(full, c.bounds), c.has_mask)
}
None => (full, false),
};
if region.width == 0 || region.height == 0 {
return None;
}
let start = out.points.len();
let x0 = region.x as f32;
let y0 = region.y as f32;
let x1 = (region.x + region.width as i32) as f32;
let y1 = (region.y + region.height as i32) as f32;
for p in [[x0, y0], [x1, y0], [x1, y1], [x0, y1]] {
out.points.push(p);
}
let range_start = out.subpaths.len() as u32;
out.subpaths.push((start, out.points.len()));
let range_end = out.subpaths.len() as u32;
out.ops.push(PreparedOp::Draw(PreparedCommand {
origin: crate::page_ir::PaintOrigin::default(),
class: DrawClass::SolidPath,
subpath_range: (range_start, range_end),
rule: FillRule::NonZero,
rgb: [0, 0, 0],
premul: [0, 0, 0, 255],
alpha: 255,
opaque: false,
bounds: region,
clip,
clip_has_mask,
blend: crate::page_ir::BlendMode::Normal,
shading: Some(Box::new(shading)),
stencil: None,
}));
Some(region)
}
#[cfg(test)]
mod font_cache_tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::page_ir::{FontResource, ResourceKey};
fn bare_cff() -> Arc<[u8]> {
let sfnt = crate::font::StandardFont::Helvetica.program_data();
let n = u16::from_be_bytes([sfnt[4], sfnt[5]]) as usize;
for i in 0..n {
let rec = 12 + i * 16;
if &sfnt[rec..rec + 4] == b"CFF " {
let off = u32::from_be_bytes(sfnt[rec + 8..rec + 12].try_into().unwrap()) as usize;
let len = u32::from_be_bytes(sfnt[rec + 12..rec + 16].try_into().unwrap()) as usize;
return Arc::from(&sfnt[off..off + len]);
}
}
panic!("bundled face has no CFF table");
}
fn resource(program: Arc<[u8]>) -> FontResource {
FontResource {
key: ResourceKey {
object_number: 1,
generation: 0,
variant: 0,
},
program,
face_index: 0,
synthetic_shear: 0.0,
synthetic_embolden_em: 0.0,
}
}
#[test]
fn retains_and_serves_across_workers() {
let cache = SharedFontProgramCache::default();
let res = resource(bare_cff());
let key = FontProgramKey::for_resource(&res);
let prog = FontProgram::parse(bare_cff()).expect("parse bare cff");
assert!(prog.benefits_from_parse_cache());
cache.insert(key, prog.clone(), prog.retained_bytes());
assert_eq!(cache.len(), 1);
let (h0, i0) = cache.stats();
let served = cache.get(&key).expect("served from cache");
let (h1, i1) = cache.stats();
assert_eq!(h1 - h0, 1, "get is a shared hit");
assert_eq!(i1, i0, "no extra insert");
assert_eq!(served.units_per_em(), prog.units_per_em());
}
#[test]
fn parse_cache_retention_policy_is_deterministic() {
let bare = FontProgram::parse(bare_cff()).expect("parse bare cff");
assert!(bare.benefits_from_parse_cache());
assert!(!should_retain_font_program(
&bare,
MIN_PARSE_TO_CACHE - std::time::Duration::from_micros(1)
));
assert!(should_retain_font_program(&bare, MIN_PARSE_TO_CACHE));
let sfnt = FontProgram::parse(crate::font::StandardFont::Helvetica.program_data())
.expect("parse bundled sfnt");
assert!(!sfnt.benefits_from_parse_cache());
assert!(!should_retain_font_program(
&sfnt,
std::time::Duration::from_secs(1)
));
let t1 = FontProgram::parse(Arc::from(crate::test_support::fonts::minimal_type1()))
.expect("parse type 1");
assert!(t1.is_type1());
assert!(should_retain_font_program(&t1, std::time::Duration::ZERO));
}
#[test]
fn device_bounds_sane_rejects_corrupt_geometry() {
let size = DeviceSize {
width: 100,
height: 80,
};
assert_eq!(
device_bounds_sane(&[[10.0, 10.0], [50.0, 40.0]], size, 100.0),
Some((10, 10, 50, 40))
);
assert!(device_bounds_sane(&[[-20.0, -20.0], [30.0, 30.0]], size, 100.0).is_some());
assert_eq!(
device_bounds_sane(&[[0.0, 0.0], [1.0e9, 5.0]], size, 100.0),
None
);
assert_eq!(
device_bounds_sane(&[[0.0, 0.0], [f32::NAN, 5.0]], size, 100.0),
None
);
assert_eq!(
device_bounds_sane(&[[f32::INFINITY, 0.0]], size, 100.0),
None
);
let window = DeviceSize {
width: 8,
height: 8,
};
let corner = [[-2400.0, -3100.0], [48.0, 68.0]];
assert!(device_bounds_sane(&corner, window, 3168.0).is_some());
assert_eq!(device_bounds_sane(&corner, window, 8.0), None);
assert_eq!(
device_bounds_sane(&[[0.0, 0.0], [1.0e9, 5.0]], window, 3168.0),
None
);
let crop = crate::page_ir::Rect {
x0: 0.0,
y0: 0.0,
x1: 612.0,
y1: 792.0,
};
let full = DeviceSize {
width: 2448,
height: 3168,
};
assert_eq!(sanity_extent(crop, Matrix::scale(4.0, 4.0), full), 3168.0);
let shifted = Matrix::scale(4.0, 4.0).then(Matrix::translate(-2400.0, -3100.0));
assert_eq!(sanity_extent(crop, shifted, window), 3100.0);
}
#[test]
fn axis_aligned_rect_accepts_fractional_edges_rejects_rotated() {
let frac = [
[12.24, 12.06],
[599.76, 12.06],
[599.76, 780.5],
[12.24, 780.5],
];
assert!(
is_axis_aligned_rect(&frac),
"fractional rect must be a rect clip"
);
assert!(
!is_integer_rect(&frac, 12.24, 12.06, 599.76, 780.5),
"sanity: not integer"
);
let rot = [[10.0, 0.0], [20.0, 10.0], [10.0, 20.0], [0.0, 10.0]];
assert!(
!is_axis_aligned_rect(&rot),
"rotated quad is not axis-aligned"
);
let line = [[0.0, 5.0], [100.0, 5.0], [100.0, 5.0], [0.0, 5.0]];
assert!(
!is_axis_aligned_rect(&line),
"zero-area shape is not a rect"
);
assert!(!is_axis_aligned_rect(&[[0.0, 0.0], [1.0, 1.0]]));
}
#[test]
fn identity_is_content_not_pointer() {
let bytes = bare_cff();
let r1 = resource(bytes.clone());
let independent: Arc<[u8]> = Arc::from(&bytes[..]);
assert_ne!(
bytes.as_ptr(),
independent.as_ptr(),
"genuinely distinct allocations"
);
assert_eq!(
FontProgramKey::for_resource(&r1),
FontProgramKey::for_resource(&resource(independent))
);
let mut other = bytes.to_vec();
other[10] ^= 0xff;
assert_ne!(
FontProgramKey::for_resource(&r1),
FontProgramKey::for_resource(&resource(Arc::from(other)))
);
}
#[test]
fn serves_across_independent_allocations() {
let cache = SharedFontProgramCache::default();
let first = resource(bare_cff());
let second = resource(Arc::from(&bare_cff()[..]));
assert_ne!(first.program.as_ptr(), second.program.as_ptr());
let key1 = FontProgramKey::for_resource(&first);
let key2 = FontProgramKey::for_resource(&second);
assert_eq!(key1, key2, "content identity, not pointer");
let prog = FontProgram::parse(bare_cff()).expect("parse");
cache.insert(key1, prog.clone(), prog.retained_bytes());
let (h0, _) = cache.stats();
assert!(cache.get(&key2).is_some(), "distinct allocation is a hit");
assert_eq!(cache.stats().0 - h0, 1);
assert_eq!(cache.len(), 1);
}
#[test]
fn evicts_by_byte_budget() {
let cache = SharedFontProgramCache::new(1);
let program = FontProgram::parse(bare_cff()).expect("parse");
for i in 0..8u64 {
let key = FontProgramKey {
h0: 0x1000 + i * 0x40,
h1: i,
len: 4096,
face: 0,
};
cache.insert(key, program.clone(), 4096);
}
assert!(cache.len() <= SharedFontProgramCache::SHARDS);
}
#[test]
fn evicts_the_least_recently_used_entry_first() {
let cache = SharedFontProgramCache::new(8 * 2 * 4096);
let program = FontProgram::parse(bare_cff()).expect("parse");
let key = |i: u64| FontProgramKey {
h0: (7u64 << 32) | i,
h1: i,
len: 4096,
face: 0,
};
cache.insert(key(1), program.clone(), 4096);
cache.insert(key(2), program.clone(), 4096);
assert!(cache.get(&key(1)).is_some());
cache.insert(key(3), program.clone(), 4096);
assert!(
cache.get(&key(2)).is_none(),
"the least recently used entry goes"
);
assert!(cache.get(&key(1)).is_some(), "the touched entry stays");
assert!(cache.get(&key(3)).is_some(), "the new entry stays");
assert_eq!(cache.len(), 2);
}
#[test]
fn none_shared_cache_still_parses() {
let res = resource(bare_cff());
let p = resolve_program_bytes(&res, None).expect("parse without cache");
assert!(p.benefits_from_parse_cache());
}
}
#[cfg(test)]
mod glyph_cache_tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use crate::page_ir::{Color, FontId, FontResource, PlacedGlyph, ResourceKey};
fn helvetica() -> Arc<[u8]> {
Arc::from(crate::font::StandardFont::Helvetica.program_data())
}
fn font_key() -> FontProgramKey {
FontProgramKey::for_resource(&FontResource {
key: ResourceKey {
object_number: 1,
generation: 0,
variant: 0,
},
program: helvetica(),
face_index: 0,
synthetic_shear: 0.0,
synthetic_embolden_em: 0.0,
})
}
fn base_key(glyph: u32) -> GlyphCacheKey {
GlyphCacheKey {
font: font_key(),
glyph,
la_bits: 0.01f64.to_bits(),
ld_bits: (-0.01f64).to_bits(),
ppem_bits: 0,
sx: 0,
sy: 0,
hinted: false,
}
}
fn nonempty_bitmap() -> Arc<GlyphBitmap> {
Arc::new(GlyphBitmap {
left: 0,
top: -8,
width: 6,
height: 8,
cov: vec![200u8; 6 * 8].into_boxed_slice(),
})
}
#[test]
fn hit_miss_and_stats() {
let cache = SharedGlyphCache::default();
let key = base_key(3);
assert!(cache.get(&key).is_none(), "cold miss");
cache.insert(key, nonempty_bitmap());
assert_eq!(cache.len(), 1);
let (h0, m0, i0) = cache.stats();
let served = cache.get(&key).expect("served after insert");
assert_eq!(served.width, 6);
let (h1, m1, i1) = cache.stats();
assert_eq!(h1 - h0, 1, "one hit");
assert_eq!(m1, m0, "no new miss");
assert_eq!(i1, i0, "no new insert");
}
#[test]
fn key_distinct_for_hinting_and_transform() {
let cache = SharedGlyphCache::default();
let unhinted = base_key(5);
cache.insert(unhinted, nonempty_bitmap());
let hinted = GlyphCacheKey {
hinted: true,
..unhinted
};
assert!(cache.get(&hinted).is_none(), "hinting state is part of key");
let scaled = GlyphCacheKey {
ld_bits: (-0.02f64).to_bits(),
..unhinted
};
assert!(cache.get(&scaled).is_none(), "transform is part of key");
let phased = GlyphCacheKey { sx: 2, ..unhinted };
assert!(
cache.get(&phased).is_none(),
"sub-pixel phase is part of key"
);
let other = GlyphCacheKey {
glyph: 6,
..unhinted
};
assert!(cache.get(&other).is_none(), "glyph id is part of key");
assert!(cache.get(&unhinted).is_some(), "original entry retained");
}
#[test]
fn evicts_by_byte_budget() {
let cache = SharedGlyphCache::new(1);
for i in 0..64u32 {
let key = GlyphCacheKey {
glyph: i,
..base_key(0)
};
cache.insert(key, nonempty_bitmap());
}
assert!(
cache.len() <= SharedGlyphCache::SHARDS,
"bounded to one entry per shard, got {}",
cache.len()
);
assert!(cache.retained_bytes() <= SharedGlyphCache::SHARDS * nonempty_bitmap().charge());
}
fn empty_page(w: u32, h: u32) -> CpuPreparedPage {
CpuPreparedPage {
size: DeviceSize {
width: w,
height: h,
},
ops: Vec::new(),
clips: Vec::new(),
points: Vec::new(),
subpaths: Vec::new(),
codecs: crate::image::CodecRegistry::default(),
decode_limits: crate::image::DecodeLimits::default(),
hinting: crate::font::HintingPolicy::None,
color_policy: crate::render_api::RenderColorPolicy::Original,
diagnostics: RenderDiagnostics::default(),
image_cache: None,
decode_floor: None,
sanity_extent: w.max(h) as f32,
rows: (0, u32::MAX),
op_extent: None,
strip_decodes: None,
#[cfg(feature = "profiling")]
profile: std::cell::RefCell::new(crate::profiling::ProfileReport::new()),
#[cfg(feature = "profiling")]
decode_cache: None,
#[cfg(feature = "profiling")]
lower_prof: Default::default(),
}
}
fn run_at(font_size: f64, transform: Matrix, gid: u32) -> GlyphRun {
GlyphRun {
font: FontId(0),
font_size,
transform,
glyphs: Arc::from([PlacedGlyph {
glyph: gid,
x: 0.0,
y: 0.0,
}]),
render_mode: 0,
}
}
#[test]
fn eligible_run_populates_then_hits() {
let prog = FontProgram::parse(helvetica()).expect("parse helvetica");
let gid = prog.gid_for_char('A').expect("gid for A");
let cache = SharedGlyphCache::default();
let mut raster = crate::render_cpu::raster::RasterKernel::default();
let color = Color::from_rgb(0.0, 0.0, 0.0);
let run = run_at(40.0, Matrix::translate(20.0, 60.0), gid);
let mut page = empty_page(200, 200);
let handled = try_cached_glyph_run(
&mut page,
&run,
&prog,
Matrix::IDENTITY,
color,
1.0,
None,
crate::page_ir::BlendMode::Normal,
&cache,
font_key(),
&mut raster,
);
assert!(handled.is_some(), "eligible run is handled, not fallback");
assert!(handled.unwrap().is_some(), "produced device bounds");
assert_eq!(page.ops.len(), 1, "emitted one glyph-run op");
assert!(matches!(page.ops[0], PreparedOp::GlyphRun(_)));
let (h0, _, i0) = cache.stats();
assert_eq!(i0, 1, "one glyph inserted on the miss");
let mut page2 = empty_page(200, 200);
try_cached_glyph_run(
&mut page2,
&run,
&prog,
Matrix::IDENTITY,
color,
1.0,
None,
crate::page_ir::BlendMode::Normal,
&cache,
font_key(),
&mut raster,
);
let (h1, _, i1) = cache.stats();
assert_eq!(i1, i0, "no new insert on repeat");
assert_eq!(h1 - h0, 1, "second occurrence is a hit");
}
#[test]
fn rotated_and_oversized_runs_are_ineligible() {
let prog = FontProgram::parse(helvetica()).expect("parse helvetica");
let gid = prog.gid_for_char('A').expect("gid");
let cache = SharedGlyphCache::default();
let mut raster = crate::render_cpu::raster::RasterKernel::default();
let color = Color::from_rgb(0.0, 0.0, 0.0);
let skew = Matrix {
a: 1.0,
b: 0.4,
c: -0.4,
d: 1.0,
e: 0.0,
f: 0.0,
};
let mut page = empty_page(400, 400);
let r = try_cached_glyph_run(
&mut page,
&run_at(40.0, skew, gid),
&prog,
Matrix::IDENTITY,
color,
1.0,
None,
crate::page_ir::BlendMode::Normal,
&cache,
font_key(),
&mut raster,
);
assert!(r.is_none(), "rotated run is ineligible");
assert!(page.ops.is_empty(), "no op emitted for a fallback run");
let big = try_cached_glyph_run(
&mut page,
&run_at(400.0, Matrix::translate(10.0, 10.0), gid),
&prog,
Matrix::IDENTITY,
color,
1.0,
None,
crate::page_ir::BlendMode::Normal,
&cache,
font_key(),
&mut raster,
);
assert!(big.is_none(), "oversized run is ineligible");
assert_eq!(cache.stats().2, 0, "nothing inserted by ineligible runs");
}
#[test]
fn rasterizes_real_outline_to_tight_bitmap() {
let prog = FontProgram::parse(helvetica()).expect("parse");
let gid = prog.gid_for_char('H').expect("gid for H");
let outline = prog.outline(gid).expect("H has an outline");
let upem = prog.units_per_em() as f64;
let s = 100.0 / upem;
let mut raster = crate::render_cpu::raster::RasterKernel::default();
let bmp = rasterize_glyph_bitmap(
&outline,
|p| [(s * p[0] as f64) as f32, (-s * p[1] as f64) as f32],
&mut raster,
);
assert!(bmp.width > 0 && bmp.height > 0, "H has a non-empty bitmap");
assert!(
(bmp.cov.len()) == (bmp.width * bmp.height) as usize,
"coverage sized to bbox"
);
assert!(bmp.cov.iter().any(|&c| c > 0), "some coverage painted");
assert!(
bmp.height >= 40 && bmp.height <= 120,
"plausible H height: {}",
bmp.height
);
assert!(bmp.top < 0, "cap sits above the baseline: top={}", bmp.top);
}
#[test]
fn empty_outline_yields_empty_bitmap() {
let mut raster = crate::render_cpu::raster::RasterKernel::default();
let outline = crate::font::Outline::default();
let bmp = rasterize_glyph_bitmap(&outline, |p| p, &mut raster);
assert_eq!(bmp.width, 0);
assert!(
place_glyph(bmp, (10, 10)).is_none(),
"empty glyph places nothing"
);
}
}
#[cfg(test)]
mod image_cache_tests {
#![allow(clippy::unwrap_used, clippy::expect_used)]
use super::*;
use crate::page_ir::{
Color, ImageColorSpace, ImageIr, InterpolationMode, PageBounds, PageComplexity,
PageFeatures, Rect, ResourceKey,
};
use std::sync::Barrier;
use std::sync::atomic::{AtomicUsize, Ordering};
fn jpeg_payload(seed: u8) -> Vec<u8> {
jpeg_payload_sized(16, seed)
}
fn jpeg_payload_sized(size: u16, seed: u8) -> Vec<u8> {
let px: Vec<u8> = (0..size as usize * size as usize)
.map(|i| (i as u8).wrapping_mul(31).wrapping_add(seed))
.collect();
crate::image::jpeg::encoder::write_jpeg(&px, size, size, false, 90, false).expect("encode")
}
fn dct_page(payload: Vec<u8>) -> CompiledPage {
dct_page_sized(payload, 16)
}
fn dct_page_sized(payload: Vec<u8>, size: u32) -> CompiledPage {
let extent = f64::from(size);
let image = ImageIr {
key: ResourceKey {
object_number: 7,
generation: 0,
variant: 0,
},
width: size,
height: size,
is_stencil: false,
interpolation: InterpolationMode::Nearest,
soft_mask: None,
bits_per_component: 8,
color_space: ImageColorSpace::Gray,
decode: None,
samples: None,
codec: Some(crate::page_ir::ImageCodecKind::Dct),
codec_data: Some(payload.into()),
codec_parms: None,
smask: None,
mask: None,
smask_in_data: 0,
lowering_degraded: false,
};
CompiledPage {
schema_version: crate::page_ir::IR_SCHEMA_VERSION,
bounds: PageBounds {
crop: Rect {
x0: 0.0,
y0: 0.0,
x1: extent,
y1: extent,
},
rotate: 0,
},
content_bounds: None,
operations: Arc::from([
DisplayOp::ConcatTransform(Matrix::scale(extent, extent)),
DisplayOp::DrawImage {
image: crate::page_ir::ImageId(0),
paint: crate::page_ir::PaintId(0),
transform: Matrix::IDENTITY,
alpha: 1.0,
blend: crate::page_ir::BlendMode::Normal,
},
]),
paths: Arc::from([]),
paints: Arc::from([Paint::Solid(Color::BLACK)]),
stroke_styles: Arc::from([]),
glyph_runs: Arc::from([]),
fonts: Arc::from([]),
images: Arc::from([image]),
masks: Arc::from([]),
groups: Arc::from([]),
shadings: Arc::from([]),
tilings: Arc::from([]),
features: PageFeatures::IMAGES,
complexity: PageComplexity::default(),
}
}
fn registry() -> crate::image::CodecRegistry {
crate::image::CodecRegistry::new([
Arc::new(crate::image::JpegCodec) as Arc<dyn crate::image::ImageCodec>,
Arc::new(crate::image::JpxCodec),
])
}
fn cache_key_for_shard(shard: usize) -> ImageCacheKey {
ImageCacheKey {
h0: (shard as u64) << 32,
h1: shard as u64,
len: 1,
codec: 0,
width: 1,
height: 1,
bpc: 8,
is_mask: false,
space: None,
scale: DecodeScaleKey::Level(0),
parms: 0,
}
}
fn cached_samples(sample_bytes: usize, alpha_bytes: usize) -> CodecSamples {
CodecSamples {
samples: Arc::from(vec![7; sample_bytes]),
width: sample_bytes as u32,
height: 1,
bpc: 8,
color_space: ImageColorSpace::Gray,
format: crate::image::DecodedFormat::Gray8,
alpha: (alpha_bytes != 0).then(|| Arc::from(vec![11; alpha_bytes])),
}
}
fn lower_page(page: &CompiledPage, cache: Option<&Arc<SharedImageCache>>) -> CpuPreparedPage {
lower_page_at(page, 1.0, 16, cache)
}
fn lower_page_at(
page: &CompiledPage,
scale: f64,
device: u32,
cache: Option<&Arc<SharedImageCache>>,
) -> CpuPreparedPage {
lower_with_codecs(page, scale, device, ®istry(), cache)
}
fn lower_with_codecs(
page: &CompiledPage,
scale: f64,
device: u32,
codecs: &crate::image::CodecRegistry,
cache: Option<&Arc<SharedImageCache>>,
) -> CpuPreparedPage {
lower_with_floor(page, scale, device, codecs, None, cache)
}
fn lower_with_floor(
page: &CompiledPage,
scale: f64,
device: u32,
codecs: &crate::image::CodecRegistry,
reference: Option<f64>,
cache: Option<&Arc<SharedImageCache>>,
) -> CpuPreparedPage {
let base = Matrix::scale(scale, scale);
lower_impl(
page,
base,
DeviceSize {
width: device,
height: device,
},
codecs,
&crate::image::DecodeLimits::default(),
crate::font::HintingPolicy::None,
crate::render_api::RenderColorPolicy::Original,
None,
None,
None,
cache,
reference.and_then(|r| decode_floor_map(base, Matrix::scale(r, r))),
false,
None,
#[cfg(feature = "profiling")]
None,
#[cfg(feature = "profiling")]
true,
)
}
fn render_pixels(prepared: &CpuPreparedPage) -> Vec<u8> {
let mut surface = crate::render_cpu::surface::Surface::new(
prepared.size.width as usize,
prepared.size.height as usize,
crate::render_api::Background::White,
);
let mut ctx = crate::render_cpu::exec::CpuWorkerContext::new();
let mut stats = crate::render_cpu::stats::RenderStats::default();
crate::render_cpu::exec::execute(prepared, &mut surface, &mut ctx, &mut stats);
let (_stride, pixels) =
surface.into_output(crate::render_api::OutputFormat::Rgba8PremultipliedSrgb);
pixels.to_vec()
}
fn prepared_samples(prepared: &CpuPreparedPage) -> Arc<[u8]> {
prepared
.ops
.iter()
.find_map(|op| match op {
PreparedOp::Image(img) => Some(img.samples.clone()),
_ => None,
})
.expect("an image op was lowered")
}
#[test]
fn cache_on_off_renders_byte_identical() {
let page = dct_page(jpeg_payload(3));
let cache = Arc::new(SharedImageCache::default());
let uncached = lower_page(&page, None);
let cold = lower_page(&page, Some(&cache));
let warm = lower_page(&page, Some(&cache));
assert_eq!(cache.stats(), (1, 1, 1), "miss+insert then hit");
assert_eq!(
prepared_samples(&uncached),
prepared_samples(&cold),
"cold cache decode matches uncached decode"
);
assert_eq!(
prepared_samples(&cold),
prepared_samples(&warm),
"warm hit serves the identical payload"
);
let base = render_pixels(&uncached);
assert_eq!(base, render_pixels(&cold), "cache-off vs cache-cold pixels");
assert_eq!(base, render_pixels(&warm), "cache-off vs cache-warm pixels");
}
fn decoded_size(prepared: &CpuPreparedPage) -> (u32, u32) {
let image = prepared_image(prepared);
(image.width, image.height)
}
#[test]
fn reduced_dct_decode_never_serves_a_larger_draw() {
let page = dct_page_sized(jpeg_payload_sized(64, 5), 64);
let shared = Arc::new(SharedImageCache::default());
let thumbnail = lower_page_at(&page, 0.25, 16, Some(&shared));
assert_eq!(decoded_size(&thumbnail), (16, 16), "reduced decode");
let after_thumbnail = lower_page_at(&page, 1.0, 64, Some(&shared));
let fresh = lower_page_at(&page, 1.0, 64, Some(&Arc::new(SharedImageCache::default())));
let uncached = lower_page_at(&page, 1.0, 64, None);
assert_eq!(decoded_size(&fresh), (64, 64), "full-size decode");
assert_eq!(prepared_samples(&fresh), prepared_samples(&uncached));
assert_eq!(
decoded_size(&after_thumbnail),
(64, 64),
"the thumbnail's reduced decode served the full-size draw"
);
assert_eq!(prepared_samples(&after_thumbnail), prepared_samples(&fresh));
assert_eq!(
render_pixels(&after_thumbnail),
render_pixels(&fresh),
"full-size pixels depend on what was rendered before"
);
}
#[test]
fn dct_draws_share_one_entry_per_decode_scale() {
let page = dct_page_sized(jpeg_payload_sized(64, 9), 64);
let cache = Arc::new(SharedImageCache::default());
let a = lower_page_at(&page, 20.0 / 64.0, 20, Some(&cache));
let b = lower_page_at(&page, 30.0 / 64.0, 30, Some(&cache));
assert_eq!(cache.stats(), (1, 1, 1), "miss+insert then hit");
assert_eq!(decoded_size(&a), (32, 32));
assert!(Arc::ptr_eq(&prepared_samples(&a), &prepared_samples(&b)));
let c = lower_page_at(&page, 48.0 / 64.0, 48, Some(&cache));
let d = lower_page_at(&page, 1.0, 64, Some(&cache));
assert_eq!(cache.stats(), (2, 2, 2), "a new scale is a new entry");
assert_eq!(decoded_size(&d), (64, 64));
assert!(Arc::ptr_eq(&prepared_samples(&c), &prepared_samples(&d)));
assert_eq!(cache.len(), 2);
}
#[test]
fn jpx_draws_are_keyed_by_the_decoded_wavelet_level() {
let size = 64u32;
let src: Vec<u8> = (0..size * size).map(|i| (i * 31 % 251) as u8).collect();
let image = jp2lam::Image::from_gray_bytes(size, size, &src).expect("gray image");
let options = jp2lam::EncodeOptions {
quality: 100,
..Default::default()
};
let mut page = dct_page_sized(jp2lam::encode(&image, &options).expect("encode"), size);
let mut jpx = page.images[0].clone();
jpx.codec = Some(crate::page_ir::ImageCodecKind::Jpx);
page.images = Arc::from([jpx]);
let shared = Arc::new(SharedImageCache::default());
let thumbnail = lower_page_at(&page, 0.25, 16, Some(&shared));
assert_eq!(decoded_size(&thumbnail), (16, 16), "two levels dropped");
let full = lower_page_at(&page, 1.0, 64, Some(&shared));
let fresh = lower_page_at(&page, 1.0, 64, Some(&Arc::new(SharedImageCache::default())));
assert_eq!(decoded_size(&fresh), (64, 64));
assert_eq!(prepared_samples(&full), prepared_samples(&fresh));
assert_eq!(render_pixels(&full), render_pixels(&fresh));
assert_eq!(shared.stats(), (0, 2, 2));
let a = lower_page_at(&page, 20.0 / 64.0, 20, Some(&shared));
let b = lower_page_at(&page, 30.0 / 64.0, 30, Some(&shared));
assert_eq!(decoded_size(&a), (32, 32));
assert!(Arc::ptr_eq(&prepared_samples(&a), &prepared_samples(&b)));
assert_eq!(shared.stats(), (1, 3, 3));
}
fn flat_decode(
decodes: &AtomicUsize,
descriptor: &crate::image::ImageDescriptor,
) -> Result<crate::image::DecodedImage, crate::image::ImageError> {
decodes.fetch_add(1, Ordering::Relaxed);
let (width, height) = (descriptor.width, descriptor.height);
Ok(crate::image::DecodedImage {
width,
height,
format: crate::image::DecodedFormat::Gray8,
stride: width as usize,
data: Arc::from(vec![128u8; width as usize * height as usize]),
})
}
#[test]
fn a_draw_crossing_strips_is_decoded_once_and_released_after_its_last_row() {
let page = dct_page_sized(jpeg_payload_sized(64, 3), 64);
for hold in [true, false] {
let codec = Arc::new(FixedScaleCodec::default());
let codecs = crate::image::CodecRegistry::new([
Arc::clone(&codec) as Arc<dyn crate::image::ImageCodec>
]);
let decodes = Arc::new(StripDecodes::default());
let mut extents = OpExtents::default();
for (first, end) in [(0u32, 24u32), (24, 48), (48, 72), (72, 96)] {
let mut flush = |_: &CpuPreparedPage, _: &[u32]| true;
let mut sink = LowerSink {
chunk_bytes: usize::MAX,
image_chunk_bytes: usize::MAX,
rows: (first, end),
extents: Some(&mut extents),
decodes: hold.then(|| Arc::clone(&decodes)),
flush: &mut flush,
};
let prepared = lower_impl(
&page,
Matrix {
a: 1.0,
b: 0.0,
c: 0.0,
d: 1.0,
e: 0.0,
f: 0.0,
},
DeviceSize {
width: 64,
height: 96,
},
&codecs,
&crate::image::DecodeLimits::default(),
crate::font::HintingPolicy::None,
crate::render_api::RenderColorPolicy::Original,
None,
None,
None,
None,
None,
false,
Some(&mut sink),
#[cfg(feature = "profiling")]
None,
#[cfg(feature = "profiling")]
true,
);
let drawn = prepared
.ops
.iter()
.any(|op| matches!(op, PreparedOp::Image(_)));
assert_eq!(drawn, first < 64, "strip {first}..{end}");
decodes.release_through(end);
assert_eq!(
decodes.len(),
usize::from(hold && end < 64),
"strip {first}..{end}"
);
}
assert_eq!(
codec.decodes.load(Ordering::Relaxed),
if hold { 1 } else { 3 },
"hold={hold}"
);
}
}
#[derive(Debug, Default)]
struct FixedScaleCodec {
decodes: AtomicUsize,
}
impl crate::image::ImageCodec for FixedScaleCodec {
fn filter(&self) -> crate::image::StreamFilter {
crate::image::StreamFilter::DctDecode
}
fn decode(
&self,
_data: &[u8],
descriptor: &crate::image::ImageDescriptor,
_params: &crate::image::DecodeParameters,
_limits: &crate::image::DecodeLimits,
) -> Result<crate::image::DecodedImage, crate::image::ImageError> {
flat_decode(&self.decodes, descriptor)
}
fn reduction_level(
&self,
_data: &[u8],
_descriptor: &crate::image::ImageDescriptor,
_params: &crate::image::DecodeParameters,
_limits: &crate::image::DecodeLimits,
) -> Option<u8> {
Some(0)
}
}
#[derive(Debug, Default)]
struct UnknownScaleCodec {
decodes: AtomicUsize,
}
impl crate::image::ImageCodec for UnknownScaleCodec {
fn filter(&self) -> crate::image::StreamFilter {
crate::image::StreamFilter::DctDecode
}
fn decode(
&self,
_data: &[u8],
descriptor: &crate::image::ImageDescriptor,
_params: &crate::image::DecodeParameters,
_limits: &crate::image::DecodeLimits,
) -> Result<crate::image::DecodedImage, crate::image::ImageError> {
flat_decode(&self.decodes, descriptor)
}
}
#[test]
fn the_reported_level_decides_sharing_across_draw_sizes() {
let page = dct_page_sized(jpeg_payload_sized(64, 1), 64);
let draw = |codecs: &crate::image::CodecRegistry, cache: &Arc<SharedImageCache>| {
for device in [16u32, 32, 64, 16] {
lower_with_codecs(&page, f64::from(device) / 64.0, device, codecs, Some(cache));
}
};
let fixed = Arc::new(FixedScaleCodec::default());
let cache = Arc::new(SharedImageCache::default());
draw(
&crate::image::CodecRegistry::new([fixed.clone() as Arc<dyn crate::image::ImageCodec>]),
&cache,
);
assert_eq!(fixed.decodes.load(Ordering::Relaxed), 1);
assert_eq!(cache.stats(), (3, 1, 1));
let unknown = Arc::new(UnknownScaleCodec::default());
let cache = Arc::new(SharedImageCache::default());
draw(
&crate::image::CodecRegistry::new([
unknown.clone() as Arc<dyn crate::image::ImageCodec>
]),
&cache,
);
assert_eq!(unknown.decodes.load(Ordering::Relaxed), 3);
assert_eq!(cache.stats(), (1, 3, 3), "only the repeated size hits");
}
#[test]
fn codec_target_size_reads_image_axes() {
assert_eq!(
codec_target_size(Matrix::scale(100.0, 50.0)),
Some((100, 50))
);
assert_eq!(
codec_target_size(Matrix::scale(100.0, -50.0)),
Some((100, 50))
);
let moved = Matrix::scale(100.0, 50.0).then(Matrix::translate(37.25, -12.5));
assert_eq!(codec_target_size(moved), Some((100, 50)));
let quarter = Matrix {
a: 0.0,
b: 50.0,
c: -100.0,
d: 0.0,
e: 300.0,
f: 0.0,
};
assert_eq!(codec_target_size(quarter), Some((50, 100)));
let three_quarter = Matrix {
a: 0.0,
b: -50.0,
c: 100.0,
d: 0.0,
e: 0.0,
f: 400.0,
};
assert_eq!(codec_target_size(three_quarter), Some((50, 100)));
let r = std::f64::consts::FRAC_1_SQRT_2 * 100.0;
let diag = Matrix {
a: r,
b: r,
c: -r,
d: r,
e: 0.0,
f: 0.0,
};
assert_eq!(codec_target_size(diag), Some((142, 142)));
let draw = Matrix::scale(16.0, 8.0);
let floor = decode_floor_map(
Matrix::IDENTITY,
Matrix {
a: 0.0,
b: 2.0,
c: -2.0,
d: 0.0,
e: 0.0,
f: 0.0,
},
);
assert_eq!(decode_target_size(draw, floor), Some((32, 16)));
let turned = Matrix {
a: 0.0,
b: 16.0,
c: -8.0,
d: 0.0,
e: 0.0,
f: 0.0,
};
assert_eq!(decode_target_size(turned, None), Some((16, 8)));
}
#[test]
fn decode_floor_raises_the_hint_to_the_reference_footprint() {
let draw = Matrix::scale(16.0, 16.0);
assert_eq!(decode_target_size(draw, None), Some((16, 16)));
let to_double = decode_floor_map(
Matrix::scale(0.25, 0.25).then(Matrix::translate(5.0, 7.0)),
Matrix::scale(0.5, 0.5),
)
.expect("invertible base");
assert_eq!((to_double.e, to_double.f), (0.0, 0.0));
assert_eq!(decode_target_size(draw, Some(to_double)), Some((32, 32)));
let to_half = decode_floor_map(Matrix::IDENTITY, Matrix::scale(0.5, 0.5));
assert_eq!(
decode_target_size(draw, to_half),
Some((16, 16)),
"never lowered"
);
let skewed = decode_floor_map(Matrix::IDENTITY, Matrix::scale(2.0, 0.5));
assert_eq!(decode_target_size(draw, skewed), Some((32, 16)), "per axis");
assert_eq!(
decode_floor_map(Matrix::scale(0.0, 1.0), Matrix::IDENTITY),
None
);
assert_eq!(
decode_target_size(Matrix::scale(0.0, 16.0), Some(to_double)),
None,
"a degenerate draw keeps the full-resolution hint"
);
}
#[test]
fn decode_floor_shares_one_decode_between_products() {
let page = dct_page_sized(jpeg_payload_sized(64, 11), 64);
let codecs = registry();
assert_eq!(
decoded_size(&lower_with_floor(&page, 0.25, 16, &codecs, None, None)),
(16, 16),
"the analysis draw alone decodes at 1/4 scale"
);
let cache = Arc::new(SharedImageCache::default());
let analysis = lower_with_floor(&page, 0.25, 16, &codecs, Some(0.5), Some(&cache));
let base = lower_with_floor(&page, 0.5, 32, &codecs, Some(0.5), Some(&cache));
assert_eq!(cache.stats(), (1, 1, 1), "one decode, then a hit");
assert_eq!(decoded_size(&analysis), (32, 32));
assert!(Arc::ptr_eq(
&prepared_samples(&analysis),
&prepared_samples(&base)
));
let unfloored = lower_with_floor(&page, 0.5, 32, &codecs, None, None);
assert_eq!(render_pixels(&base), render_pixels(&unfloored));
}
#[test]
fn decode_floor_output_depends_on_the_request_alone() {
let page = dct_page_sized(jpeg_payload_sized(64, 12), 64);
let codecs = registry();
let analysis = |cache: Option<&Arc<SharedImageCache>>| {
render_pixels(&lower_with_floor(
&page,
0.25,
16,
&codecs,
Some(0.5),
cache,
))
};
let uncached = analysis(None);
let fresh = Arc::new(SharedImageCache::default());
assert_eq!(analysis(Some(&fresh)), uncached);
let warm = Arc::new(SharedImageCache::default());
for (scale, device) in [(1.0, 64), (0.125, 8), (0.5, 32)] {
lower_with_floor(&page, scale, device, &codecs, None, Some(&warm));
}
assert_eq!(analysis(Some(&warm)), uncached);
}
#[test]
fn decode_floor_never_lowers_a_larger_draw() {
let page = dct_page_sized(jpeg_payload_sized(64, 13), 64);
let codecs = registry();
let cache = Arc::new(SharedImageCache::default());
let base = lower_with_floor(&page, 0.5, 32, &codecs, Some(0.5), Some(&cache));
let region = lower_with_floor(&page, 1.0, 64, &codecs, Some(0.5), Some(&cache));
assert_eq!(decoded_size(&base), (32, 32));
assert_eq!(decoded_size(®ion), (64, 64));
assert_eq!(cache.stats(), (0, 2, 2));
let unfloored = lower_with_floor(&page, 1.0, 64, &codecs, None, None);
assert_eq!(render_pixels(®ion), render_pixels(&unfloored));
}
#[derive(Debug, Default)]
struct SpaceAwareJpxCodec {
decodes: AtomicUsize,
}
impl crate::image::ImageCodec for SpaceAwareJpxCodec {
fn filter(&self) -> crate::image::StreamFilter {
crate::image::StreamFilter::Jpx
}
fn decode(
&self,
_data: &[u8],
descriptor: &crate::image::ImageDescriptor,
_params: &crate::image::DecodeParameters,
_limits: &crate::image::DecodeLimits,
) -> Result<crate::image::DecodedImage, crate::image::ImageError> {
self.decodes.fetch_add(1, Ordering::Relaxed);
let indexed = descriptor
.color_space
.as_ref()
.is_some_and(|cs| cs.family == crate::color::ColorSpaceFamily::Indexed);
let (format, channels) = if indexed {
(crate::image::DecodedFormat::Gray8, 1)
} else {
(crate::image::DecodedFormat::Rgb8, 3)
};
let (width, height) = (descriptor.width, descriptor.height);
let len = width as usize * height as usize * channels;
Ok(crate::image::DecodedImage {
width,
height,
format,
stride: width as usize * channels,
data: Arc::from((0..len).map(|i| (i * 7 % 251) as u8).collect::<Vec<u8>>()),
})
}
fn reduction_level(
&self,
_data: &[u8],
_descriptor: &crate::image::ImageDescriptor,
_params: &crate::image::DecodeParameters,
_limits: &crate::image::DecodeLimits,
) -> Option<u8> {
Some(0)
}
}
#[test]
fn declared_colour_space_is_part_of_the_decode_identity() {
let mut indexed = dct_page_sized(b"one JPX payload, two dictionaries".to_vec(), 16);
let mut image = indexed.images[0].clone();
image.codec = Some(crate::page_ir::ImageCodecKind::Jpx);
image.color_space = ImageColorSpace::Indexed {
base: Box::new(ImageColorSpace::Rgb),
hival: 255,
lookup: Arc::from((0..768).map(|i| (i * 13 % 256) as u8).collect::<Vec<u8>>()),
};
indexed.images = Arc::from([image.clone()]);
let mut rgb = indexed.clone();
image.color_space = ImageColorSpace::Rgb;
rgb.images = Arc::from([image]);
let codec = Arc::new(SpaceAwareJpxCodec::default());
let codecs =
crate::image::CodecRegistry::new([codec.clone() as Arc<dyn crate::image::ImageCodec>]);
let lower = |page: &CompiledPage, cache: Option<&Arc<SharedImageCache>>| {
lower_with_codecs(page, 1.0, 16, &codecs, cache)
};
let cache = Arc::new(SharedImageCache::default());
let indexed_cached = lower(&indexed, Some(&cache));
let rgb_cached = lower(&rgb, Some(&cache));
assert_eq!(
codec.decodes.load(Ordering::Relaxed),
2,
"one decode per declared colour space"
);
for (cached, page) in [(&indexed_cached, &indexed), (&rgb_cached, &rgb)] {
let uncached = lower(page, None);
assert_eq!(
prepared_image(cached).color_space,
prepared_image(&uncached).color_space
);
assert_eq!(prepared_samples(cached), prepared_samples(&uncached));
assert_eq!(render_pixels(cached), render_pixels(&uncached));
}
}
fn indexed_page(lookup: Vec<u8>, decode: Option<[f32; 2]>) -> CompiledPage {
let mut page = dct_page(jpeg_payload(0));
let mut image = page.images[0].clone();
image.bits_per_component = 4;
image.color_space = ImageColorSpace::Indexed {
base: Box::new(ImageColorSpace::Rgb),
hival: 15,
lookup: Arc::from(lookup),
};
image.decode = decode.map(|d| Arc::from(vec![d]));
image.samples = Some(Arc::from(
(0..16 * 8)
.map(|i| (i as u8).wrapping_mul(37))
.collect::<Vec<u8>>(),
));
image.codec = None;
image.codec_data = None;
page.images = Arc::from([image]);
page
}
fn prepared_image(prepared: &CpuPreparedPage) -> &crate::render_cpu::image::PreparedImage {
prepared
.ops
.iter()
.find_map(|op| match op {
PreparedOp::Image(img) => Some(&**img),
_ => None,
})
.expect("an image op was lowered")
}
#[test]
fn indexed_promotion_is_cached_by_content_and_renders_identically() {
let lookup: Vec<u8> = (0..48u8).map(|i| i.wrapping_mul(53)).collect();
let page = indexed_page(lookup.clone(), None);
let cache = Arc::new(SharedImageCache::default());
let uncached = lower_page(&page, None);
let cold = lower_page(&page, Some(&cache));
let warm = lower_page(&page, Some(&cache));
assert_eq!(cache.stats(), (1, 1, 1), "miss+insert then hit");
let img = prepared_image(&cold);
assert_eq!(img.color_space, ImageColorSpace::Rgb);
assert_eq!(
(img.bpc, img.decode.is_none(), img.sample_lut.is_none()),
(8, true, true)
);
assert!(Arc::ptr_eq(&img.samples, &prepared_image(&warm).samples));
assert_eq!(prepared_samples(&uncached), prepared_samples(&cold));
let mut original = img.clone();
let ir = &page.images[0];
original.color_space = ir.color_space.clone();
original.bpc = 4;
original.samples = ir.samples.clone().unwrap();
original.sample_lut =
crate::render_cpu::image::build_sample_lut(4, &ir.color_space, None, false);
let expanded = original.indexed_promoted_to_rgb8().expect("eligible");
assert_eq!(expanded.samples, img.samples);
let base = render_pixels(&uncached);
assert_eq!(base, render_pixels(&cold));
assert_eq!(base, render_pixels(&warm));
let mut other = lookup.clone();
other[3] ^= 0xff;
let repaletted = lower_page(&indexed_page(other, None), Some(&cache));
let decoded = lower_page(&indexed_page(lookup, Some([15.0, 0.0])), Some(&cache));
assert_eq!(cache.len(), 3, "palette and /Decode are part of the key");
assert_ne!(prepared_samples(&repaletted), prepared_samples(&cold));
assert_ne!(prepared_samples(&decoded), prepared_samples(&cold));
}
fn sixteen_bit_page(space: ImageColorSpace, comps: usize, placement: Matrix) -> CompiledPage {
let mut page = dct_page(jpeg_payload(0));
let mut image = page.images[0].clone();
image.bits_per_component = 16;
image.color_space = space;
image.width = 16;
image.height = 8;
let n = 16 * 8 * comps;
let mut samples = Vec::with_capacity(n * 2);
for i in 0..n {
let v = ((i as u32).wrapping_mul(2_654_435_761u32) >> 8) as u16;
samples.extend_from_slice(&v.to_be_bytes());
}
image.samples = Some(Arc::from(samples));
image.codec = None;
image.codec_data = None;
page.images = Arc::from([image]);
page.operations = Arc::from([
DisplayOp::ConcatTransform(placement),
DisplayOp::DrawImage {
image: crate::page_ir::ImageId(0),
paint: crate::page_ir::PaintId(0),
transform: Matrix::IDENTITY,
alpha: 1.0,
blend: crate::page_ir::BlendMode::Normal,
},
]);
page
}
#[test]
fn sixteen_bit_device_images_promote_only_where_the_ring_is_unchanged() {
let whole = Matrix {
a: 12.0,
b: 0.0,
c: 0.0,
d: 12.0,
e: 2.0,
f: 3.0,
};
let fractional = Matrix {
a: 11.5,
b: 0.0,
c: 0.0,
d: 12.0,
e: 2.25,
f: 3.0,
};
let rotated = Matrix {
a: 8.0,
b: 5.0,
c: -5.0,
d: 8.0,
e: 6.0,
f: 1.0,
};
for (space, comps) in [
(ImageColorSpace::Gray, 1usize),
(ImageColorSpace::Rgb, 3),
(ImageColorSpace::Cmyk, 4),
] {
for (name, placement, promoted) in [
("whole", whole, true),
("fractional", fractional, false),
("rotated", rotated, true),
] {
let page = sixteen_bit_page(space.clone(), comps, placement);
let cache = Arc::new(SharedImageCache::default());
let mut lowered = lower_page(&page, Some(&cache));
let img = prepared_image(&lowered);
assert_eq!(img.bpc == 8, promoted, "{space:?} {name}");
let got = render_pixels(&lowered);
for op in lowered.ops.iter_mut() {
if let PreparedOp::Image(img) = op {
let ir = &page.images[0];
**img = crate::render_cpu::image::PreparedImage {
bpc: 16,
color_space: ir.color_space.clone(),
samples: ir.samples.clone().unwrap(),
..(**img).clone()
};
}
}
assert_eq!(prepared_image(&lowered).bpc, 16);
assert_eq!(got, render_pixels(&lowered), "{space:?} {name}");
if promoted {
let again = lower_page(&page, Some(&cache));
assert_eq!(prepared_image(&again).bpc, 8);
assert_eq!(cache.stats().2, 1, "{space:?} {name}: one promotion hit");
}
}
}
}
#[test]
fn dct_nearest_hint_uses_continuous_tone_magnification_smoothing() {
let prepared = lower_page(&dct_page(jpeg_payload(17)), None);
let interpolation = prepared.ops.iter().find_map(|op| match op {
PreparedOp::Image(image) => Some(image.interpolation),
_ => None,
});
assert_eq!(
interpolation,
Some(InterpolationMode::Bilinear),
"JPEG scans follow PDFium/MuPDF's magnification policy"
);
}
#[test]
fn distinct_payloads_get_distinct_entries_and_lru_bounds_bytes() {
let cache = Arc::new(SharedImageCache::default());
let page_a = dct_page(jpeg_payload(3));
let page_b = dct_page(jpeg_payload(200));
let a = prepared_samples(&lower_page(&page_a, Some(&cache)));
let b = prepared_samples(&lower_page(&page_b, Some(&cache)));
assert_ne!(a, b, "different payloads decode differently");
assert_eq!(cache.len(), 2);
let tiny = Arc::new(SharedImageCache::new(SharedImageCache::SHARDS * 512));
for seed in 0..32u8 {
let _ = lower_page(&dct_page(jpeg_payload(seed)), Some(&tiny));
}
assert!(
tiny.retained_bytes() <= SharedImageCache::SHARDS * 512,
"retained {} bytes exceeds budget",
tiny.retained_bytes()
);
}
#[test]
fn oversized_entries_and_alpha_cannot_escape_the_hard_cache_bound() {
let total = SharedImageCache::SHARDS * 1024;
let cache = SharedImageCache::new(total);
for shard in 0..SharedImageCache::SHARDS {
cache.insert(cache_key_for_shard(shard), cached_samples(512, 0));
}
assert!(cache.retained_bytes() <= total);
let scan_cache = SharedImageCache::new(total);
scan_cache.insert(cache_key_for_shard(0), cached_samples(2048, 0));
assert_eq!(scan_cache.len(), 1);
assert!(scan_cache.retained_bytes() <= total);
let alpha_cache = SharedImageCache::new(1024);
alpha_cache.insert(cache_key_for_shard(0), cached_samples(512, 768));
assert_eq!(alpha_cache.len(), 0);
assert_eq!(alpha_cache.retained_bytes(), 0);
let empty = SharedImageCache::new(total);
empty.insert(cache_key_for_shard(0), cached_samples(total * 2, 0));
assert_eq!(empty.len(), 0);
assert_eq!(empty.retained_bytes(), 0);
}
#[test]
fn concurrent_misses_have_one_producer_and_share_its_result() {
let workers = 8;
let cache = Arc::new(SharedImageCache::default());
let start = Arc::new(Barrier::new(workers));
let producers = Arc::new(AtomicUsize::new(0));
let key = cache_key_for_shard(0);
let threads: Vec<_> = (0..workers)
.map(|_| {
let cache = Arc::clone(&cache);
let start = Arc::clone(&start);
let producers = Arc::clone(&producers);
std::thread::spawn(move || {
start.wait();
match cache.probe(key) {
ImageCacheProbe::Hit(decoded) => decoded,
ImageCacheProbe::Leader(flight) => {
producers.fetch_add(1, Ordering::Relaxed);
let decoded = cached_samples(4096, 1024);
flight.complete(&decoded);
decoded
}
}
})
})
.collect();
let decoded: Vec<_> = threads
.into_iter()
.map(|thread| thread.join().unwrap())
.collect();
assert_eq!(producers.load(Ordering::Relaxed), 1);
for other in &decoded[1..] {
assert!(Arc::ptr_eq(&decoded[0].samples, &other.samples));
assert!(Arc::ptr_eq(
decoded[0].alpha.as_ref().unwrap(),
other.alpha.as_ref().unwrap()
));
}
}
#[test]
#[allow(
clippy::panic,
reason = "the test deliberately unwinds a producer to verify RAII wakeup"
)]
fn failed_cancelled_or_panicked_producer_wakes_and_allows_retry() {
let cache = Arc::new(SharedImageCache::default());
let key = cache_key_for_shard(0);
let ImageCacheProbe::Leader(cancelled) = cache.probe(key) else {
panic!("cold cache must elect a producer");
};
let waiter_cache = Arc::clone(&cache);
let (waiting, waiter_is_ready) = std::sync::mpsc::channel();
let waiter = std::thread::spawn(move || {
waiting.send(()).unwrap();
let ImageCacheProbe::Leader(retry) = waiter_cache.probe(key) else {
panic!("a failed producer has no cached result");
};
drop(retry);
});
waiter_is_ready.recv().unwrap();
while Arc::strong_count(&cancelled.flight) < 3 {
std::thread::yield_now();
}
drop(cancelled);
waiter.join().unwrap();
let decode_error: Result<(), ()> = (|| {
let ImageCacheProbe::Leader(_guard) = cache.probe(key) else {
return Ok(());
};
Err(())
})();
assert_eq!(decode_error, Err(()));
let ImageCacheProbe::Leader(error_retry) = cache.probe(key) else {
panic!("a codec error must permit retry");
};
drop(error_retry);
let unwind = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
let ImageCacheProbe::Leader(_guard) = cache.probe(key) else {
panic!("cold cache must elect a producer");
};
panic!("synthetic codec panic");
}));
assert!(unwind.is_err());
assert!(matches!(cache.probe(key), ImageCacheProbe::Leader(_)));
}
}