use std::cell::RefCell;
use std::sync::Arc;
use jp2lam::{
ColorSpace, DecodeConcurrency, DecodeLimits as Jp2DecodeLimits, DecodeOutputFormat,
DecodeRequest, DecodeResolution, DecodeResult, DecodeTarget,
};
use crate::image::codec::{DecodeLimits, DecodedFormat, DecodedImage, ImageCodec};
use crate::image::{DecodeParameters, ImageDescriptor, ImageError, StreamFilter};
thread_local! {
static JPX_DECODER: RefCell<jp2lam::Jp2Decoder> = RefCell::new(jp2lam::Jp2Decoder::new());
}
const JPX_QUALITY_MARGIN: f32 = 1.0;
fn jpx_quality_margin() -> f32 {
use std::sync::OnceLock;
static MARGIN: OnceLock<f32> = OnceLock::new();
*MARGIN.get_or_init(|| {
std::env::var("PDF_RENDERER_JPX_MARGIN")
.ok()
.and_then(|v| v.parse::<f32>().ok())
.filter(|m| m.is_finite() && *m >= 1.0)
.unwrap_or(JPX_QUALITY_MARGIN)
})
}
fn jpx_concurrency_override() -> Option<DecodeConcurrency> {
use std::sync::OnceLock;
static C: OnceLock<Option<DecodeConcurrency>> = OnceLock::new();
*C.get_or_init(|| {
std::env::var("PDF_RENDERER_JPX_CONCURRENCY")
.ok()
.and_then(|v| parse_jpx_concurrency(&v))
})
}
fn parse_jpx_concurrency(value: &str) -> Option<DecodeConcurrency> {
let v = value.trim().to_ascii_lowercase();
if v == "serial" {
return Some(DecodeConcurrency::Serial);
}
let n = v.strip_prefix("budgeted:").unwrap_or(&v);
match n.parse::<usize>().ok()? {
0 => None,
1 if n.len() == v.len() => Some(DecodeConcurrency::Serial),
n => Some(DecodeConcurrency::Budgeted(n)),
}
}
fn jpx_decode_trace_enabled() -> bool {
use std::sync::OnceLock;
static TRACE: OnceLock<bool> = OnceLock::new();
*TRACE.get_or_init(|| {
std::env::var("JP2LAM_DECODE_TRACE")
.ok()
.is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes"))
})
}
static JPX_IN_FLIGHT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
struct InFlightGuard;
impl InFlightGuard {
fn enter() -> Self {
JPX_IN_FLIGHT.fetch_add(1, std::sync::atomic::Ordering::AcqRel);
Self
}
fn current(&self) -> usize {
JPX_IN_FLIGHT
.load(std::sync::atomic::Ordering::Acquire)
.max(1)
}
}
impl Drop for InFlightGuard {
fn drop(&mut self) {
JPX_IN_FLIGHT.fetch_sub(1, std::sync::atomic::Ordering::AcqRel);
}
}
const JPX_BUDGET_MIN: usize = 1;
const JPX_BUDGET_MAX: usize = 8;
fn load_aware_budget(in_flight: usize) -> DecodeConcurrency {
use std::sync::OnceLock;
static CORES: OnceLock<usize> = OnceLock::new();
let cores = *CORES.get_or_init(|| {
std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(JPX_BUDGET_MIN)
});
let budget = (cores / in_flight).clamp(JPX_BUDGET_MIN, JPX_BUDGET_MAX);
DecodeConcurrency::Budgeted(budget)
}
#[derive(Debug, Default)]
pub struct JpxCodec;
impl ImageCodec for JpxCodec {
fn filter(&self) -> StreamFilter {
StreamFilter::Jpx
}
fn decode(
&self,
data: &[u8],
descriptor: &ImageDescriptor,
params: &DecodeParameters,
limits: &DecodeLimits,
) -> Result<DecodedImage, ImageError> {
limits.check_input(data.len())?;
let codec_limits = decoder_limits(limits);
let meta = jp2lam::inspect_jp2_with_limits(data, &codec_limits)
.map_err(|e| ImageError::Decode(format!("JPX: {e}")))?;
if limits.is_cancelled() {
return Err(ImageError::Cancelled);
}
let (width, height) = (meta.width, meta.height);
if width == 0 || height == 0 {
return Err(ImageError::Decode("JPX: zero dimension".into()));
}
if u64::from(width) * u64::from(height) > limits.max_pixels {
return Err(ImageError::TooLarge { width, height });
}
let ignore_container_palette = meta.container_palette_channels.is_some()
&& descriptor
.color_space
.as_ref()
.is_some_and(|cs| cs.family == crate::color::ColorSpaceFamily::Indexed);
let (format, channels) = if ignore_container_palette {
(DecodedFormat::Gray8, 1usize)
} else {
match meta.colorspace {
ColorSpace::Gray
if meta.codestream.siz.components.len() == 2
&& descriptor
.color_space
.as_ref()
.is_some_and(|cs| cs.components == 2) =>
{
(DecodedFormat::Multi2, 2usize)
}
ColorSpace::Gray if meta.in_data_alpha.is_some() => (DecodedFormat::GrayA8, 2usize),
ColorSpace::Gray => (DecodedFormat::Gray8, 1usize),
ColorSpace::Srgb if meta.in_data_alpha.is_some() => (DecodedFormat::Rgba8, 4usize),
ColorSpace::Srgb => (DecodedFormat::Rgb8, 3usize),
ColorSpace::YCbCr => (DecodedFormat::Rgb8, 3usize),
ColorSpace::Cmyk => (DecodedFormat::Cmyk8, 4usize),
other => {
return Err(ImageError::Decode(format!(
"JPX: unsupported colorspace {other:?}"
)));
}
}
};
let resolution = decode_resolution(params);
let all_8bit = meta
.codestream
.siz
.components
.iter()
.all(|component| component.precision == 8);
let in_flight = InFlightGuard::enter();
let concurrency =
jpx_concurrency_override().unwrap_or_else(|| load_aware_budget(in_flight.current()));
let packed_direct =
all_8bit && (meta.container_palette_channels.is_none() || ignore_container_palette);
let trace_start = jpx_decode_trace_enabled().then(std::time::Instant::now);
let result = if packed_direct {
let (decoded_width, decoded_height) = meta
.decoded_dimensions(resolution)
.map_err(|e| ImageError::Decode(format!("JPX: {e}")))?;
self.decode_packed(
data,
resolution,
format,
channels,
decoded_width,
decoded_height,
limits,
concurrency,
ignore_container_palette,
)
} else {
self.decode_native_interleaved(
data,
resolution,
format,
channels,
width,
height,
limits,
concurrency,
ignore_container_palette,
)
};
let in_flight_now = in_flight.current();
drop(in_flight);
if let (Some(started), Ok(image)) = (trace_start, &result) {
eprintln!(
"[jpx-trace] src={}x{} out={}x{} fmt={:?} path={} conc={:?} in_flight={} elapsed_ms={:.3}",
width,
height,
image.width,
image.height,
image.format,
if packed_direct { "packed" } else { "planar" },
concurrency,
in_flight_now,
started.elapsed().as_secs_f64() * 1000.0
);
}
if limits.is_cancelled() {
return Err(ImageError::Cancelled);
}
result
}
fn reduction_level(
&self,
data: &[u8],
_descriptor: &ImageDescriptor,
params: &DecodeParameters,
limits: &DecodeLimits,
) -> Option<u8> {
let resolution = decode_resolution(params);
if resolution == DecodeResolution::Full {
return Some(0);
}
jp2lam::inspect_jp2_with_limits(data, &decoder_limits(limits))
.ok()?
.reduce_levels(resolution)
.ok()
}
}
fn decode_resolution(params: &DecodeParameters) -> DecodeResolution {
match params.target_size {
Some((tw, th)) if tw > 0 && th > 0 => DecodeResolution::AtLeast {
width: tw,
height: th,
quality_margin: jpx_quality_margin(),
},
_ => DecodeResolution::Full,
}
}
impl JpxCodec {
#[allow(clippy::too_many_arguments)]
fn decode_packed(
&self,
data: &[u8],
resolution: DecodeResolution,
format: DecodedFormat,
channels: usize,
width: u32,
height: u32,
limits: &DecodeLimits,
concurrency: DecodeConcurrency,
ignore_container_palette: bool,
) -> Result<DecodedImage, ImageError> {
let output = match format {
DecodedFormat::Gray8 => DecodeOutputFormat::Gray8,
DecodedFormat::GrayA8 | DecodedFormat::Multi2 => DecodeOutputFormat::GrayA8,
DecodedFormat::Rgb8 => DecodeOutputFormat::Rgb8,
DecodedFormat::Rgba8 => DecodeOutputFormat::Rgba8,
DecodedFormat::Cmyk8 => DecodeOutputFormat::Cmyk8,
other => {
return Err(ImageError::Decode(format!(
"JPX: packed output not applicable to {other:?}"
)));
}
};
let request = DecodeRequest {
resolution,
output,
region: None,
concurrency,
ignore_container_palette,
limits: decoder_limits(limits),
};
let stride = (width as usize)
.checked_mul(channels)
.ok_or_else(|| ImageError::Decode("JPX: stride overflow".into()))?;
let bytes = stride
.checked_mul(height as usize)
.ok_or_else(|| ImageError::Decode("JPX: size overflow".into()))?;
if bytes as u64 > limits.max_output_bytes {
return Err(ImageError::TooLarge { width, height });
}
let mut output_data = zeroed_arc(bytes);
let Some(output_slice) = Arc::get_mut(&mut output_data) else {
return Err(ImageError::Decode(
"JPX: output allocation unexpectedly became shared".into(),
));
};
let info = JPX_DECODER
.with(|decoder| {
decoder.borrow_mut().decode_into(
data,
&request,
DecodeTarget {
data: output_slice,
width,
height,
stride,
format: output,
premultiplied: false,
},
)
})
.map_err(|e| ImageError::Decode(format!("JPX: {e}")))?;
if limits.is_cancelled() {
return Err(ImageError::Cancelled);
}
Ok(DecodedImage {
width: info.width,
height: info.height,
format,
stride: info.stride,
data: output_data,
})
}
#[allow(clippy::too_many_arguments)]
fn decode_native_interleaved(
&self,
data: &[u8],
resolution: DecodeResolution,
format: DecodedFormat,
channels: usize,
_width: u32,
_height: u32,
limits: &DecodeLimits,
concurrency: DecodeConcurrency,
ignore_container_palette: bool,
) -> Result<DecodedImage, ImageError> {
let request = DecodeRequest {
resolution,
output: DecodeOutputFormat::NativePlanarI32,
region: None,
concurrency,
ignore_container_palette,
limits: decoder_limits(limits),
};
let result = JPX_DECODER
.with(|decoder| decoder.borrow_mut().decode(data, &request))
.map_err(|e| ImageError::Decode(format!("JPX: {e}")))?;
if limits.is_cancelled() {
return Err(ImageError::Cancelled);
}
let image = match result {
DecodeResult::Native(image) => image,
DecodeResult::Raster(_) => {
return Err(ImageError::Decode(
"JPX: native decode returned a packed raster".into(),
));
}
};
let width = image.width;
let height = image.height;
if width == 0 || height == 0 {
return Err(ImageError::Decode("JPX: zero dimension".into()));
}
let ncomp = image.components.len();
if ncomp != channels {
return Err(ImageError::Decode(format!(
"JPX: {format:?} expects {channels} components, decoded {ncomp}"
)));
}
let stride = (width as usize)
.checked_mul(ncomp)
.ok_or_else(|| ImageError::Decode("JPX: stride overflow".into()))?;
let bytes = stride
.checked_mul(height as usize)
.ok_or_else(|| ImageError::Decode("JPX: size overflow".into()))?;
if bytes as u64 > limits.max_output_bytes {
return Err(ImageError::TooLarge { width, height });
}
let pixels = (width as usize)
.checked_mul(height as usize)
.ok_or_else(|| ImageError::Decode("JPX: pixel count overflow".into()))?;
let mut out = zeroed_arc(bytes);
let Some(out_data) = Arc::get_mut(&mut out) else {
return Err(ImageError::Decode(
"JPX: native output allocation unexpectedly became shared".into(),
));
};
let preserve_palette_indices = ignore_container_palette && ncomp == 1;
for (ci, comp) in image.components.iter().enumerate() {
if comp.data.len() < pixels {
return Err(ImageError::Decode("JPX: short component plane".into()));
}
let shift = comp.precision.saturating_sub(8);
let max_sample = (1u32 << comp.precision.clamp(1, 31)) - 1;
for y in 0..height as usize {
if y & 31 == 0 && limits.is_cancelled() {
return Err(ImageError::Cancelled);
}
let row = y * width as usize;
for x in 0..width as usize {
let i = row + x;
out_data[i * ncomp + ci] = component_sample_to_u8(
comp.data[i],
comp.precision,
max_sample,
shift,
preserve_palette_indices,
);
}
}
}
Ok(DecodedImage {
width,
height,
format,
stride,
data: out,
})
}
}
#[allow(
unsafe_code,
reason = "Arc::new_zeroed_slice hands back MaybeUninit; see SAFETY comment"
)]
fn zeroed_arc(len: usize) -> Arc<[u8]> {
let data = Arc::<[u8]>::new_zeroed_slice(len);
unsafe { data.assume_init() }
}
fn decoder_limits(limits: &DecodeLimits) -> Jp2DecodeLimits {
let defaults = Jp2DecodeLimits::default();
Jp2DecodeLimits {
max_input_bytes: defaults
.max_input_bytes
.min(usize::try_from(limits.max_input_bytes).unwrap_or(usize::MAX)),
max_pixels: limits.max_pixels,
max_working_bytes: defaults
.max_working_bytes
.min(usize::try_from(limits.max_working_bytes).unwrap_or(usize::MAX)),
..defaults
}
}
fn component_sample_to_u8(
value: i32,
precision: u32,
max_sample: u32,
right_shift: u32,
preserve_palette_index: bool,
) -> u8 {
if preserve_palette_index {
return value.clamp(0, max_sample.min(255) as i32) as u8;
}
if precision < 8 {
((value.clamp(0, max_sample as i32) as u32) << (8 - precision)).min(255) as u8
} else {
let value = if right_shift > 0 {
value >> right_shift
} else {
value
};
value.clamp(0, 255) as u8
}
}
#[cfg(test)]
mod tests {
use super::{component_sample_to_u8, decoder_limits, load_aware_budget, parse_jpx_concurrency};
use crate::image::codec::DecodeLimits;
use jp2lam::DecodeConcurrency;
#[test]
fn jpx_concurrency_override_accepts_bare_counts() {
assert_eq!(
parse_jpx_concurrency("serial"),
Some(DecodeConcurrency::Serial)
);
assert_eq!(
parse_jpx_concurrency(" 1 "),
Some(DecodeConcurrency::Serial)
);
assert_eq!(
parse_jpx_concurrency("4"),
Some(DecodeConcurrency::Budgeted(4))
);
assert_eq!(
parse_jpx_concurrency("budgeted:1"),
Some(DecodeConcurrency::Budgeted(1))
);
assert_eq!(
parse_jpx_concurrency("Budgeted:3"),
Some(DecodeConcurrency::Budgeted(3))
);
assert_eq!(parse_jpx_concurrency("0"), None);
assert_eq!(parse_jpx_concurrency("budgeted:0"), None);
assert_eq!(parse_jpx_concurrency("auto"), None);
assert_eq!(parse_jpx_concurrency("fast"), None);
}
#[test]
fn saturated_load_can_fall_back_to_one_decode_worker() {
assert_eq!(
load_aware_budget(usize::MAX),
DecodeConcurrency::Budgeted(1)
);
}
#[test]
fn sub8_pdf_palette_indices_are_not_color_widened() {
assert_eq!(component_sample_to_u8(15, 4, 15, 0, true), 15);
assert_eq!(
component_sample_to_u8(15, 4, 15, 0, false),
240,
"ordinary 4-bit color components retain PDFium's widening"
);
}
#[test]
fn renderer_limits_are_pushed_into_jp2_decode() {
let renderer = DecodeLimits {
max_input_bytes: 2048,
max_pixels: 1234,
max_output_bytes: 4096,
max_working_bytes: 3072,
..DecodeLimits::default()
};
let mapped = decoder_limits(&renderer);
assert_eq!(mapped.max_pixels, 1234);
assert_eq!(mapped.max_input_bytes, 2048);
assert_eq!(mapped.max_working_bytes, 3072);
}
}