Allocate native PNG transparency and palette objects

This commit is contained in:
gloamxun committed 2026-11-27 21:30:31 +08:00
1 parent 51451813dc
commit 342bedf9b4
9 files changed
+215 -29

No files matched your search

@@ -452,6 +452,7 @@ impl Executor {
let mut has_space_nodes = false;
let mut has_explicit_space = false;
let mut pdf_objects = Vec::new();
let mut pdf_images = Vec::new();
let mut pdf_forms = Vec::new();
let mut xdv_annotations = std::collections::BTreeMap::new();
let mut reopened_images = false;
@@ -496,6 +497,17 @@ impl Executor {
self.current = output.span;
self.tick()?;
pdf_forms.push((form.number, output.span));
} else if let OutputOperation::PdfImage { image, .. } = &output.operation
&& !unicode_pages && device.pdf.is_some()
{
self.current = output.span;
self.tick()?;
if let Some(page) = &mut shipout.pdf_objects
&& page.png_group.is_none()
{
page.png_group = image.png_group;
}
pdf_images.push((image.id, output.span));
} else if let OutputOperation::PdfColor { stack, action } = &output.operation {
if device.pdf.is_none() {
return self.fail("cannot ship a PDF color operation to DVI");
@@ -705,6 +717,10 @@ impl Executor {
.finish_page(self.shipped_pages as u32 + 1, limit)
.map_err(|message| self.error(message, current))?;
}
for (image, span) in pdf_images {
self.current = span;
self.declare_pdf_image(image, files)?;
}
if reopened_images {
self.rebind_shipped_format_images(&mut shipout.box_node)?;
}
@@ -233,6 +233,11 @@ impl Executor {
self.reads.insert(Dependency::PdfObjects);
image.pdf_object_number = Some(self.state.pdf_objects.get_or_insert_with(Default::default)
.reserve_image(id, self.limits.tokens).map_err(|error| self.error(error, token.span))?);
let header = header.expect("prepared pdfTeX header");
if image.image.reserves_png_group((header.major, i32::from(header.minor))) {
image.png_group = Some(self.state.pdf_objects.as_deref_mut().expect("registered image")
.reserve_png_group(self.limits.tokens).map_err(|error| self.error(error, token.span))?);
}
}
let saved = (pdftex && self.state.is_initex())
.then(|| FormatPdfImage::capture(&image, &attributes, format_kind));
@@ -486,7 +491,7 @@ impl Executor {
pending_xdv: None,
});
let hidden = special.hidden;
self.emit_pdf_image_object(image.clone(), special.attributes);
self.emit_pdf_image_object(image.clone(), special.attributes, None);
Ok((!hidden).then_some(image))
}
@@ -538,7 +543,18 @@ impl Executor {
} else {
text.into_bytes()
};
self.emit_pdf_image_object(image, attributes);
let png_auxiliary = if self.state.input_profile() == InputProfile::TeX8Bit
&& let Some(header) = self.state.pdf_header_options
&& let Some(is_mask) = image.image.png_auxiliary_stream((header.major, i32::from(header.minor)))
{
self.reads.insert(Dependency::PdfObjects);
Some(self.state.pdf_objects.get_or_insert_with(Default::default)
.reserve_png_auxiliary(is_mask, self.limits.tokens)
.map_err(|error| self.error(error, self.current))?)
} else {
None
};
self.emit_pdf_image_object(image, attributes, png_auxiliary);
Ok(())
}
@@ -578,7 +594,9 @@ impl Executor {
.map_err(|message| self.error(message, b.span))
}
fn emit_pdf_image_object(&mut self, image: Arc<PdfImageUse>, attributes: Vec<u8>) {
fn emit_pdf_image_object(
&mut self, image: Arc<PdfImageUse>, attributes: Vec<u8>, png_auxiliary: Option<u32>,
) {
let compression = self
.read_parameter(Parameter::Pdfcompresslevel)
.width()
@@ -587,6 +605,7 @@ impl Executor {
image,
attributes,
compression,
png_auxiliary,
}));
}
@@ -14,9 +14,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 88;
const COMPATIBLE_SCHEMAS: [u32; 55] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, SCHEMA,
const SCHEMA: u32 = 89;
const COMPATIBLE_SCHEMAS: [u32; 56] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -208,8 +208,13 @@ impl FormatImage {
} else {
saved.image.image.color_space.is_none()
};
let valid_group = saved.image.png_group.is_none_or(|group| {
image.schema >= 89 && saved.kind == FormatImageKind::Png
&& pdf_objects.is_some_and(|objects| objects.is_png_group(group))
});
if !valid_profile
|| !valid_number
|| !valid_group
|| saved.image.id != index + 1
|| saved.path().as_os_str().is_empty()
{
+25 -8
View File
@@ -2297,7 +2297,7 @@ fn write_pdf(
// retains its measured source image and can precede that registration.
let declarations = paint_lists.iter().flat_map(|list| &list.items).filter_map(|item| {
if let DisplayItem::PdfImageObject(object) = item {
Some((object.image.as_ref(), object.attributes.as_slice(), object.compression))
Some((object.image.as_ref(), object.attributes.as_slice(), object.compression, object.png_auxiliary))
} else {
None
}
@@ -2306,7 +2306,7 @@ fn write_pdf(
let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
list.items.iter().filter_map(move |item| {
if let DisplayItem::PdfImage { image, .. } = item {
Some((image.as_ref(), &[][..], compression))
Some((image.as_ref(), &[][..], compression, None))
} else {
None
}
@@ -2321,7 +2321,7 @@ fn write_pdf(
let mut type1_plans = type1_fonts::FontPlans::default();
// pdfTeX collects included font descriptors as it writes forms. The
// TeX font dictionaries and their glyph marks are finalized afterward.
for (image, _, _) in &images {
for (image, ..) in &images {
for font in image.image.mapped_type1_fonts() {
type1_plans.include(font);
}
@@ -2547,6 +2547,16 @@ fn write_pdf(
objects.push(Vec::new());
device_objects.insert(number, objects.len() as u32);
}
const PNG_GROUP: &[u8] = b"<< /Type /Group /S /Transparency /CS /DeviceRGB /I true >>";
if let Some(registry) = registry {
for number in registry.png_object_numbers() {
objects.push(Vec::new());
device_objects.insert(number, objects.len() as u32);
}
if let Some(group) = registry.written_png_group() {
objects[device_objects[&group] as usize - 1] = PNG_GROUP.to_vec();
}
}
let parents: BTreeSet<_> = pages.iter().filter_map(|page| {
page.pdf_resources.objects.map(|allocation| allocation.parent)
}).collect();
@@ -2590,8 +2600,12 @@ fn write_pdf(
.and_then(|page| page.pdf.as_ref())
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
let mut unwritten_color_spaces = BTreeMap::new();
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression)| {
let target = image.pdf_object_number.map(|number| device_objects[&number] as usize);
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression, auxiliary)| {
let physical = |number: u32| device_objects[&number] as usize;
let targets = crate::pdf_image::PdfImageTargets {
image: image.pdf_object_number.map(physical),
png_auxiliary: auxiliary.map(physical),
};
let color_space = image.image.color_space.map(|number| {
let Ok(reference) = u32::try_from(number) else {
return i64::from(number);
@@ -2607,7 +2621,7 @@ fn write_pdf(
})
});
let object = image.image.append_to(
&mut objects, attributes, compression, pdf_version, &type1_references, color_space, target,
&mut objects, attributes, compression, pdf_version, &type1_references, color_space, targets,
);
(image.id, object)
}).collect();
@@ -2714,14 +2728,17 @@ fn write_pdf(
}
let mut png_group = None;
for (page_index, list) in pages.iter().enumerate() {
let png_group_ref = if !list.pdf_resources.has_page_group
let png_group_ref = if let Some(page) = list.pdf_resources.objects {
page.png_group.map(|group| format!(" /Group {} 0 R", device_objects[&group]))
.unwrap_or_default()
} else if !list.pdf_resources.has_page_group
&& list.items.iter().any(|item| {
matches!(item, DisplayItem::PdfImage { image, .. }
if image.image.png_transparency(pdf_version))
})
{
let id = *png_group.get_or_insert_with(|| {
objects.push(b"<< /Type /Group /S /Transparency /CS /DeviceRGB /I true >>".to_vec());
objects.push(PNG_GROUP.to_vec());
objects.len()
});
format!(" /Group {id} 0 R")
@@ -18,6 +18,8 @@ pub(crate) enum ObjectBody {
Form,
FormResources,
Image(usize),
PngGroup,
PngAuxiliary,
Font(FontId),
PageResources,
PageContents,
@@ -40,7 +42,7 @@ impl ObjectBody {
match self {
Self::Page | Self::Link | Self::FormatLink | Self::Form
| Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
| Self::Pages | Self::DiscardedAtDump => 0,
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::DiscardedAtDump => 0,
Self::Direct(bytes) => bytes.len(),
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
Self::File {
@@ -58,7 +60,8 @@ impl ObjectBody {
fn parse(&self) -> Result<Object, String> {
match self {
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources
| Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents | Self::Pages => {
| Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
| Self::Pages | Self::PngGroup | Self::PngAuxiliary => {
Err("expected a generic native PDF object".into())
}
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".into()),
@@ -81,6 +84,8 @@ pub(crate) struct PageObjects {
pub resources: u32,
pub contents: u32,
pub parent: u32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub png_group: Option<u32>,
}
pub(crate) const PAGE_TREE_FANOUT: u32 = 6;
@@ -101,6 +106,10 @@ pub struct PdfObjects {
font_numbers: BTreeMap<FontId, u32>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
scalable_fonts: BTreeMap<String, u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
png_group: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
written_png_group: Option<u32>,
}
impl PdfObjects {
@@ -184,6 +193,38 @@ impl PdfObjects {
Ok(number)
}
pub(crate) fn reserve_png_group(&mut self, limit: usize) -> Result<u32, String> {
if let Some(group) = self.png_group {
return Ok(group);
}
let group = self.allocate(Some(Arc::new(ObjectBody::PngGroup)), limit)?;
self.png_group = Some(group);
Ok(group)
}
pub(crate) fn is_png_group(&self, number: u32) -> bool {
matches!(self.entry(number).and_then(Option::as_deref), Some(ObjectBody::PngGroup))
}
pub(crate) fn reserve_png_auxiliary(&mut self, mask: bool, limit: usize) -> Result<u32, String> {
let number = self.allocate(Some(Arc::new(ObjectBody::PngAuxiliary)), limit)?;
if mask {
self.written_png_group = self.png_group;
}
Ok(number)
}
pub(crate) fn png_object_numbers(&self) -> impl Iterator<Item = u32> + '_ {
self.values.iter().enumerate().filter_map(|(index, entry)| {
matches!(entry.as_deref(), Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary))
.then_some(index as u32 + 1)
})
}
pub(crate) fn written_png_group(&self) -> Option<u32> {
self.written_png_group
}
pub(crate) fn reserve_image(&mut self, image: usize, limit: usize) -> Result<u32, String> {
self.allocate(Some(Arc::new(ObjectBody::Image(image))), limit)
}
@@ -210,7 +251,7 @@ impl PdfObjects {
let resources = self.allocate(Some(Arc::new(ObjectBody::PageResources)), limit)?;
self.page_reference(page, limit)?;
let contents = self.allocate(Some(Arc::new(ObjectBody::PageContents)), limit)?;
Ok(PageObjects { resources, contents, parent: 0 })
Ok(PageObjects { resources, contents, parent: 0, png_group: None })
}
pub(crate) fn finish_page(&mut self, page: u32, limit: usize) -> Result<u32, String> {
@@ -245,7 +286,8 @@ impl PdfObjects {
// A restored link whatsit gets its own annotation object when shipped.
Some(ObjectBody::Link) => ObjectBody::FormatLink,
Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources
| ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)) => {
| ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)
| ObjectBody::PngAuxiliary) => {
ObjectBody::DiscardedAtDump
}
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
@@ -260,6 +302,8 @@ impl PdfObjects {
self.page_parent = None;
self.font_numbers.clear();
self.scalable_fonts.clear();
self.png_group = None;
self.written_png_group = None;
!self.values.is_empty()
}
@@ -715,7 +759,10 @@ impl ResourceOutput {
continue;
}
if values.contains_key(&number) || page_objects.contains(&number)
|| device_objects.contains(&number) || objects.font_owner(number).is_some() {
|| device_objects.contains(&number) || objects.font_owner(number).is_some()
|| matches!(objects.entry(number).and_then(Option::as_deref),
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary))
{
continue;
}
if objects.is_discarded_at_dump(number) {
+29 -2
View File
@@ -61,6 +61,8 @@ pub struct PdfImageUse {
pub id: usize,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) pdf_object_number: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) png_group: Option<u32>,
pub image: Arc<PdfImage>,
pub width: i64,
pub height: i64,
@@ -104,6 +106,14 @@ pub struct PdfImageObject {
pub attributes: Vec<u8>,
#[serde(default)]
pub compression: u8,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) png_auxiliary: Option<u32>,
}
#[derive(Clone, Copy)]
pub(crate) struct PdfImageTargets {
pub image: Option<usize>,
pub png_auxiliary: Option<usize>,
}
impl PdfImageUse {
@@ -139,6 +149,7 @@ impl PdfImageUse {
Ok(Self {
id,
pdf_object_number: None,
png_group: None,
image: Arc::new(image),
width,
height,
@@ -186,6 +197,7 @@ impl PdfImageUse {
Ok(Self {
id,
pdf_object_number: None,
png_group: None,
image,
width,
height,
@@ -233,6 +245,7 @@ impl PdfImageUse {
Ok(Self {
id,
pdf_object_number: None,
png_group: None,
image,
width: (right - left) as i64,
height: (top - bottom) as i64,
@@ -633,6 +646,19 @@ impl PdfImage {
self.sampled_image().is_some_and(|samples| samples.has_alpha(pdf_version))
}
pub(crate) fn reserves_png_group(&self, version: (i32, i32)) -> bool {
matches!(self.objects.first().map(Vec::as_slice), Some([Part::Png(samples)])
if samples.source_alpha && samples.has_alpha(version))
}
pub(crate) fn png_auxiliary_stream(&self, version: (i32, i32)) -> Option<bool> {
match self.objects.first()?.as_slice() {
[Part::Png(samples)] if samples.has_alpha(version) => Some(true),
[Part::Png(samples)] if samples.uses_palette() => Some(false),
_ => None,
}
}
pub(crate) fn read(
resource: LoadedResource,
doc: Document,
@@ -854,11 +880,12 @@ impl PdfImage {
pdf_version: (i32, i32),
fonts: &crate::pdf::type1_fonts::References<'_>,
color_space: Option<i64>,
target: Option<usize>,
targets: PdfImageTargets,
) -> usize {
if let Some(samples) = self.sampled_image() {
return samples.append(pdf, attributes, compression, pdf_version, color_space, target);
return samples.append(pdf, attributes, compression, pdf_version, color_space, targets);
}
let target = targets.image;
// A preallocated image slot owns the first object. Other imported objects
// still occupy a contiguous range, including references back to the image.
let base = pdf.len() + usize::from(target.is_none());
+32 -8
View File
@@ -1,5 +1,5 @@
//! Decode PNG samples for native PDF image XObjects.
use super::{Part, PdfImage, RasterProcSet};
use super::{Part, PdfImage, PdfImageTargets, RasterProcSet};
use crate::{pdf::objects, resources::LoadedResource};
use ::png::{ColorType, Decoder, PixelDimensions, Transformations, Unit};
use serde::{Deserialize, Serialize};
@@ -20,6 +20,8 @@ pub(super) struct SampledImage {
pub(super) source_depth: u8,
#[serde(default)]
source_indexed: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub(super) source_alpha: bool,
depth: u8,
color: ColorSpace,
samples: Vec<u8>,
@@ -37,6 +39,7 @@ pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, Option<PixelDimensio
let [width, height] = [reader.info().width, reader.info().height];
let source_depth = reader.info().bit_depth as u8;
let source_indexed = reader.info().color_type == ColorType::Indexed;
let source_alpha = matches!(reader.info().color_type, ColorType::GrayscaleAlpha | ColorType::Rgba);
// Preserve packed grayscale and palettes unless tRNS needs an alpha channel.
if reader.info().trns.is_some() {
reader = read_info(Transformations::EXPAND)?;
@@ -94,6 +97,7 @@ pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, Option<PixelDimensio
size: [width, height],
source_depth,
source_indexed,
source_alpha,
depth,
color,
samples: buf,
@@ -155,6 +159,7 @@ impl SampledImage {
size,
source_depth: 8,
source_indexed: false,
source_alpha: false,
depth: 8,
color: ColorSpace::Rgb,
samples,
@@ -177,6 +182,10 @@ impl SampledImage {
pdf_version >= (1, 4) && !self.alpha.is_empty()
}
pub(super) fn uses_palette(&self) -> bool {
matches!(self.color, ColorSpace::Indexed(_))
}
pub(super) fn append(
&self,
pdf: &mut Vec<Vec<u8>>,
@@ -184,14 +193,19 @@ impl SampledImage {
compression: u8,
pdf_version: (i32, i32),
color_space: Option<i64>,
target: Option<usize>,
targets: PdfImageTargets,
) -> usize {
let target = targets.image;
let id = target.unwrap_or(pdf.len() + 1);
let [width, height] = self.size;
let mut color = match (color_space, &self.color) {
(Some(id), _) => format!("{id} 0 R"),
(None, ColorSpace::Gray) => "/DeviceGray".to_owned(),
(None, ColorSpace::Rgb) => "/DeviceRGB".to_owned(),
(None, ColorSpace::Indexed(table)) if targets.png_auxiliary.is_some() => {
let palette = targets.png_auxiliary.unwrap();
format!("[/Indexed /DeviceRGB {} {palette} 0 R]", table.len() / 3 - 1)
}
(None, ColorSpace::Indexed(table)) => {
let mut color = format!("[/Indexed /DeviceRGB {} <", table.len() / 3 - 1);
for byte in table {
@@ -201,9 +215,10 @@ impl SampledImage {
color
}
};
let has_alpha = self.has_alpha(pdf_version);
if has_alpha {
let mask = pdf.len() + 1 + usize::from(target.is_none());
let mask = self.has_alpha(pdf_version).then(|| {
targets.png_auxiliary.unwrap_or(pdf.len() + 1 + usize::from(target.is_none()))
});
if let Some(mask) = mask {
write!(color, " /SMask {mask} 0 R").expect("writing to a string");
}
let strip_16 = pdf_version < (1, 5) && self.depth == 16;
@@ -228,15 +243,24 @@ impl SampledImage {
} else {
pdf.push(stream);
}
if has_alpha {
pdf.push(objects::stream(
if let Some(mask) = mask {
let stream = objects::stream(
&format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace /DeviceGray /BitsPerComponent 8"
),
&self.alpha,
compression,
));
);
if targets.png_auxiliary.is_some() {
pdf[mask - 1] = stream;
} else {
pdf.push(stream);
}
} else if let ColorSpace::Indexed(table) = &self.color
&& let Some(palette) = targets.png_auxiliary
{
pdf[palette - 1] = objects::stream("", table, compression);
}
id
}