Allocate compressed PDF object streams during native output
This commit is contained in:
1 parent
d87464fde3
commit
70ebacb056
9 files changed
+315
-46
No files matched your search
@@ -268,11 +268,15 @@ impl Executor {
|
|||||||
self.native_page.as_mut().unwrap().dead_cycles = 0;
|
self.native_page.as_mut().unwrap().dead_cycles = 0;
|
||||||
let before = self.statistics_before_shipout(&shipout.box_node, files)?;
|
let before = self.statistics_before_shipout(&shipout.box_node, files)?;
|
||||||
self.shipped_pages += 1;
|
self.shipped_pages += 1;
|
||||||
|
let page_resources = shipout.pdf_objects.map(|objects| objects.resources);
|
||||||
self.events.push(Event::Shipout(Box::new(shipout)));
|
self.events.push(Event::Shipout(Box::new(shipout)));
|
||||||
if probed_page && let Some(probe) = self.pdf_space_probe.as_mut() {
|
if probed_page && let Some(probe) = self.pdf_space_probe.as_mut() {
|
||||||
Arc::make_mut(probe).observed_events = self.events.len();
|
Arc::make_mut(probe).observed_events = self.events.len();
|
||||||
}
|
}
|
||||||
self.write_shipout_forms(forms, files)?;
|
self.write_shipout_forms(forms, files)?;
|
||||||
|
if let Some(resources) = page_resources {
|
||||||
|
self.pack_pdf_object(resources)?;
|
||||||
|
}
|
||||||
self.statistics_after_shipout(before, files)?;
|
self.statistics_after_shipout(before, files)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -697,10 +701,6 @@ impl Executor {
|
|||||||
shipout.pdf_text_spaces.as_mut().unwrap().dedicated_font =
|
shipout.pdf_text_spaces.as_mut().unwrap().dedicated_font =
|
||||||
self.pdf_loaded_space_font.clone();
|
self.pdf_loaded_space_font.clone();
|
||||||
}
|
}
|
||||||
for (number, span) in pdf_objects {
|
|
||||||
self.current = span;
|
|
||||||
self.write_pdf_object(number, files)?;
|
|
||||||
}
|
|
||||||
if has_link_material {
|
if has_link_material {
|
||||||
if for_form {
|
if for_form {
|
||||||
return self.fail("PDF page links and destinations require a page shipout");
|
return self.fail("PDF page links and destinations require a page shipout");
|
||||||
@@ -713,10 +713,15 @@ impl Executor {
|
|||||||
}
|
}
|
||||||
if let Some(objects) = &mut shipout.pdf_objects {
|
if let Some(objects) = &mut shipout.pdf_objects {
|
||||||
let limit = self.limits.tokens;
|
let limit = self.limits.tokens;
|
||||||
|
let compression = device.pdf.as_ref().unwrap().file.object_compression;
|
||||||
objects.parent = self.state.pdf_objects.as_deref_mut().expect("allocated PDF page")
|
objects.parent = self.state.pdf_objects.as_deref_mut().expect("allocated PDF page")
|
||||||
.finish_page(self.shipped_pages as u32 + 1, limit)
|
.finish_page(self.shipped_pages as u32 + 1, compression, limit)
|
||||||
.map_err(|message| self.error(message, current))?;
|
.map_err(|message| self.error(message, current))?;
|
||||||
}
|
}
|
||||||
|
for (number, span) in pdf_objects {
|
||||||
|
self.current = span;
|
||||||
|
self.write_pdf_object(number, files)?;
|
||||||
|
}
|
||||||
for (image, span) in pdf_images {
|
for (image, span) in pdf_images {
|
||||||
self.current = span;
|
self.current = span;
|
||||||
self.declare_pdf_image(image, files)?;
|
self.declare_pdf_image(image, files)?;
|
||||||
|
|||||||
@@ -116,6 +116,7 @@ impl Executor {
|
|||||||
self.write_shipout_forms(children, files)
|
self.write_shipout_forms(children, files)
|
||||||
})?;
|
})?;
|
||||||
}
|
}
|
||||||
|
self.pack_pdf_object(resource_number)?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -554,7 +554,7 @@ impl Executor {
|
|||||||
{
|
{
|
||||||
self.reads.insert(Dependency::PdfObjects);
|
self.reads.insert(Dependency::PdfObjects);
|
||||||
Some(self.state.pdf_objects.get_or_insert_with(Default::default)
|
Some(self.state.pdf_objects.get_or_insert_with(Default::default)
|
||||||
.reserve_png_auxiliary(is_mask, self.limits.tokens)
|
.reserve_png_auxiliary(is_mask, header.object_compression, self.limits.tokens)
|
||||||
.map_err(|error| self.error(error, self.current))?)
|
.map_err(|error| self.error(error, self.current))?)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
|
|||||||
@@ -121,6 +121,18 @@ impl Executor {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) fn pack_pdf_object(&mut self, number: u32) -> Result<(), Error> {
|
||||||
|
if self.state.input_profile() == InputProfile::TeX8Bit
|
||||||
|
&& self.state.pdf_header_options.is_some_and(|header| header.object_compression > 0)
|
||||||
|
{
|
||||||
|
self.reads.insert(Dependency::PdfObjects);
|
||||||
|
self.state.pdf_objects.as_deref_mut().expect("registered PDF object")
|
||||||
|
.pack_object(number, self.limits.tokens)
|
||||||
|
.map_err(|message| self.error(message, self.current))?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn write_pdf_object(
|
pub(super) fn write_pdf_object(
|
||||||
&mut self,
|
&mut self,
|
||||||
number: u32,
|
number: u32,
|
||||||
@@ -135,6 +147,7 @@ impl Executor {
|
|||||||
.and_then(|objects| objects.unwritten(number))
|
.and_then(|objects| objects.unwritten(number))
|
||||||
.map_err(|error| self.error(error, self.current))?;
|
.map_err(|error| self.error(error, self.current))?;
|
||||||
let Some(object) = object else { return Ok(()) };
|
let Some(object) = object else { return Ok(()) };
|
||||||
|
let direct = matches!(object, ObjectBody::Direct(_) | ObjectBody::File { attributes: None, .. });
|
||||||
let materialized = if let ObjectBody::File {
|
let materialized = if let ObjectBody::File {
|
||||||
attributes,
|
attributes,
|
||||||
name,
|
name,
|
||||||
@@ -169,6 +182,10 @@ impl Executor {
|
|||||||
.as_deref_mut()
|
.as_deref_mut()
|
||||||
.expect("existing object table")
|
.expect("existing object table")
|
||||||
.write(number, materialized, self.limits.tokens)
|
.write(number, materialized, self.limits.tokens)
|
||||||
.map_err(|error| self.error(error, self.current))
|
.map_err(|error| self.error(error, self.current))?;
|
||||||
|
if direct {
|
||||||
|
self.pack_pdf_object(number)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2557,6 +2557,12 @@ fn write_pdf(
|
|||||||
objects[device_objects[&group] as usize - 1] = PNG_GROUP.to_vec();
|
objects[device_objects[&group] as usize - 1] = PNG_GROUP.to_vec();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if let Some(registry) = registry {
|
||||||
|
for stream in registry.object_streams() {
|
||||||
|
objects.push(Vec::new());
|
||||||
|
device_objects.insert(stream.number, objects.len() as u32);
|
||||||
|
}
|
||||||
|
}
|
||||||
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();
|
||||||
@@ -3282,7 +3288,28 @@ fn write_pdf(
|
|||||||
objects.push(dictionary);
|
objects.push(dictionary);
|
||||||
Some(objects.len())
|
Some(objects.len())
|
||||||
};
|
};
|
||||||
return Ok(objects::serialize(&objects, info, &device.file, level.clamp(0, 9) as u8));
|
let packing = if let (Some(registry), Some(resources)) = (registry, remapped.as_ref())
|
||||||
|
&& !registry.object_streams().is_empty()
|
||||||
|
{
|
||||||
|
let physical = |number| {
|
||||||
|
resources.object_numbers.get(&number).map(|&id| id as usize)
|
||||||
|
.ok_or_else(|| format!("missing PDF object stream allocation for {number}"))
|
||||||
|
};
|
||||||
|
let streams = registry.object_streams().iter().map(|stream| {
|
||||||
|
let members = stream.members.iter().copied().map(physical)
|
||||||
|
.collect::<Result<Vec<_>, _>>()?;
|
||||||
|
Ok::<_, String>((physical(stream.number)?, members))
|
||||||
|
}).collect::<Result<Vec<_>, _>>()?;
|
||||||
|
let uncompressed = if device.file.object_compression < 2 {
|
||||||
|
registry.written_png_group().map(physical).transpose()?
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
Some(objects::ObjectPacking { streams, uncompressed })
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
return objects::serialize(&objects, info, &device.file, level.clamp(0, 9) as u8, packing);
|
||||||
}
|
}
|
||||||
|
|
||||||
let info_ref = match metadata_object(metadata) {
|
let info_ref = match metadata_object(metadata) {
|
||||||
|
|||||||
@@ -35,6 +35,7 @@ pub(crate) enum ObjectBody {
|
|||||||
name: String,
|
name: String,
|
||||||
from: String,
|
from: String,
|
||||||
},
|
},
|
||||||
|
ObjectStream,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ObjectBody {
|
impl ObjectBody {
|
||||||
@@ -42,7 +43,8 @@ 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::PngGroup | Self::PngAuxiliary | Self::DiscardedAtDump => 0,
|
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
|
||||||
|
| 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 {
|
||||||
@@ -61,7 +63,7 @@ impl ObjectBody {
|
|||||||
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::Image(_) | Self::Font(_) | Self::PageResources | Self::PageContents
|
||||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary => {
|
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream => {
|
||||||
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()),
|
||||||
@@ -89,6 +91,13 @@ pub(crate) struct PageObjects {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub(crate) const PAGE_TREE_FANOUT: u32 = 6;
|
pub(crate) const PAGE_TREE_FANOUT: u32 = 6;
|
||||||
|
pub(crate) const OBJECT_STREAM_CAPACITY: usize = 100;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub(crate) struct PdfObjectStream {
|
||||||
|
pub number: u32,
|
||||||
|
pub members: Vec<u32>,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||||
pub struct PdfObjects {
|
pub struct PdfObjects {
|
||||||
@@ -110,6 +119,10 @@ pub struct PdfObjects {
|
|||||||
png_group: Option<u32>,
|
png_group: Option<u32>,
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
written_png_group: Option<u32>,
|
written_png_group: Option<u32>,
|
||||||
|
// A new format job keeps the allocated numbers but never carries the
|
||||||
|
// previous output file's pending stream or its cross references.
|
||||||
|
#[serde(skip)]
|
||||||
|
object_streams: Vec<Arc<PdfObjectStream>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PdfObjects {
|
impl PdfObjects {
|
||||||
@@ -142,6 +155,19 @@ impl PdfObjects {
|
|||||||
Ok(self.values.len() as u32)
|
Ok(self.values.len() as u32)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn pack_object(&mut self, member: u32, limit: usize) -> Result<(), String> {
|
||||||
|
if self.object_streams.last().is_none_or(|stream| stream.members.len() == OBJECT_STREAM_CAPACITY) {
|
||||||
|
let number = self.allocate(Some(Arc::new(ObjectBody::ObjectStream)), limit)?;
|
||||||
|
self.object_streams.push(Arc::new(PdfObjectStream { number, members: Vec::new() }));
|
||||||
|
}
|
||||||
|
Arc::make_mut(self.object_streams.last_mut().unwrap()).members.push(member);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn object_streams(&self) -> &[Arc<PdfObjectStream>] {
|
||||||
|
&self.object_streams
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn reserve(&mut self, limit: usize) -> Result<u32, String> {
|
pub(crate) fn reserve(&mut self, limit: usize) -> Result<u32, String> {
|
||||||
let number = self.allocate(None, limit)?;
|
let number = self.allocate(None, limit)?;
|
||||||
self.last = number as i32;
|
self.last = number as i32;
|
||||||
@@ -206,10 +232,15 @@ impl PdfObjects {
|
|||||||
matches!(self.entry(number).and_then(Option::as_deref), Some(ObjectBody::PngGroup))
|
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> {
|
pub(crate) fn reserve_png_auxiliary(
|
||||||
|
&mut self, mask: bool, object_compression: u8, limit: usize,
|
||||||
|
) -> Result<u32, String> {
|
||||||
let number = self.allocate(Some(Arc::new(ObjectBody::PngAuxiliary)), limit)?;
|
let number = self.allocate(Some(Arc::new(ObjectBody::PngAuxiliary)), limit)?;
|
||||||
if mask {
|
if mask && self.written_png_group.is_none() && let Some(group) = self.png_group {
|
||||||
self.written_png_group = self.png_group;
|
if object_compression >= 2 {
|
||||||
|
self.pack_object(group, limit)?;
|
||||||
|
}
|
||||||
|
self.written_png_group = Some(group);
|
||||||
}
|
}
|
||||||
Ok(number)
|
Ok(number)
|
||||||
}
|
}
|
||||||
@@ -254,7 +285,12 @@ impl PdfObjects {
|
|||||||
Ok(PageObjects { resources, contents, parent: 0, png_group: None })
|
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, object_compression: u8, limit: usize,
|
||||||
|
) -> Result<u32, String> {
|
||||||
|
if object_compression > 0 {
|
||||||
|
self.pack_object(self.page_references[&page], limit)?;
|
||||||
|
}
|
||||||
if (page - 1) % PAGE_TREE_FANOUT == 0 {
|
if (page - 1) % PAGE_TREE_FANOUT == 0 {
|
||||||
self.page_parent = Some(self.allocate(Some(Arc::new(ObjectBody::Pages)), limit)?);
|
self.page_parent = Some(self.allocate(Some(Arc::new(ObjectBody::Pages)), limit)?);
|
||||||
}
|
}
|
||||||
@@ -287,7 +323,7 @@ impl PdfObjects {
|
|||||||
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::PngAuxiliary | ObjectBody::ObjectStream) => {
|
||||||
ObjectBody::DiscardedAtDump
|
ObjectBody::DiscardedAtDump
|
||||||
}
|
}
|
||||||
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
||||||
@@ -304,6 +340,7 @@ impl PdfObjects {
|
|||||||
self.scalable_fonts.clear();
|
self.scalable_fonts.clear();
|
||||||
self.png_group = None;
|
self.png_group = None;
|
||||||
self.written_png_group = None;
|
self.written_png_group = None;
|
||||||
|
self.object_streams.clear();
|
||||||
!self.values.is_empty()
|
!self.values.is_empty()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -761,7 +798,7 @@ impl ResourceOutput {
|
|||||||
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),
|
|| matches!(objects.entry(number).and_then(Option::as_deref),
|
||||||
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary))
|
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream))
|
||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//! PDF streams, object streams and cross-reference serialization.
|
//! PDF streams, object streams and cross-reference serialization.
|
||||||
use crate::pdf_device::PdfFileOptions;
|
use crate::pdf_device::{PdfFileOptions, page_resources::OBJECT_STREAM_CAPACITY};
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
|
|
||||||
pub(crate) fn stream(extra: &str, data: &[u8], level: u8) -> Vec<u8> {
|
pub(crate) fn stream(extra: &str, data: &[u8], level: u8) -> Vec<u8> {
|
||||||
@@ -29,44 +29,87 @@ pub(crate) fn stream_bytes(extra: &[u8], data: &[u8], level: u8) -> Vec<u8> {
|
|||||||
result
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(super) struct ObjectPacking {
|
||||||
|
pub streams: Vec<(usize, Vec<usize>)>,
|
||||||
|
pub uncompressed: Option<usize>,
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) fn serialize(
|
pub(super) fn serialize(
|
||||||
objects: &[Vec<u8>],
|
objects: &[Vec<u8>],
|
||||||
info: Option<usize>,
|
info: Option<usize>,
|
||||||
options: &PdfFileOptions,
|
options: &PdfFileOptions,
|
||||||
compression: u8,
|
compression: u8,
|
||||||
) -> Vec<u8> {
|
packing: Option<ObjectPacking>,
|
||||||
|
) -> Result<Vec<u8>, String> {
|
||||||
let mut pdf = format!("%PDF-{}.{}\n", options.major, options.minor).into_bytes();
|
let mut pdf = format!("%PDF-{}.{}\n", options.major, options.minor).into_bytes();
|
||||||
let mut offsets = vec![0u64; objects.len() + 1];
|
|
||||||
let mut packed = vec![None; objects.len() + 1];
|
let mut packed = vec![None; objects.len() + 1];
|
||||||
|
let mut stream_slots = vec![false; objects.len() + 1];
|
||||||
|
let mut next_stream = objects.len() + 1;
|
||||||
|
let execution_order = packing.is_some();
|
||||||
|
let ObjectPacking { streams: mut groups, uncompressed } = packing.unwrap_or_default();
|
||||||
|
for (id, members) in &groups {
|
||||||
|
if *id == 0 || *id > objects.len() || !objects[*id - 1].is_empty()
|
||||||
|
|| std::mem::replace(&mut stream_slots[*id], true)
|
||||||
|
|| members.is_empty() || members.len() > OBJECT_STREAM_CAPACITY
|
||||||
|
|| options.object_compression == 0
|
||||||
|
{
|
||||||
|
return Err("invalid native PDF object stream slot".into());
|
||||||
|
}
|
||||||
|
for (index, &member) in members.iter().enumerate() {
|
||||||
|
if member == 0 || member > objects.len() || objects[member - 1].is_empty()
|
||||||
|
|| is_pdf_stream(&objects[member - 1])
|
||||||
|
|| packed[member].replace((*id, index)).is_some()
|
||||||
|
{
|
||||||
|
return Err("invalid native PDF object stream member".into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if options.object_compression > 0 {
|
||||||
|
// The page tree precedes the catalog. Info, when eligible, is last.
|
||||||
|
let document_tail = [Some(2), Some(1), info];
|
||||||
|
let order = (1..=objects.len())
|
||||||
|
.filter(|id| !execution_order || !document_tail.contains(&Some(*id)))
|
||||||
|
.chain(document_tail.into_iter().flatten().filter(|_| execution_order));
|
||||||
|
for id in order {
|
||||||
|
let body = &objects[id - 1];
|
||||||
|
if body.is_empty() || packed[id].is_some() || Some(id) == uncompressed
|
||||||
|
|| is_pdf_stream(body)
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let level = if Some(id) == info {
|
||||||
|
3
|
||||||
|
} else if body.windows(19).any(|s| s == b"/Subtype /TrueType ")
|
||||||
|
|| body.windows(13).any(|s| s == b"/CIDFontType2")
|
||||||
|
{
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
};
|
||||||
|
if options.object_compression < level {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if groups.last().is_none_or(|(_, members)| members.len() == OBJECT_STREAM_CAPACITY) {
|
||||||
|
groups.push((next_stream, Vec::new()));
|
||||||
|
next_stream += 1;
|
||||||
|
}
|
||||||
|
let (stream, members) = groups.last_mut().unwrap();
|
||||||
|
packed[id] = Some((*stream, members.len()));
|
||||||
|
members.push(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut offsets = vec![0u64; next_stream];
|
||||||
let mut free = vec![None; objects.len() + 1];
|
let mut free = vec![None; objects.len() + 1];
|
||||||
let mut last_free = 0;
|
let mut last_free = 0;
|
||||||
let mut groups: Vec<Vec<usize>> = Vec::new();
|
|
||||||
for (i, body) in objects.iter().enumerate() {
|
for (i, body) in objects.iter().enumerate() {
|
||||||
let id = i + 1;
|
let id = i + 1;
|
||||||
|
if stream_slots[id] || packed[id].is_some() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if body.is_empty() {
|
if body.is_empty() {
|
||||||
free[last_free] = Some(id);
|
free[last_free] = Some(id);
|
||||||
last_free = id;
|
last_free = id;
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let level = if Some(id) == info {
|
|
||||||
3
|
|
||||||
} else if body.windows(19).any(|s| s == b"/Subtype /TrueType ")
|
|
||||||
|| body.windows(13).any(|s| s == b"/CIDFontType2")
|
|
||||||
{
|
|
||||||
2
|
|
||||||
} else {
|
|
||||||
1
|
|
||||||
};
|
|
||||||
let eligible =
|
|
||||||
options.object_compression >= level && !body.windows(8).any(|w| w == b"\nstream\n");
|
|
||||||
if eligible {
|
|
||||||
if groups.last().is_none_or(|v| v.len() == 100) {
|
|
||||||
groups.push(Vec::new());
|
|
||||||
}
|
|
||||||
let group = groups.len() - 1;
|
|
||||||
let index = groups[group].len();
|
|
||||||
groups[group].push(id);
|
|
||||||
packed[id] = Some((objects.len() + 1 + group, index));
|
|
||||||
} else {
|
} else {
|
||||||
offsets[id] = pdf.len() as u64;
|
offsets[id] = pdf.len() as u64;
|
||||||
pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes());
|
pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes());
|
||||||
@@ -75,12 +118,11 @@ pub(super) fn serialize(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
free[last_free] = Some(0);
|
free[last_free] = Some(0);
|
||||||
for (i, ids) in groups.iter().enumerate() {
|
for (id, ids) in groups {
|
||||||
let id = objects.len() + 1 + i;
|
offsets[id] = pdf.len() as u64;
|
||||||
offsets.push(pdf.len() as u64);
|
|
||||||
let mut header = String::new();
|
let mut header = String::new();
|
||||||
let mut body = Vec::new();
|
let mut body = Vec::new();
|
||||||
for obj in ids {
|
for obj in &ids {
|
||||||
header.push_str(&format!("{obj} {} ", body.len()));
|
header.push_str(&format!("{obj} {} ", body.len()));
|
||||||
body.extend_from_slice(&objects[*obj - 1]);
|
body.extend_from_slice(&objects[*obj - 1]);
|
||||||
body.push(b'\n');
|
body.push(b'\n');
|
||||||
@@ -145,5 +187,9 @@ pub(super) fn serialize(
|
|||||||
pdf.extend(object);
|
pdf.extend(object);
|
||||||
pdf.extend_from_slice(format!("\nendobj\nstartxref\n{xref}\n%%EOF\n").as_bytes());
|
pdf.extend_from_slice(format!("\nendobj\nstartxref\n{xref}\n%%EOF\n").as_bytes());
|
||||||
}
|
}
|
||||||
pdf
|
Ok(pdf)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_pdf_stream(body: &[u8]) -> bool {
|
||||||
|
body.windows(8).any(|window| window == b"\nstream\n")
|
||||||
}
|
}
|
||||||
@@ -894,6 +894,31 @@ target/p3-pdf-object-streams/comparison.json。另有三组对照保存在
|
|||||||
同目录的 header-lifetime.json,覆盖实际写出冻结压缩级别及草稿
|
同目录的 header-lifetime.json,覆盖实际写出冻结压缩级别及草稿
|
||||||
模式关闭对象流。原生仍缺少 pdfdraftmode 原语。
|
模式关闭对象流。原生仍缺少 pdfdraftmode 原语。
|
||||||
|
|
||||||
|
### pdfTeX 在实际写出时分配压缩对象流
|
||||||
|
|
||||||
|
即时和延迟写出的直接对象、页面字典、页面与 Form 的资源
|
||||||
|
字典以及 PNG 透明组进入实际写入顺序。首次写入合资格对象时
|
||||||
|
分配主对象表中的流编号,每个流容纳 100 项。序列化使用
|
||||||
|
执行时记录的成员顺序生成对象流和 XRef,可从 PDF 用户对象
|
||||||
|
映射至实际流。页面内容及独立资源流保持直接写出。会话检查点
|
||||||
|
共享已经记录的流,恢复时保留待写流的成员。格式重载保留原作业
|
||||||
|
已用的编号,并从新输出流开始。
|
||||||
|
[上游流分配与成员登记](https://github.com/TeX-Live/texlive-source/blob/fb6158926661cb7a7246b3a94a0cb170a9624d5a/texk/web2c/pdftexdir/pdftex.web#L15612-L15658)
|
||||||
|
|
||||||
|
十三页与 pdfTeX 逐像素一致,逐项核对 464 个压缩 XRef 条目。
|
||||||
|
覆盖 PDF 1.4 禁用压缩、压缩级别 0–3、105 个即时对象、
|
||||||
|
跨流发页、Form、PNG 透明组及 schema89 转储和重载。十九项
|
||||||
|
设备、图像、链接定向回归通过。跨文件修改使对象流在不同位置
|
||||||
|
滚动,恢复检查点后只更新第二页,PDF、SVG 和来源映射与独立
|
||||||
|
全量一致。第一版的文字回归失败和无效流结构保留在
|
||||||
|
target/p3-pdf-object-streams/first-candidate。最终回执 SHA-256
|
||||||
|
为 7649106cbb1f9ccab4cfe6f840c1fedc2d3e2dd603c932d246a847f00b34944c。
|
||||||
|
|
||||||
|
仍需按同一对象机制接入出页链接、命名目标及相关的写出次序。
|
||||||
|
命名目标缺少实际发页登记的案例在 next-destination。另有
|
||||||
|
next-raw-options 重现通用 PDF 对象在展开主体时与页面分配
|
||||||
|
顺序相反。pdfdraftmode 原语尚未接入。
|
||||||
|
|
||||||
### PDF 预览按实际页面资源复用
|
### PDF 预览按实际页面资源复用
|
||||||
|
|
||||||
编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。
|
编译会话的 SVG 缓存采用预览读取器解析出的页面、有效页框、旋转和资源。
|
||||||
|
|||||||
@@ -82,6 +82,117 @@ fn reproducible_pdf_dates_keep_register_policy_and_reject_invalid_epochs() {
|
|||||||
fs::remove_dir_all(p).unwrap();
|
fs::remove_dir_all(p).unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn compressed_page_fills_pending_object_stream_before_deferred_resources() {
|
||||||
|
let p = directory();
|
||||||
|
let source = r"\catcode123=1 \catcode125=2 \catcode35=6
|
||||||
|
\pdfoutput=1 \pdfminorversion=5 \pdfcompresslevel=0 \pdfobjcompresslevel=1
|
||||||
|
\count1=0
|
||||||
|
\def\burst{\advance\count1 by1
|
||||||
|
\immediate\pdfobj{\the\count1}%
|
||||||
|
\ifnum\count1<99 \expandafter\burst\fi}
|
||||||
|
\burst \message{BURST=\the\pdflastobj;}
|
||||||
|
\pdfobj{<< /Probe /Deferred /PriorStream 2 0 R >>}\count0=\pdflastobj
|
||||||
|
\shipout\hbox{\pdfrefobj\count0\vrule width2pt height2pt depth0pt}
|
||||||
|
\pdfobj reserveobjnum \message{AFTER=\the\pdflastobj;}
|
||||||
|
\end";
|
||||||
|
fs::write(p.join("probe.tex"), source).unwrap();
|
||||||
|
let run = native_fonts::command()
|
||||||
|
.args(["native", "--job", "--initex", "--etex", "probe.tex", "probe.pdf"])
|
||||||
|
.current_dir(&p)
|
||||||
|
.output()
|
||||||
|
.unwrap();
|
||||||
|
assert!(run.status.success(), "{}", String::from_utf8_lossy(&run.stderr));
|
||||||
|
let log = fs::read_to_string(p.join("probe.log")).unwrap();
|
||||||
|
assert!(log.contains("BURST=100;") && log.contains("AFTER=107;"), "{log}");
|
||||||
|
|
||||||
|
let pdf = lopdf::Document::load(p.join("probe.pdf")).unwrap();
|
||||||
|
let (late, reference) = pdf.objects.iter().find_map(|(id, value)| {
|
||||||
|
let dict = value.as_dict().ok()?;
|
||||||
|
(dict.get(b"Probe").ok()?.as_name().ok()? == b"Deferred")
|
||||||
|
.then(|| (*id, dict.get(b"PriorStream").unwrap().as_reference().unwrap()))
|
||||||
|
}).unwrap();
|
||||||
|
let members = |stream: &lopdf::Stream| {
|
||||||
|
let first = stream.dict.get(b"First").unwrap().as_i64().unwrap() as usize;
|
||||||
|
std::str::from_utf8(&stream.content[..first]).unwrap().split_ascii_whitespace()
|
||||||
|
.step_by(2).map(|id| id.parse::<u32>().unwrap()).collect::<Vec<_>>()
|
||||||
|
};
|
||||||
|
let first = pdf.get_object(reference).unwrap().as_stream().unwrap();
|
||||||
|
assert!(first.dict.type_is(b"ObjStm"));
|
||||||
|
let first_members = members(first);
|
||||||
|
assert_eq!(first_members.len(), 100);
|
||||||
|
assert_eq!(first_members[99], pdf.get_pages()[&1].0);
|
||||||
|
let second = pdf.objects.iter().find_map(|(id, object)| {
|
||||||
|
let stream = object.as_stream().ok()?;
|
||||||
|
(*id != reference && stream.dict.type_is(b"ObjStm")).then_some(stream)
|
||||||
|
}).unwrap();
|
||||||
|
assert_eq!(members(second).first(), Some(&late.0));
|
||||||
|
assert!(pdf.reference_table.get(late.0).unwrap().is_compressed());
|
||||||
|
fs::remove_dir_all(p).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn checkpoint_resumes_open_object_stream_when_only_the_second_page_changes() {
|
||||||
|
use std::sync::Arc;
|
||||||
|
use texrra_engine::native::{
|
||||||
|
CompileRequest, Entry, NativeCompiler, ProjectDefinition, ProjectSnapshot,
|
||||||
|
};
|
||||||
|
use texrra_tex_core::{execution::JobTime, resources::WorldConfig};
|
||||||
|
|
||||||
|
let root = directory();
|
||||||
|
let entry = root.join("probe.tex");
|
||||||
|
let second = root.join("second.tex");
|
||||||
|
let configuration = WorldConfig::new(&root);
|
||||||
|
let mut source = r"\catcode123=1 \catcode125=2 \catcode35=6
|
||||||
|
\pdfoutput=1 \pdfminorversion=5 \pdfcompresslevel=6 \pdfobjcompresslevel=1
|
||||||
|
\pdfpagewidth=100pt \pdfpageheight=100pt \pdfhorigin=8pt \pdfvorigin=8pt
|
||||||
|
\shipout\hbox{\vrule width8pt height8pt depth0pt}
|
||||||
|
\count1=0
|
||||||
|
\def\burst{\advance\count1 by1
|
||||||
|
\immediate\pdfobj{\the\count1}%
|
||||||
|
\ifnum\count1<96 \expandafter\burst\fi}
|
||||||
|
\burst
|
||||||
|
".to_owned();
|
||||||
|
let line = format!("{}\n", "\\relax ".repeat(26));
|
||||||
|
source.push_str(&line.repeat(40));
|
||||||
|
source.push_str("\\input second.tex\n\\end\n");
|
||||||
|
let original = br"\immediate\pdfobj{150}\immediate\pdfobj{151}
|
||||||
|
\shipout\hbox{\vrule width4pt height5pt depth0pt}";
|
||||||
|
let modified = br"\immediate\pdfobj{150}
|
||||||
|
\shipout\hbox{\vrule width8pt height5pt depth0pt}";
|
||||||
|
let project = ProjectSnapshot::new(ProjectDefinition {
|
||||||
|
configuration: configuration.clone(),
|
||||||
|
revision: 1,
|
||||||
|
roots: [root.clone()].into(),
|
||||||
|
files: [
|
||||||
|
(entry.clone(), Arc::<[u8]>::from(source.into_bytes())),
|
||||||
|
(second.clone(), Arc::from(original.as_slice())),
|
||||||
|
].into(),
|
||||||
|
directories: Default::default(),
|
||||||
|
aliases: Default::default(),
|
||||||
|
generated_roots: [root.clone()].into(),
|
||||||
|
generated: Default::default(),
|
||||||
|
}).unwrap();
|
||||||
|
let updated = project.with_file_edits(2, [(second, Arc::from(modified.as_slice()))].into()).unwrap();
|
||||||
|
let time = JobTime::new(2026, 11, 27, 600).unwrap().with_pdf_clock(0, 0).unwrap();
|
||||||
|
let mut request = CompileRequest::new(configuration, entry, "probe.pdf", time);
|
||||||
|
request.entry = Entry::Initex;
|
||||||
|
request.etex = true;
|
||||||
|
let live = NativeCompiler::default().with_automatic_entry_checkpoints();
|
||||||
|
let first = live.compile(request.clone().with_project(project)).unwrap();
|
||||||
|
let next = live.compile(request.clone().with_project(updated.clone())).unwrap();
|
||||||
|
let cold = NativeCompiler::default().compile(request.with_project(updated)).unwrap();
|
||||||
|
assert!(next.entry_checkpoint_work.reused_steps > 0);
|
||||||
|
assert_ne!(first.pdf, next.pdf);
|
||||||
|
assert_eq!(next.pdf, cold.pdf);
|
||||||
|
assert_eq!(next.source_map.pages, cold.source_map.pages);
|
||||||
|
assert_eq!(next.preview_since(None).unwrap().pages, cold.preview_since(None).unwrap().pages);
|
||||||
|
let patch = next.preview_since(Some(first.revision())).unwrap();
|
||||||
|
assert_eq!(patch.base_revision, Some(first.revision()));
|
||||||
|
assert_eq!(patch.pages.iter().map(|page| page.index).collect::<Vec<_>>(), [1]);
|
||||||
|
fs::remove_dir_all(root).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn actual_compressed_pdf_objects_fonts_pages_and_late_writes_reach_the_cli() {
|
fn actual_compressed_pdf_objects_fonts_pages_and_late_writes_reach_the_cli() {
|
||||||
let p = directory();
|
let p = directory();
|
||||||
|
|||||||
Reference in new issue
Block a user