Files
texrra-engine/crates/texrra-tex-core/src/pdf_image.rs
T

515 lines
18 KiB
Rust

//! Native image XObjects and the resource objects reachable from their content.
mod jpeg;
use crate::resources::{LoadedResource, ResourceVersion};
use lopdf::{Dictionary, Document, Object, ObjectId};
use std::{
collections::{BTreeMap, BTreeSet},
io::Write,
sync::Arc,
};
#[derive(Clone, Copy, Debug, Default)]
pub(crate) enum PageBox {
Media,
#[default]
Crop,
Bleed,
Trim,
Art,
}
impl PageBox {
fn keys(self) -> &'static [&'static [u8]] {
match self {
Self::Media => &[b"MediaBox"],
Self::Crop => &[b"CropBox", b"MediaBox"],
Self::Bleed => &[b"BleedBox", b"CropBox", b"MediaBox"],
Self::Trim => &[b"TrimBox", b"CropBox", b"MediaBox"],
Self::Art => &[b"ArtBox", b"CropBox", b"MediaBox"],
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfImage {
pub version: ResourceVersion,
pub page: usize,
pub page_count: usize,
pub natural: [i64; 2],
extent: [u64; 2],
objects: Vec<Vec<Part>>,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfImageUse {
pub id: usize,
pub image: Arc<PdfImage>,
pub width: i64,
pub height: i64,
pub depth: i64,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct PdfImageObject {
pub image: Arc<PdfImageUse>,
pub attributes: Vec<u8>,
}
impl PdfImageUse {
pub(crate) fn new(
id: usize,
image: PdfImage,
requested: [Option<i32>; 3],
) -> Result<Self, String> {
let [w, h] = image.natural;
let jpeg = image.jpeg_frame().map(|(size, _)| size.map(i64::from));
let [aspect_width, aspect_height] = jpeg.unwrap_or([w, h]);
let [width, height, depth] = requested.map(|value| value.map(i64::from));
let ratio = |value: i64, numerator: i64, denominator: i64| {
let product = value * numerator;
product.signum() * ((product.abs() + denominator / 2) / denominator)
};
let depth = depth.unwrap_or(0);
let (width, height) = match (width, height) {
(None, None) if jpeg.is_some() && requested[2].is_some() => {
(ratio(h, aspect_width, aspect_height), h - depth)
}
(None, None) => (w, h - depth),
(Some(width), None) => (width, ratio(width, aspect_height, aspect_width) - depth),
(None, Some(height)) => (ratio(height + depth, aspect_width, aspect_height), height),
(Some(width), Some(height)) => (width, height),
};
if [width, height, depth].iter().any(|v| v.abs() > 1073741823) {
return Err("native PDF image dimension capacity exceeded".into());
}
Ok(Self {
id,
image: Arc::new(image),
width,
height,
depth,
})
}
pub(crate) fn dimensions(&self) -> (i64, i64, i64) {
(self.width, self.height, self.depth)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
enum Part {
Bytes(Vec<u8>),
Ref(usize),
Jpeg {
size: [u16; 2],
precision: u8,
bytes: Vec<u8>,
},
}
pub(crate) fn real(value: f64) -> String {
let body = format!("{value:.15}");
body.trim_end_matches('0').trim_end_matches('.').to_owned()
}
impl PdfImage {
pub(crate) fn is_jpeg(resource: &LoadedResource) -> bool {
resource.data.starts_with(jpeg::SIGNATURE)
|| (!resource.data.starts_with(b"%PDF-")
&& resource.version.path.extension().is_some_and(|extension| {
extension.eq_ignore_ascii_case("jpg") || extension.eq_ignore_ascii_case("jpeg")
}))
}
pub(crate) fn read_jpeg(
resource: LoadedResource,
fallback_resolution: i32,
pdf_version: (i32, i32),
) -> Result<(Self, Option<&'static str>), String> {
let header = jpeg::read(&resource.data).map_err(|error| {
format!(
"could not parse JPEG image {}: {error}",
resource.version.path.display()
)
})?;
if header.progressive && pdf_version.0 == 1 && pdf_version.1 <= 2 {
return Err("cannot use progressive DCT with PDF-1.2".into());
}
let [width, height] = header.size;
let color = match header.components {
1 => "/DeviceGray",
3 => "/DeviceRGB",
4 => "/DeviceCMYK /Decode [1 0 1 0 1 0 1 0]",
_ => unreachable!("JPEG component count was checked"),
};
let mut density = header.density;
let warning = if density.iter().any(|&dpi| dpi > 65_535) {
Some("too large image resolution ignored")
} else if density != [0, 0] && density.contains(&0) {
Some("too small image resolution ignored")
} else {
None
};
if warning.is_some() || density == [0, 0] {
let default = fallback_resolution.clamp(0, 65_535) as u32;
density = [if default == 0 { 72 } else { default }; 2];
}
let natural = std::array::from_fn(|axis| {
// One hundred inches in TeX scaled points.
let numerator = 473_628_672_i64 * i64::from(header.size[axis]);
let denominator = 100 * i64::from(density[axis]);
(numerator + denominator / 2) / denominator
});
let dictionary = format!(
"/Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace {color} /BitsPerComponent {} /Filter /DCTDecode /Length {} >>\nstream\n",
header.precision,
resource.data.len()
);
Ok((
Self {
version: resource.version,
page: 1,
page_count: 1,
natural,
extent: [1.0_f64.to_bits(); 2],
objects: vec![vec![
Part::Bytes(dictionary.into_bytes()),
Part::Jpeg {
size: header.size,
precision: header.precision,
bytes: resource.data,
},
Part::Bytes(b"\nendstream".to_vec()),
]],
},
warning,
))
}
pub(crate) fn jpeg_frame(&self) -> Option<([u16; 2], u8)> {
self.objects.first()?.iter().find_map(|part| match part {
Part::Jpeg {
size, precision, ..
} => Some((*size, *precision)),
_ => None,
})
}
pub(crate) fn read(
resource: LoadedResource,
page: usize,
kind: PageBox,
) -> Result<Self, String> {
let doc = Document::load_mem(&resource.data).map_err(|error| {
format!(
"could not parse PDF image {}: {error}",
resource.version.path.display()
)
})?;
if doc.trailer.has(b"Encrypt") {
return Err("encrypted PDF image requires a decryption key".into());
}
let pages = doc.get_pages();
let page_id = pages
.get(&u32::try_from(page).map_err(|_| "required page does not exist")?)
.copied()
.ok_or("required page does not exist")?;
let chain = page_chain(&doc, page_id)?;
let inherited = |name: &[u8]| chain.iter().find_map(|dict| dict.get(name).ok());
let bounds = kind
.keys()
.iter()
.find_map(|key| inherited(key))
.ok_or("PDF image has no page bounding box")?;
let bounds = resolved(&doc, bounds)?
.as_array()
.map_err(|error| error.to_string())?;
let [a, b, c, d] = bounds.as_slice() else {
return Err("PDF image bounding box must contain four coordinates".into());
};
let (a, b, c, d) = (
number(&doc, a)?,
number(&doc, b)?,
number(&doc, c)?,
number(&doc, d)?,
);
let [left, bottom, right, top] = [a.min(c), b.min(d), a.max(c), b.max(d)];
let rotation = inherited(b"Rotate")
.map(|rotate| {
resolved(&doc, rotate)?
.as_i64()
.map_err(|error| error.to_string())
})
.transpose()?
.unwrap_or(0)
.rem_euclid(360);
let (matrix, width, height) = match rotation {
0 => (
[1.0, 0.0, 0.0, 1.0, -left, -bottom],
right - left,
top - bottom,
),
90 => (
[0.0, -1.0, 1.0, 0.0, -bottom, right],
top - bottom,
right - left,
),
180 => (
[-1.0, 0.0, 0.0, -1.0, right, top],
right - left,
top - bottom,
),
270 => (
[0.0, 1.0, -1.0, 0.0, top, -left],
top - bottom,
right - left,
),
_ => return Err("PDF image rotation must be a multiple of 90 degrees".into()),
};
let sp = |bp: f64| -> Result<i64, String> {
let value = (bp * 65536.0 * 803.0 / 800.0).round();
if !(1.0..=1073741823.0).contains(&value) {
return Err("invalid image dimensions".into());
}
Ok(value as i64)
};
let natural = [sp(width)?, sp(height)?];
let mut contents = Vec::new();
if let Ok(content) = chain[0].get(b"Contents") {
read_contents(&doc, content, &mut contents, 0)?;
}
let array = |values: &[f64]| {
values
.iter()
.map(|&v| real(v))
.collect::<Vec<_>>()
.join(" ")
};
let mut graph = Graph {
doc: &doc,
ids: BTreeMap::new(),
bodies: vec![Vec::new()],
};
let mut form = Vec::new();
let header = format!(
"/Type /XObject /Subtype /Form /FormType 1 /BBox [{}] /Matrix [{}] /Resources ",
array(&[left, bottom, right, top]),
array(&matrix)
);
form.push(Part::Bytes(header.into_bytes()));
match inherited(b"Resources") {
Some(resources) => graph.render(resources, &mut form, 0)?,
None => form.push(Part::Bytes(b"<<>>".to_vec())),
}
if let Ok(group) = chain[0].get(b"Group") {
form.push(Part::Bytes(b" /Group ".to_vec()));
graph.render(group, &mut form, 0)?;
}
let mut stream = format!(" /Length {} >>\nstream\n", contents.len()).into_bytes();
stream.extend(contents);
stream.extend_from_slice(b"\nendstream");
form.push(Part::Bytes(stream));
graph.bodies[0] = form;
Ok(Self {
version: resource.version,
page,
page_count: pages.len(),
natural,
extent: [width.to_bits(), height.to_bits()],
objects: graph.bodies,
})
}
pub(crate) fn extent(&self) -> [f64; 2] {
self.extent.map(f64::from_bits)
}
pub(crate) fn append_to(&self, pdf: &mut Vec<Vec<u8>>, attributes: &[u8]) -> usize {
let base = pdf.len() + 1;
pdf.extend(self.objects.iter().enumerate().map(|(index, parts)| {
let mut body = Vec::new();
if index == 0 {
body.extend_from_slice(b"<< ");
if !attributes.is_empty() {
body.extend_from_slice(attributes);
body.push(b'\n');
}
}
for part in parts {
match part {
Part::Bytes(bytes) | Part::Jpeg { bytes, .. } => body.extend_from_slice(bytes),
Part::Ref(id) => write!(body, "{} 0 R", base + id).unwrap(),
}
}
body
}));
base
}
}
fn page_chain(doc: &Document, mut id: ObjectId) -> Result<Vec<&Dictionary>, String> {
let mut chain = Vec::new();
let mut seen = BTreeSet::new();
loop {
if chain.len() >= 64 || !seen.insert(id) {
return Err("PDF image page tree is cyclic or too deep".into());
}
let dict = doc.get_dictionary(id).map_err(|error| error.to_string())?;
chain.push(dict);
let Ok(parent) = dict.get(b"Parent") else {
return Ok(chain);
};
id = parent.as_reference().map_err(|error| error.to_string())?;
}
}
fn resolved<'a>(doc: &'a Document, mut object: &'a Object) -> Result<&'a Object, String> {
for _ in 0..64 {
let Object::Reference(id) = object else {
return Ok(object);
};
object = doc.objects.get(id).ok_or("missing object in PDF image")?;
}
Err("PDF image object reference chain is too deep".into())
}
fn number(doc: &Document, object: &Object) -> Result<f64, String> {
let value = match resolved(doc, object)? {
Object::Integer(value) => *value as f64,
Object::Real(value) => *value,
_ => return Err("PDF image bounding box contains a non-numeric value".into()),
};
if !value.is_finite() {
return Err("PDF image bounding box contains a non-finite value".into());
}
Ok(value)
}
fn read_contents(
doc: &Document,
object: &Object,
out: &mut Vec<u8>,
depth: usize,
) -> Result<(), String> {
if depth >= 64 {
return Err("PDF image contents are too deeply nested".into());
}
match resolved(doc, object)? {
Object::Null => {}
Object::Stream(stream) => {
if stream.dict.has(b"Filter") {
out.extend(
stream
.decompressed_content()
.map_err(|error| error.to_string())?,
);
} else {
out.extend_from_slice(&stream.content);
}
out.push(b'\n');
}
Object::Array(items) => {
for item in items {
read_contents(doc, item, out, depth + 1)?;
}
}
_ => return Err("PDF image contents must be a stream or array of streams".into()),
}
Ok(())
}
struct Graph<'a> {
doc: &'a Document,
ids: BTreeMap<ObjectId, usize>,
bodies: Vec<Vec<Part>>,
}
impl Graph<'_> {
fn render(&mut self, value: &Object, out: &mut Vec<Part>, depth: usize) -> Result<(), String> {
if depth >= 128 {
return Err("PDF image resource graph is too deeply nested".into());
}
let bytes = |out: &mut Vec<Part>, bytes: &[u8]| {
if let Some(Part::Bytes(last)) = out.last_mut() {
last.extend_from_slice(bytes);
} else {
out.push(Part::Bytes(bytes.to_vec()));
}
};
match value {
Object::Null => bytes(out, b"null"),
Object::Boolean(true) => bytes(out, b"true"),
Object::Boolean(false) => bytes(out, b"false"),
Object::Integer(n) => bytes(out, n.to_string().as_bytes()),
Object::Real(n) if n.is_finite() => bytes(out, real(*n).as_bytes()),
Object::Real(_) => return Err("non-finite number in PDF image".into()),
Object::Name(name) => {
let mut encoded = vec![b'/'];
for &ch in name {
if (33..=126).contains(&ch) && !b"#%()<>[]{}/".contains(&ch) {
encoded.push(ch);
} else {
write!(encoded, "#{ch:02X}").unwrap();
}
}
bytes(out, &encoded);
}
Object::String(data, _) => {
let mut encoded = vec![b'<'];
for &ch in data {
write!(encoded, "{ch:02X}").unwrap();
}
encoded.push(b'>');
bytes(out, &encoded);
}
Object::Array(values) => {
bytes(out, b"[");
for child in values {
self.render(child, out, depth + 1)?;
bytes(out, b" ");
}
bytes(out, b"]");
}
Object::Dictionary(dict) => {
bytes(out, b"<<");
for (key, child) in dict.iter() {
self.render(&Object::Name(key.clone()), out, depth + 1)?;
bytes(out, b" ");
self.render(child, out, depth + 1)?;
bytes(out, b" ");
}
bytes(out, b">>");
}
Object::Stream(stream) => {
let mut dict = stream.dict.clone();
dict.set("Length", stream.content.len() as i64);
self.render(&Object::Dictionary(dict), out, depth + 1)?;
bytes(out, b"\nstream\n");
bytes(out, &stream.content);
bytes(out, b"\nendstream");
}
Object::Reference(id) => {
let index = match self.ids.get(id) {
Some(index) => *index,
None => {
let new_index = self.bodies.len();
self.ids.insert(*id, new_index);
self.bodies.push(Vec::new());
let mut body = Vec::new();
let object = self
.doc
.objects
.get(id)
.ok_or("missing resource object in PDF image")?;
self.render(object, &mut body, depth + 1)?;
self.bodies[new_index] = body;
new_index
}
};
out.push(Part::Ref(index));
}
}
Ok(())
}
}