//! Decode PNG samples for native PDF image XObjects. use super::{Part, PdfImage, PdfImageTargets, RasterProcSet}; use crate::{pdf::objects, resources::LoadedResource}; use ::png::{ColorType, Decoder, PixelDimensions, Transformations, Unit}; use serde::{Deserialize, Serialize}; use std::{fmt::Write, io::Cursor}; pub(super) const SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n"; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] enum ColorSpace { Gray, Rgb, Indexed(Vec), } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub(super) struct SampledImage { pub(super) size: [u32; 2], 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, alpha: Vec, } pub(super) fn decode(bytes: &[u8]) -> Result<(SampledImage, Option), String> { let read_info = |transforms| { let mut decoder = Decoder::new(Cursor::new(bytes)); decoder.set_transformations(transforms); decoder.set_ignore_text_chunk(true); decoder.read_info().map_err(|error| error.to_string()) }; let mut reader = read_info(Transformations::IDENTITY)?; 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)?; } let info = reader.info(); let physical = info .pixel_dims .filter(|physical| physical.unit == Unit::Meter); let palette = info.palette.clone(); let capacity = reader .output_buffer_size() .ok_or("PNG dimensions exceed decoder capacity")?; // The decoder limits its own scratch allocations. Its caller-provided // output buffer also needs a bound before allocating decompressed pixels. if capacity > 256 * 1024 * 1024 { return Err("decoded PNG exceeds native image capacity".into()); } let mut buf = vec![0; capacity]; let info = reader .next_frame(&mut buf) .map_err(|error| error.to_string())?; if [info.width, info.height] != [width, height] { return Err("PNG default frame dimensions differ from IHDR".into()); } buf.truncate(info.buffer_size()); reader.finish().map_err(|error| error.to_string())?; let color = match info.color_type { ColorType::Grayscale | ColorType::GrayscaleAlpha => ColorSpace::Gray, ColorType::Rgb | ColorType::Rgba => ColorSpace::Rgb, ColorType::Indexed => { let table = palette.ok_or("indexed PNG has no palette")?; if !(3..=768).contains(&table.len()) || table.len() % 3 != 0 { return Err("invalid indexed PNG palette".into()); } ColorSpace::Indexed(table.into_owned()) } }; let depth = info.bit_depth as u8; let mut alpha = Vec::new(); if matches!(info.color_type, ColorType::GrayscaleAlpha | ColorType::Rgba) { let sample = usize::from(depth / 8); let stride = sample * info.color_type.samples(); let color_bytes = stride - sample; alpha.reserve(buf.len() / stride); for offset in (0..buf.len()).step_by(stride) { let start = offset / stride * color_bytes; // PDF's soft mask uses the high byte even for 16-bit PNG color. alpha.push(buf[offset + color_bytes]); buf.copy_within(offset..offset + color_bytes, start); } buf.truncate(alpha.len() * color_bytes); } Ok(( SampledImage { size: [width, height], source_depth, source_indexed, source_alpha, depth, color, samples: buf, alpha, }, physical, )) } pub(super) fn read( resource: LoadedResource, fallback_resolution: i32, color_space: Option, ) -> Result<(PdfImage, Option<&'static str>), String> { let (image, physical) = decode(&resource.data).map_err(|error| { format!( "could not parse PNG image {}: {error}", resource.version.path.display() ) })?; let mut density = physical.map_or([0, 0], |physical| { [physical.xppu, physical.yppu].map(|px| ((u64::from(px) * 254 + 5_000) / 10_000) as u32) }); 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 resolution = fallback_resolution.clamp(0, 65_535) as u32; density = [if resolution == 0 { 72 } else { resolution }; 2]; } let natural = std::array::from_fn(|axis| { let numerator = 473_628_672_i64 * i64::from(image.size[axis]); let denominator = 100 * i64::from(density[axis]); (numerator + denominator / 2) / denominator }); Ok(( PdfImage { version: resource.version, page: 1, page_count: 1, natural, extent: [1.0_f64.to_bits(); 2], objects: vec![vec![Part::Png(image)]], color_space, imported_fonts: Vec::new(), restored_pdf_origin: None, }, warning, )) } impl SampledImage { pub(super) fn rgb8(size: [u32; 2], samples: Vec) -> Self { Self { size, source_depth: 8, source_indexed: false, source_alpha: false, depth: 8, color: ColorSpace::Rgb, samples, alpha: Vec::new(), } } pub(super) fn procset(&self) -> RasterProcSet { // Expanding a PNG transparency table may change the decoded colors. if self.source_indexed || matches!(self.color, ColorSpace::Indexed(_)) { RasterProcSet::Indexed } else if matches!(self.color, ColorSpace::Gray) { RasterProcSet::Gray } else { RasterProcSet::Color } } pub(super) fn has_alpha(&self, pdf_version: (i32, i32)) -> bool { 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>, attributes: &[u8], compression: u8, pdf_version: (i32, i32), color_space: Option, 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 { write!(color, "{byte:02X}").expect("writing to a string"); } color.push_str(">]"); color } }; 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; let reduced; let (depth, samples): (u8, &[u8]) = if strip_16 { reduced = self.samples.iter().step_by(2).copied().collect::>(); (8, &reduced) } else { (self.depth, &self.samples) }; let extra = format!( "/Type /XObject /Subtype /Image /Width {width} /Height {height} \ /ColorSpace {color} /BitsPerComponent {depth}" ); let mut stream = objects::stream(&extra, samples, compression); if !attributes.is_empty() { // Image attributes are TeX printer bytes and may be non-UTF-8. stream.splice(3..3, attributes.iter().copied().chain([b'\n'])); } if target.is_some() { pdf[id - 1] = stream; } else { pdf.push(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 } }