use std::sync::Arc;
use crate::reader::session::{
CancellationToken, CompiledDocumentPage, GraySurface, PageGeometry, RasterFormat, RasterPlane,
RasterProduct, ReadError, RenderSession, RgbSurface,
};
pub const DEFAULT_EXPORT_DPI: f64 = 150.0;
pub const DEFAULT_MAX_EXPORT_PIXELS: u64 = 100_000_000;
const MAX_EXPORT_DPI: f64 = 10_000.0;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
Png,
Jpeg {
quality: u8,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExportColor {
Rgb8,
Gray8,
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ExportOptions {
pub dpi: f64,
pub format: ImageFormat,
pub color: ExportColor,
pub max_pixels: u64,
}
impl Default for ExportOptions {
fn default() -> Self {
Self {
dpi: DEFAULT_EXPORT_DPI,
format: ImageFormat::Png,
color: ExportColor::Rgb8,
max_pixels: DEFAULT_MAX_EXPORT_PIXELS,
}
}
}
impl ExportOptions {
pub fn png(dpi: f64) -> Self {
Self {
dpi,
format: ImageFormat::Png,
..Self::default()
}
}
pub fn jpeg(dpi: f64, quality: u8) -> Self {
Self {
dpi,
format: ImageFormat::Jpeg { quality },
..Self::default()
}
}
pub fn with_color(mut self, color: ExportColor) -> Self {
self.color = color;
self
}
pub fn with_max_pixels(mut self, max_pixels: u64) -> Self {
self.max_pixels = max_pixels;
self
}
fn raster_format(self) -> RasterFormat {
match self.color {
ExportColor::Rgb8 => RasterFormat::Rgb8,
ExportColor::Gray8 => RasterFormat::Gray8,
}
}
}
pub fn pixel_size_for_dpi(
geometry: PageGeometry,
dpi: f64,
max_pixels: u64,
) -> Result<(u32, u32), ReadError> {
if !dpi.is_finite() || dpi <= 0.0 {
return Err(ReadError::InvalidExportOptions(
"dpi must be finite and greater than zero",
));
}
if dpi > MAX_EXPORT_DPI {
return Err(ReadError::InvalidExportOptions("dpi exceeds 10000"));
}
let scale = dpi / 72.0;
let to_pixels = |points: f64| -> u32 {
let pixels = (points * scale).round();
if !pixels.is_finite() || pixels < 1.0 {
1
} else if pixels > u32::MAX as f64 {
u32::MAX
} else {
pixels as u32
}
};
let width = to_pixels(geometry.display_width());
let height = to_pixels(geometry.display_height());
if u64::from(width) * u64::from(height) > max_pixels {
return Err(ReadError::ExportTooLarge {
width,
height,
max_pixels,
});
}
Ok((width, height))
}
impl RenderSession {
pub fn page_pixel_size(&self, page: u32, dpi: f64) -> Result<(u32, u32), ReadError> {
pixel_size_for_dpi(self.page_geometry(page)?, dpi, u64::MAX)
}
pub fn export_page(&self, page: u32, options: &ExportOptions) -> Result<Vec<u8>, ReadError> {
self.export_page_cancellable(page, options, None)
}
pub fn export_page_cancellable(
&self,
page: u32,
options: &ExportOptions,
cancellation: Option<&CancellationToken>,
) -> Result<Vec<u8>, ReadError> {
let compiled = self.compile_cancellable(page, cancellation)?;
self.export_compiled_page(&compiled, options, cancellation)
}
pub fn export_compiled_page(
&self,
page: &Arc<CompiledDocumentPage>,
options: &ExportOptions,
cancellation: Option<&CancellationToken>,
) -> Result<Vec<u8>, ReadError> {
let geometry = self.page_geometry(page.page_index())?;
let (width, height) = pixel_size_for_dpi(geometry, options.dpi, options.max_pixels)?;
let product = RasterProduct {
width,
height,
format: options.raster_format(),
crop: None,
decode_reference: None,
};
let plane = self.render_cancellable(page, &product, cancellation)?;
encode_plane(&plane, options.format)
}
}
pub fn encode_plane(plane: &RasterPlane, format: ImageFormat) -> Result<Vec<u8>, ReadError> {
match plane {
RasterPlane::Rgb8(surface) => encode_rgb(surface, format),
RasterPlane::Gray8(surface) => encode_gray(surface, format),
}
}
fn encode_rgb(surface: &RgbSurface, format: ImageFormat) -> Result<Vec<u8>, ReadError> {
let packed = pack_rows(
&surface.pixels,
surface.width,
surface.height,
surface.stride,
3,
)?;
match format {
ImageFormat::Png => encode_png(&packed, surface.width, surface.height, png::ColorType::Rgb),
ImageFormat::Jpeg { quality } => encode_jpeg(
&packed,
surface.width,
surface.height,
quality,
jpeg_encoder::ColorType::Rgb,
),
}
}
fn encode_gray(surface: &GraySurface, format: ImageFormat) -> Result<Vec<u8>, ReadError> {
let packed = pack_rows(
&surface.pixels,
surface.width,
surface.height,
surface.stride,
1,
)?;
match format {
ImageFormat::Png => encode_png(
&packed,
surface.width,
surface.height,
png::ColorType::Grayscale,
),
ImageFormat::Jpeg { quality } => encode_jpeg(
&packed,
surface.width,
surface.height,
quality,
jpeg_encoder::ColorType::Luma,
),
}
}
fn pack_rows<'a>(
pixels: &'a Arc<[u8]>,
width: u32,
height: u32,
stride: usize,
bytes_per_pixel: usize,
) -> Result<std::borrow::Cow<'a, [u8]>, ReadError> {
let row_bytes = (width as usize)
.checked_mul(bytes_per_pixel)
.ok_or(ReadError::InvalidRasterProduct("row size overflow"))?;
let height = height as usize;
if stride == row_bytes {
let needed = row_bytes
.checked_mul(height)
.ok_or(ReadError::InvalidRasterProduct("surface size overflow"))?;
let packed = pixels
.get(..needed)
.ok_or_else(|| ReadError::Encode("surface is shorter than its dimensions".into()))?;
return Ok(std::borrow::Cow::Borrowed(packed));
}
let capacity = row_bytes
.checked_mul(height)
.ok_or(ReadError::InvalidRasterProduct("surface size overflow"))?;
let mut packed = Vec::with_capacity(capacity);
for row in 0..height {
let start = row
.checked_mul(stride)
.ok_or(ReadError::InvalidRasterProduct("row offset overflow"))?;
let end = start
.checked_add(row_bytes)
.ok_or(ReadError::InvalidRasterProduct("row end overflow"))?;
let row = pixels
.get(start..end)
.ok_or_else(|| ReadError::Encode("surface row is out of bounds".into()))?;
packed.extend_from_slice(row);
}
Ok(std::borrow::Cow::Owned(packed))
}
fn encode_png(
packed: &[u8],
width: u32,
height: u32,
color: png::ColorType,
) -> Result<Vec<u8>, ReadError> {
let mut out = Vec::new();
let mut encoder = png::Encoder::new(&mut out, width, height);
encoder.set_color(color);
encoder.set_depth(png::BitDepth::Eight);
let mut writer = encoder
.write_header()
.map_err(|error| ReadError::Encode(format!("writing PNG header: {error}")))?;
writer
.write_image_data(packed)
.map_err(|error| ReadError::Encode(format!("writing PNG pixels: {error}")))?;
writer
.finish()
.map_err(|error| ReadError::Encode(format!("finishing PNG stream: {error}")))?;
Ok(out)
}
fn encode_jpeg(
packed: &[u8],
width: u32,
height: u32,
quality: u8,
color: jpeg_encoder::ColorType,
) -> Result<Vec<u8>, ReadError> {
let width = u16::try_from(width)
.map_err(|_| ReadError::Encode("JPEG width exceeds 65535 pixels".into()))?;
let height = u16::try_from(height)
.map_err(|_| ReadError::Encode("JPEG height exceeds 65535 pixels".into()))?;
let mut out = Vec::new();
let encoder = jpeg_encoder::Encoder::new(&mut out, quality.clamp(1, 100));
encoder
.encode(packed, width, height, color)
.map_err(|error| ReadError::Encode(format!("encoding JPEG: {error}")))?;
Ok(out)
}