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_space_nodes = false;
let mut has_explicit_space = false; let mut has_explicit_space = false;
let mut pdf_objects = Vec::new(); let mut pdf_objects = Vec::new();
let mut pdf_images = Vec::new();
let mut pdf_forms = Vec::new(); let mut pdf_forms = Vec::new();
let mut xdv_annotations = std::collections::BTreeMap::new(); let mut xdv_annotations = std::collections::BTreeMap::new();
let mut reopened_images = false; let mut reopened_images = false;
@@ -496,6 +497,17 @@ impl Executor {
self.current = output.span; self.current = output.span;
self.tick()?; self.tick()?;
pdf_forms.push((form.number, output.span)); 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 { } else if let OutputOperation::PdfColor { stack, action } = &output.operation {
if device.pdf.is_none() { if device.pdf.is_none() {
return self.fail("cannot ship a PDF color operation to DVI"); 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) .finish_page(self.shipped_pages as u32 + 1, limit)
.map_err(|message| self.error(message, current))?; .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 { if reopened_images {
self.rebind_shipped_format_images(&mut shipout.box_node)?; self.rebind_shipped_format_images(&mut shipout.box_node)?;
} }
@@ -233,6 +233,11 @@ impl Executor {
self.reads.insert(Dependency::PdfObjects); self.reads.insert(Dependency::PdfObjects);
image.pdf_object_number = Some(self.state.pdf_objects.get_or_insert_with(Default::default) 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))?); .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()) let saved = (pdftex && self.state.is_initex())
.then(|| FormatPdfImage::capture(&image, &attributes, format_kind)); .then(|| FormatPdfImage::capture(&image, &attributes, format_kind));
@@ -486,7 +491,7 @@ impl Executor {
pending_xdv: None, pending_xdv: None,
}); });
let hidden = special.hidden; 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)) Ok((!hidden).then_some(image))
} }
@@ -538,7 +543,18 @@ impl Executor {
} else { } else {
text.into_bytes() 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(()) Ok(())
} }
@@ -578,7 +594,9 @@ impl Executor {
.map_err(|message| self.error(message, b.span)) .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 let compression = self
.read_parameter(Parameter::Pdfcompresslevel) .read_parameter(Parameter::Pdfcompresslevel)
.width() .width()
@@ -587,6 +605,7 @@ impl Executor {
image, image,
attributes, attributes,
compression, compression,
png_auxiliary,
})); }));
} }
@@ -14,9 +14,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak}, sync::{Arc, Mutex, OnceLock, Weak},
}; };
const SCHEMA: u32 = 88; const SCHEMA: u32 = 89;
const COMPATIBLE_SCHEMAS: [u32; 55] = [ 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, SCHEMA, 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")); const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -208,8 +208,13 @@ impl FormatImage {
} else { } else {
saved.image.image.color_space.is_none() 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 if !valid_profile
|| !valid_number || !valid_number
|| !valid_group
|| saved.image.id != index + 1 || saved.image.id != index + 1
|| saved.path().as_os_str().is_empty() || 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. // retains its measured source image and can precede that registration.
let declarations = paint_lists.iter().flat_map(|list| &list.items).filter_map(|item| { let declarations = paint_lists.iter().flat_map(|list| &list.items).filter_map(|item| {
if let DisplayItem::PdfImageObject(object) = 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 { } else {
None None
} }
@@ -2306,7 +2306,7 @@ fn write_pdf(
let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression); let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
list.items.iter().filter_map(move |item| { list.items.iter().filter_map(move |item| {
if let DisplayItem::PdfImage { image, .. } = item { if let DisplayItem::PdfImage { image, .. } = item {
Some((image.as_ref(), &[][..], compression)) Some((image.as_ref(), &[][..], compression, None))
} else { } else {
None None
} }
@@ -2321,7 +2321,7 @@ fn write_pdf(
let mut type1_plans = type1_fonts::FontPlans::default(); let mut type1_plans = type1_fonts::FontPlans::default();
// pdfTeX collects included font descriptors as it writes forms. The // pdfTeX collects included font descriptors as it writes forms. The
// TeX font dictionaries and their glyph marks are finalized afterward. // 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() { for font in image.image.mapped_type1_fonts() {
type1_plans.include(font); type1_plans.include(font);
} }
@@ -2547,6 +2547,16 @@ fn write_pdf(
objects.push(Vec::new()); objects.push(Vec::new());
device_objects.insert(number, objects.len() as u32); 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| { let parents: BTreeSet<_> = pages.iter().filter_map(|page| {
page.pdf_resources.objects.map(|allocation| allocation.parent) page.pdf_resources.objects.map(|allocation| allocation.parent)
}).collect(); }).collect();
@@ -2590,8 +2600,12 @@ fn write_pdf(
.and_then(|page| page.pdf.as_ref()) .and_then(|page| page.pdf.as_ref())
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor))); .map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
let mut unwritten_color_spaces = BTreeMap::new(); let mut unwritten_color_spaces = BTreeMap::new();
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression)| { let form_ids: BTreeMap<_, _> = images.into_iter().map(|(image, attributes, compression, auxiliary)| {
let target = image.pdf_object_number.map(|number| device_objects[&number] as usize); 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 color_space = image.image.color_space.map(|number| {
let Ok(reference) = u32::try_from(number) else { let Ok(reference) = u32::try_from(number) else {
return i64::from(number); return i64::from(number);
@@ -2607,7 +2621,7 @@ fn write_pdf(
}) })
}); });
let object = image.image.append_to( 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) (image.id, object)
}).collect(); }).collect();
@@ -2714,14 +2728,17 @@ fn write_pdf(
} }
let mut png_group = None; let mut png_group = None;
for (page_index, list) in pages.iter().enumerate() { 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| { && list.items.iter().any(|item| {
matches!(item, DisplayItem::PdfImage { image, .. } matches!(item, DisplayItem::PdfImage { image, .. }
if image.image.png_transparency(pdf_version)) if image.image.png_transparency(pdf_version))
}) })
{ {
let id = *png_group.get_or_insert_with(|| { 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() objects.len()
}); });
format!(" /Group {id} 0 R") format!(" /Group {id} 0 R")
@@ -18,6 +18,8 @@ pub(crate) enum ObjectBody {
Form, Form,
FormResources, FormResources,
Image(usize), Image(usize),
PngGroup,
PngAuxiliary,
Font(FontId), Font(FontId),
PageResources, PageResources,
PageContents, PageContents,
@@ -40,7 +42,7 @@ impl ObjectBody {
match self { match self {
Self::Page | Self::Link | Self::FormatLink | Self::Form Self::Page | Self::Link | Self::FormatLink | Self::Form
| Self::FormResources | Self::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents | 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::Direct(bytes) => bytes.len(),
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()), Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
Self::File { Self::File {
@@ -58,7 +60,8 @@ impl ObjectBody {
fn parse(&self) -> Result<Object, String> { fn parse(&self) -> Result<Object, String> {
match self { match self {
Self::Page | Self::Link | Self::FormatLink | Self::Form | Self::FormResources 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()) Err("expected a generic native PDF object".into())
} }
Self::DiscardedAtDump => Err("PDF object belongs to the format job and cannot be reused".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 resources: u32,
pub contents: u32, pub contents: u32,
pub parent: 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; pub(crate) const PAGE_TREE_FANOUT: u32 = 6;
@@ -101,6 +106,10 @@ pub struct PdfObjects {
font_numbers: BTreeMap<FontId, u32>, font_numbers: BTreeMap<FontId, u32>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")] #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
scalable_fonts: BTreeMap<String, u32>, 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 { impl PdfObjects {
@@ -184,6 +193,38 @@ impl PdfObjects {
Ok(number) 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> { pub(crate) fn reserve_image(&mut self, image: usize, limit: usize) -> Result<u32, String> {
self.allocate(Some(Arc::new(ObjectBody::Image(image))), limit) 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)?; let resources = self.allocate(Some(Arc::new(ObjectBody::PageResources)), limit)?;
self.page_reference(page, limit)?; self.page_reference(page, limit)?;
let contents = self.allocate(Some(Arc::new(ObjectBody::PageContents)), 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> { 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. // A restored link whatsit gets its own annotation object when shipped.
Some(ObjectBody::Link) => ObjectBody::FormatLink, Some(ObjectBody::Link) => ObjectBody::FormatLink,
Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources Some(ObjectBody::Page | ObjectBody::FormResources | ObjectBody::PageResources
| ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)) => { | ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)
| ObjectBody::PngAuxiliary) => {
ObjectBody::DiscardedAtDump ObjectBody::DiscardedAtDump
} }
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump, _ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
@@ -260,6 +302,8 @@ impl PdfObjects {
self.page_parent = None; self.page_parent = None;
self.font_numbers.clear(); self.font_numbers.clear();
self.scalable_fonts.clear(); self.scalable_fonts.clear();
self.png_group = None;
self.written_png_group = None;
!self.values.is_empty() !self.values.is_empty()
} }
@@ -715,7 +759,10 @@ impl ResourceOutput {
continue; continue;
} }
if values.contains_key(&number) || page_objects.contains(&number) 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; continue;
} }
if objects.is_discarded_at_dump(number) { if objects.is_discarded_at_dump(number) {
+29 -2
View File
@@ -61,6 +61,8 @@ pub struct PdfImageUse {
pub id: usize, pub id: usize,
#[serde(default, skip_serializing_if = "Option::is_none")] #[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) pdf_object_number: Option<u32>, 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 image: Arc<PdfImage>,
pub width: i64, pub width: i64,
pub height: i64, pub height: i64,
@@ -104,6 +106,14 @@ pub struct PdfImageObject {
pub attributes: Vec<u8>, pub attributes: Vec<u8>,
#[serde(default)] #[serde(default)]
pub compression: u8, 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 { impl PdfImageUse {
@@ -139,6 +149,7 @@ impl PdfImageUse {
Ok(Self { Ok(Self {
id, id,
pdf_object_number: None, pdf_object_number: None,
png_group: None,
image: Arc::new(image), image: Arc::new(image),
width, width,
height, height,
@@ -186,6 +197,7 @@ impl PdfImageUse {
Ok(Self { Ok(Self {
id, id,
pdf_object_number: None, pdf_object_number: None,
png_group: None,
image, image,
width, width,
height, height,
@@ -233,6 +245,7 @@ impl PdfImageUse {
Ok(Self { Ok(Self {
id, id,
pdf_object_number: None, pdf_object_number: None,
png_group: None,
image, image,
width: (right - left) as i64, width: (right - left) as i64,
height: (top - bottom) 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)) 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( pub(crate) fn read(
resource: LoadedResource, resource: LoadedResource,
doc: Document, doc: Document,
@@ -854,11 +880,12 @@ impl PdfImage {
pdf_version: (i32, i32), pdf_version: (i32, i32),
fonts: &crate::pdf::type1_fonts::References<'_>, fonts: &crate::pdf::type1_fonts::References<'_>,
color_space: Option<i64>, color_space: Option<i64>,
target: Option<usize>, targets: PdfImageTargets,
) -> usize { ) -> usize {
if let Some(samples) = self.sampled_image() { 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 // A preallocated image slot owns the first object. Other imported objects
// still occupy a contiguous range, including references back to the image. // still occupy a contiguous range, including references back to the image.
let base = pdf.len() + usize::from(target.is_none()); 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. //! 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 crate::{pdf::objects, resources::LoadedResource};
use ::png::{ColorType, Decoder, PixelDimensions, Transformations, Unit}; use ::png::{ColorType, Decoder, PixelDimensions, Transformations, Unit};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
@@ -20,6 +20,8 @@ pub(super) struct SampledImage {
pub(super) source_depth: u8, pub(super) source_depth: u8,
#[serde(default)] #[serde(default)]
source_indexed: bool, source_indexed: bool,
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
pub(super) source_alpha: bool,
depth: u8, depth: u8,
color: ColorSpace, color: ColorSpace,
samples: Vec<u8>, 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 [width, height] = [reader.info().width, reader.info().height];
let source_depth = reader.info().bit_depth as u8; let source_depth = reader.info().bit_depth as u8;
let source_indexed = reader.info().color_type == ColorType::Indexed; 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. // Preserve packed grayscale and palettes unless tRNS needs an alpha channel.
if reader.info().trns.is_some() { if reader.info().trns.is_some() {
reader = read_info(Transformations::EXPAND)?; reader = read_info(Transformations::EXPAND)?;
@@ -94,6 +97,7 @@ pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, Option<PixelDimensio
size: [width, height], size: [width, height],
source_depth, source_depth,
source_indexed, source_indexed,
source_alpha,
depth, depth,
color, color,
samples: buf, samples: buf,
@@ -155,6 +159,7 @@ impl SampledImage {
size, size,
source_depth: 8, source_depth: 8,
source_indexed: false, source_indexed: false,
source_alpha: false,
depth: 8, depth: 8,
color: ColorSpace::Rgb, color: ColorSpace::Rgb,
samples, samples,
@@ -177,6 +182,10 @@ impl SampledImage {
pdf_version >= (1, 4) && !self.alpha.is_empty() pdf_version >= (1, 4) && !self.alpha.is_empty()
} }
pub(super) fn uses_palette(&self) -> bool {
matches!(self.color, ColorSpace::Indexed(_))
}
pub(super) fn append( pub(super) fn append(
&self, &self,
pdf: &mut Vec<Vec<u8>>, pdf: &mut Vec<Vec<u8>>,
@@ -184,14 +193,19 @@ impl SampledImage {
compression: u8, compression: u8,
pdf_version: (i32, i32), pdf_version: (i32, i32),
color_space: Option<i64>, color_space: Option<i64>,
target: Option<usize>, targets: PdfImageTargets,
) -> usize { ) -> usize {
let target = targets.image;
let id = target.unwrap_or(pdf.len() + 1); let id = target.unwrap_or(pdf.len() + 1);
let [width, height] = self.size; let [width, height] = self.size;
let mut color = match (color_space, &self.color) { let mut color = match (color_space, &self.color) {
(Some(id), _) => format!("{id} 0 R"), (Some(id), _) => format!("{id} 0 R"),
(None, ColorSpace::Gray) => "/DeviceGray".to_owned(), (None, ColorSpace::Gray) => "/DeviceGray".to_owned(),
(None, ColorSpace::Rgb) => "/DeviceRGB".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)) => { (None, ColorSpace::Indexed(table)) => {
let mut color = format!("[/Indexed /DeviceRGB {} <", table.len() / 3 - 1); let mut color = format!("[/Indexed /DeviceRGB {} <", table.len() / 3 - 1);
for byte in table { for byte in table {
@@ -201,9 +215,10 @@ impl SampledImage {
color color
} }
}; };
let has_alpha = self.has_alpha(pdf_version); let mask = self.has_alpha(pdf_version).then(|| {
if has_alpha { targets.png_auxiliary.unwrap_or(pdf.len() + 1 + usize::from(target.is_none()))
let mask = pdf.len() + 1 + usize::from(target.is_none()); });
if let Some(mask) = mask {
write!(color, " /SMask {mask} 0 R").expect("writing to a string"); write!(color, " /SMask {mask} 0 R").expect("writing to a string");
} }
let strip_16 = pdf_version < (1, 5) && self.depth == 16; let strip_16 = pdf_version < (1, 5) && self.depth == 16;
@@ -228,15 +243,24 @@ impl SampledImage {
} else { } else {
pdf.push(stream); pdf.push(stream);
} }
if has_alpha { if let Some(mask) = mask {
pdf.push(objects::stream( let stream = objects::stream(
&format!( &format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \ "/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace /DeviceGray /BitsPerComponent 8" /ColorSpace /DeviceGray /BitsPerComponent 8"
), ),
&self.alpha, &self.alpha,
compression, 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 id
} }
+23
View File
@@ -849,6 +849,29 @@ Form 和格式重载。二十项定向回归通过。原有动态字体名称断
对象编号阶段留存了对照。回执 target/p3-pdf-font-objects/receipt.json 对象编号阶段留存了对照。回执 target/p3-pdf-font-objects/receipt.json
的 SHA-256 为 6b705dff3ef2e12a119c17d9a9dc1b6965ff170f26f6f728ac5ba0015aebf98d。 的 SHA-256 为 6b705dff3ef2e12a119c17d9a9dc1b6965ff170f26f6f728ac5ba0015aebf98d。
### pdfTeX PNG 软遮罩、透明组与色表
图像解码记录 PNG 原生 Alpha 通道,与通过色键得到的 Alpha
样本分别处理。原生 Alpha 在读图时预留文档共享的透明组,实际
写出时分配软遮罩。索引色在写出时分配独立色表流。页和 Form
在出页资源阶段写入图像,即时输出走同一写出流程。用户 PDF
对象中的引用映射到实际透明组、遮罩和色表。
[pdfTeX 的 PNG 读取和辅助对象写出](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/writepng.c#L54-L83)
十二组原版对照通过对象编号与结构检查,覆盖 PDF 1.3、RGB
与灰度 Alpha、RGB 与索引色的颜色键、即时和未引用图像、
跨页表单、发页内分配未来页以及格式重载。schema89 保存原图像
引用的透明组。重载对照按原版保留透明组的空闲引用。十七页
144 DPI 灰度图逐像素一致。十六项图像、PDF 链接和设备配置
回归通过。编辑 PNG 时复用检查点,仅更新第二页,PDF、SVG
和来源映射与独立全量一致。
后续补齐展开图像选项之前的主对象分配,以及压缩对象流的
实时分配和成员归属。前者的原版在扫描宽度时先分配图像再分配
页面,原生基线顺序相反。后者用 105 次即时对象写出覆盖压缩级别
0–3 和百个成员后的下一流。两组对照记录在
target/p3-pdf-png-objects。阶段回执的 SHA-256 为 e2fa1a5b2a9c7b0fb9f90390a3f165923f7bc4614322ae99b9f59674b200cd19。
### PDF 预览按实际页面资源复用 ### PDF 预览按实际页面资源复用
编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。 编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。
+8
View File
@@ -460,6 +460,14 @@ fn png_project_edit_updates_only_the_page_using_the_image() {
)); ));
assert_eq!(images[0].0.content, [0, 0, 255, 0, 255, 0]); assert_eq!(images[0].0.content, [0, 0, 255, 0, 255, 0]);
assert_eq!(images[0].1.content, [255, 128]); assert_eq!(images[0].1.content, [255, 128]);
let pages = document.get_pages();
let first_page = document.get_dictionary(pages[&1]).unwrap();
assert!(!first_page.has(b"Group"));
let image_page = document.get_dictionary(pages[&2]).unwrap();
let group = image_page.get(b"Group").unwrap().as_reference().unwrap();
let group = document.get_dictionary(group).unwrap();
assert_eq!(group.get(b"S").unwrap().as_name().unwrap(), b"Transparency");
assert_eq!(group.get(b"CS").unwrap().as_name().unwrap(), b"DeviceRGB");
fs::remove_dir_all(root).unwrap(); fs::remove_dir_all(root).unwrap();
} }