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;
|
||||
let before = self.statistics_before_shipout(&shipout.box_node, files)?;
|
||||
self.shipped_pages += 1;
|
||||
let page_resources = shipout.pdf_objects.map(|objects| objects.resources);
|
||||
self.events.push(Event::Shipout(Box::new(shipout)));
|
||||
if probed_page && let Some(probe) = self.pdf_space_probe.as_mut() {
|
||||
Arc::make_mut(probe).observed_events = self.events.len();
|
||||
}
|
||||
self.write_shipout_forms(forms, files)?;
|
||||
if let Some(resources) = page_resources {
|
||||
self.pack_pdf_object(resources)?;
|
||||
}
|
||||
self.statistics_after_shipout(before, files)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -697,10 +701,6 @@ impl Executor {
|
||||
shipout.pdf_text_spaces.as_mut().unwrap().dedicated_font =
|
||||
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 for_form {
|
||||
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 {
|
||||
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")
|
||||
.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))?;
|
||||
}
|
||||
for (number, span) in pdf_objects {
|
||||
self.current = span;
|
||||
self.write_pdf_object(number, files)?;
|
||||
}
|
||||
for (image, span) in pdf_images {
|
||||
self.current = span;
|
||||
self.declare_pdf_image(image, files)?;
|
||||
|
||||
@@ -116,6 +116,7 @@ impl Executor {
|
||||
self.write_shipout_forms(children, files)
|
||||
})?;
|
||||
}
|
||||
self.pack_pdf_object(resource_number)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -554,7 +554,7 @@ impl Executor {
|
||||
{
|
||||
self.reads.insert(Dependency::PdfObjects);
|
||||
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))?)
|
||||
} else {
|
||||
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(
|
||||
&mut self,
|
||||
number: u32,
|
||||
@@ -135,6 +147,7 @@ impl Executor {
|
||||
.and_then(|objects| objects.unwritten(number))
|
||||
.map_err(|error| self.error(error, self.current))?;
|
||||
let Some(object) = object else { return Ok(()) };
|
||||
let direct = matches!(object, ObjectBody::Direct(_) | ObjectBody::File { attributes: None, .. });
|
||||
let materialized = if let ObjectBody::File {
|
||||
attributes,
|
||||
name,
|
||||
@@ -169,6 +182,10 @@ impl Executor {
|
||||
.as_deref_mut()
|
||||
.expect("existing object table")
|
||||
.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();
|
||||
}
|
||||
}
|
||||
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| {
|
||||
page.pdf_resources.objects.map(|allocation| allocation.parent)
|
||||
}).collect();
|
||||
@@ -3282,7 +3288,28 @@ fn write_pdf(
|
||||
objects.push(dictionary);
|
||||
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) {
|
||||
|
||||
@@ -35,6 +35,7 @@ pub(crate) enum ObjectBody {
|
||||
name: String,
|
||||
from: String,
|
||||
},
|
||||
ObjectStream,
|
||||
}
|
||||
|
||||
impl ObjectBody {
|
||||
@@ -42,7 +43,8 @@ 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::PngGroup | Self::PngAuxiliary | Self::DiscardedAtDump => 0,
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream
|
||||
| Self::DiscardedAtDump => 0,
|
||||
Self::Direct(bytes) => bytes.len(),
|
||||
Self::Stream { attributes, bytes } => attributes.len().saturating_add(bytes.len()),
|
||||
Self::File {
|
||||
@@ -61,7 +63,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::PngGroup | Self::PngAuxiliary => {
|
||||
| Self::Pages | Self::PngGroup | Self::PngAuxiliary | Self::ObjectStream => {
|
||||
Err("expected a generic native PDF object".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 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)]
|
||||
pub struct PdfObjects {
|
||||
@@ -110,6 +119,10 @@ pub struct PdfObjects {
|
||||
png_group: Option<u32>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
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 {
|
||||
@@ -142,6 +155,19 @@ impl PdfObjects {
|
||||
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> {
|
||||
let number = self.allocate(None, limit)?;
|
||||
self.last = number as i32;
|
||||
@@ -206,10 +232,15 @@ impl PdfObjects {
|
||||
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)?;
|
||||
if mask {
|
||||
self.written_png_group = self.png_group;
|
||||
if mask && self.written_png_group.is_none() && let Some(group) = self.png_group {
|
||||
if object_compression >= 2 {
|
||||
self.pack_object(group, limit)?;
|
||||
}
|
||||
self.written_png_group = Some(group);
|
||||
}
|
||||
Ok(number)
|
||||
}
|
||||
@@ -254,7 +285,12 @@ impl PdfObjects {
|
||||
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 {
|
||||
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::Page | ObjectBody::FormResources | ObjectBody::PageResources
|
||||
| ObjectBody::PageContents | ObjectBody::Pages | ObjectBody::Font(_)
|
||||
| ObjectBody::PngAuxiliary) => {
|
||||
| ObjectBody::PngAuxiliary | ObjectBody::ObjectStream) => {
|
||||
ObjectBody::DiscardedAtDump
|
||||
}
|
||||
_ if self.written.contains(&number) => ObjectBody::DiscardedAtDump,
|
||||
@@ -304,6 +340,7 @@ impl PdfObjects {
|
||||
self.scalable_fonts.clear();
|
||||
self.png_group = None;
|
||||
self.written_png_group = None;
|
||||
self.object_streams.clear();
|
||||
!self.values.is_empty()
|
||||
}
|
||||
|
||||
@@ -761,7 +798,7 @@ impl ResourceOutput {
|
||||
if values.contains_key(&number) || page_objects.contains(&number)
|
||||
|| device_objects.contains(&number) || objects.font_owner(number).is_some()
|
||||
|| matches!(objects.entry(number).and_then(Option::as_deref),
|
||||
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary))
|
||||
Some(ObjectBody::PngGroup | ObjectBody::PngAuxiliary | ObjectBody::ObjectStream))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! 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;
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct ObjectPacking {
|
||||
pub streams: Vec<(usize, Vec<usize>)>,
|
||||
pub uncompressed: Option<usize>,
|
||||
}
|
||||
|
||||
pub(super) fn serialize(
|
||||
objects: &[Vec<u8>],
|
||||
info: Option<usize>,
|
||||
options: &PdfFileOptions,
|
||||
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 offsets = vec![0u64; 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 last_free = 0;
|
||||
let mut groups: Vec<Vec<usize>> = Vec::new();
|
||||
for (i, body) in objects.iter().enumerate() {
|
||||
let id = i + 1;
|
||||
if stream_slots[id] || packed[id].is_some() {
|
||||
continue;
|
||||
}
|
||||
if body.is_empty() {
|
||||
free[last_free] = Some(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 {
|
||||
offsets[id] = pdf.len() as u64;
|
||||
pdf.extend_from_slice(format!("{id} 0 obj\n").as_bytes());
|
||||
@@ -75,12 +118,11 @@ pub(super) fn serialize(
|
||||
}
|
||||
}
|
||||
free[last_free] = Some(0);
|
||||
for (i, ids) in groups.iter().enumerate() {
|
||||
let id = objects.len() + 1 + i;
|
||||
offsets.push(pdf.len() as u64);
|
||||
for (id, ids) in groups {
|
||||
offsets[id] = pdf.len() as u64;
|
||||
let mut header = String::new();
|
||||
let mut body = Vec::new();
|
||||
for obj in ids {
|
||||
for obj in &ids {
|
||||
header.push_str(&format!("{obj} {} ", body.len()));
|
||||
body.extend_from_slice(&objects[*obj - 1]);
|
||||
body.push(b'\n');
|
||||
@@ -145,5 +187,9 @@ pub(super) fn serialize(
|
||||
pdf.extend(object);
|
||||
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")
|
||||
}
|
||||
Reference in new issue
Block a user