use std::cell::RefCell;
use std::sync::{Arc, Mutex};
use jbig2enc_rust::decode::{
DecodeError, DecodeOptions, DecodeStrictness, DecodedGlobals, DecoderContext,
decode_embedded_with_globals, decode_globals,
};
use jbig2enc_rust::shared::limits::DecodeLimits as Jbig2Limits;
use crate::image::codec::{DecodeLimits, DecodedFormat, DecodedImage, ImageCodec};
use crate::image::{DecodeParameters, ImageDescriptor, ImageError, StreamFilter};
thread_local! {
static JBIG2_CONTEXT: RefCell<DecoderContext> = RefCell::new(DecoderContext::new());
}
const MAX_CACHED_GLOBALS_BYTES: usize = 32 * 1024 * 1024;
struct CachedGlobals {
encoded: Arc<[u8]>,
limits: Jbig2Limits,
decoded: Arc<DecodedGlobals>,
}
#[derive(Default)]
pub struct Jbig2Codec {
globals_cache: Mutex<Option<CachedGlobals>>,
}
impl std::fmt::Debug for Jbig2Codec {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Jbig2Codec")
.field(
"globals_cached",
&lock_unpoisoned(&self.globals_cache).is_some(),
)
.finish()
}
}
impl ImageCodec for Jbig2Codec {
fn filter(&self) -> StreamFilter {
StreamFilter::Jbig2
}
fn decode(
&self,
data: &[u8],
_descriptor: &ImageDescriptor,
params: &DecodeParameters,
limits: &DecodeLimits,
) -> Result<DecodedImage, ImageError> {
let globals = params
.jbig2_globals
.as_ref()
.filter(|globals| !globals.is_empty());
if jbig2enc_rust::decode::file::has_file_magic(data) {
return Err(ImageError::Decode(
"JBIG2: standalone file header in embedded stream".into(),
));
}
let input_bytes = data
.len()
.checked_add(globals.map_or(0, |g| g.len()))
.ok_or_else(|| ImageError::Decode("JBIG2: input size overflow".into()))?;
limits.check_input(input_bytes)?;
let px_budget = limits.max_pixels_at_bpp(1);
let options = DecodeOptions {
limits: decoder_limits(limits, px_budget),
strictness: DecodeStrictness::Compatible,
};
let decoded_globals = globals
.map(|bytes| self.decode_globals_cached(bytes, &options))
.transpose()?;
let bitmap = JBIG2_CONTEXT
.with(|ctx| {
decode_embedded_with_globals(
decoded_globals.as_deref(),
data,
&options,
&mut ctx.borrow_mut(),
)
})
.map_err(map_err)?;
if limits.is_cancelled() {
return Err(ImageError::Cancelled);
}
let (width, height) = (bitmap.width(), bitmap.height());
if width == 0 || height == 0 {
return Err(ImageError::Decode("JBIG2: zero dimension".into()));
}
if u64::from(width) * u64::from(height) > px_budget {
return Err(ImageError::TooLarge { width, height });
}
let stride = (width as usize).div_ceil(8);
let bytes = stride
.checked_mul(height as usize)
.ok_or_else(|| ImageError::Decode("JBIG2: size overflow".into()))?;
if bytes as u64 > limits.max_output_bytes {
return Err(ImageError::TooLarge { width, height });
}
let mut data = zeroed_arc(bytes);
let Some(out) = Arc::get_mut(&mut data) else {
return Err(ImageError::Decode(
"JBIG2: output allocation unexpectedly became shared".into(),
));
};
for (y, dst) in out.chunks_exact_mut(stride).enumerate() {
if y % 256 == 0 && limits.is_cancelled() {
return Err(ImageError::Cancelled);
}
for (d, &w) in dst.chunks_mut(4).zip(bitmap.row(y as u32)) {
let inverted = (!w).to_be_bytes();
d.copy_from_slice(&inverted[..d.len()]);
}
}
Ok(DecodedImage {
width,
height,
format: DecodedFormat::Mono1,
stride,
data,
})
}
fn reduction_level(
&self,
_data: &[u8],
_descriptor: &ImageDescriptor,
_params: &DecodeParameters,
_limits: &DecodeLimits,
) -> Option<u8> {
Some(0)
}
}
impl Jbig2Codec {
pub fn new() -> Self {
Self::default()
}
fn decode_globals_cached(
&self,
encoded: &Arc<[u8]>,
options: &DecodeOptions,
) -> Result<Arc<DecodedGlobals>, ImageError> {
{
let cache = lock_unpoisoned(&self.globals_cache);
if let Some(cached) = cache.as_ref()
&& cached.limits == options.limits
&& (Arc::ptr_eq(&cached.encoded, encoded)
|| cached.encoded.as_ref() == encoded.as_ref())
{
return Ok(Arc::clone(&cached.decoded));
}
}
let decoded = Arc::new(decode_globals(encoded, options).map_err(map_err)?);
let retained = decoded
.retained_bytes()
.checked_add(encoded.len())
.unwrap_or(usize::MAX);
let caller_budget = options.limits.max_retained_bytes;
if retained <= caller_budget.min(MAX_CACHED_GLOBALS_BYTES) {
*lock_unpoisoned(&self.globals_cache) = Some(CachedGlobals {
encoded: Arc::clone(encoded),
limits: options.limits,
decoded: Arc::clone(&decoded),
});
}
Ok(decoded)
}
}
#[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 lock_unpoisoned<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
fn decoder_limits(limits: &DecodeLimits, px_budget: u64) -> Jbig2Limits {
let defaults = Jbig2Limits::default();
let retained_byte_budget = usize::try_from(limits.max_working_bytes)
.unwrap_or(usize::MAX)
.min(defaults.max_retained_bytes);
Jbig2Limits {
max_page_pixels: px_budget,
max_region_pixels: px_budget,
max_symbol_pixels: px_budget,
max_total_dictionary_pixels: px_budget,
max_retained_bytes: retained_byte_budget,
..defaults
}
}
fn map_err(e: DecodeError) -> ImageError {
match &e {
DecodeError::Limit(_) => ImageError::Decode(format!("JBIG2: limit exceeded: {e}")),
_ => ImageError::Decode(format!("JBIG2: {e}")),
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
const JBIG2_L_12X5: &[u8] = &[
0x00, 0x00, 0x00, 0x01, 0x30, 0x00, 0x01, 0x00, 0x00, 0x00, 0x13, 0x00, 0x00, 0x00, 0x0c,
0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x01, 0x2c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x02, 0x26, 0x00, 0x01, 0x00, 0x00, 0x00, 0x22, 0x00, 0x00, 0x00, 0x0c,
0x00, 0x00, 0x00, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03,
0xff, 0xfd, 0xff, 0x02, 0xfe, 0xfe, 0xfe, 0xd2, 0x47, 0xc5, 0xc3, 0x1b, 0xff, 0xff, 0xac,
];
const EXPECT_L: &[u8] = &[0x7f, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x7f, 0xff, 0x03, 0xff];
fn descriptor() -> ImageDescriptor {
ImageDescriptor {
width: 12,
height: 5,
bits_per_component: 1,
color_space: None,
is_mask: false,
interpolate: false,
filters: vec![StreamFilter::Jbig2],
object: None,
}
}
#[test]
fn decodes_embedded_generic_region_with_pdf_polarity() {
let codec = Jbig2Codec::new();
let img = codec
.decode(
JBIG2_L_12X5,
&descriptor(),
&DecodeParameters::default(),
&DecodeLimits::default(),
)
.expect("decode L fixture");
assert_eq!((img.width, img.height), (12, 5));
assert_eq!(img.format, DecodedFormat::Mono1);
assert_eq!(img.stride, 2);
assert_eq!(&*img.data, EXPECT_L);
let again = codec
.decode(
JBIG2_L_12X5,
&descriptor(),
&DecodeParameters::default(),
&DecodeLimits::default(),
)
.expect("repeat decode L fixture");
assert_eq!(again.data, img.data);
}
#[test]
fn cancellation_wins_over_malformed_input() {
let limits = DecodeLimits {
should_cancel: Some(Arc::new(|| true)),
..DecodeLimits::default()
};
let result = Jbig2Codec::new().decode(
b"not a jbig2 stream",
&descriptor(),
&DecodeParameters::default(),
&limits,
);
assert!(matches!(result, Err(ImageError::Cancelled)));
}
#[test]
fn standalone_file_header_is_rejected_in_embedded_stream() {
let mut with_header = jbig2enc_rust::decode::file::FILE_MAGIC.to_vec();
with_header.extend_from_slice(JBIG2_L_12X5);
let err = Jbig2Codec::default().decode(
&with_header,
&descriptor(),
&DecodeParameters::default(),
&DecodeLimits::default(),
);
assert!(matches!(err, Err(ImageError::Decode(_))));
}
#[test]
fn garbage_is_a_typed_error_not_a_panic() {
let err = Jbig2Codec::default().decode(
b"not a jbig2 stream at all",
&descriptor(),
&DecodeParameters::default(),
&DecodeLimits::default(),
);
assert!(matches!(err, Err(ImageError::Decode(_))));
}
#[test]
fn pixel_limit_is_enforced() {
let tight = DecodeLimits {
max_pixels: 4,
..DecodeLimits::default()
};
let err = Jbig2Codec::default().decode(
JBIG2_L_12X5,
&descriptor(),
&DecodeParameters::default(),
&tight,
);
assert!(matches!(
err,
Err(ImageError::Decode(_)) | Err(ImageError::TooLarge { .. })
));
}
#[test]
fn bilevel_budget_admits_a_page_over_the_raw_pixel_cap() {
let limits = DecodeLimits {
max_pixels: 8,
..DecodeLimits::default()
};
let out = Jbig2Codec::default()
.decode(
JBIG2_L_12X5,
&descriptor(),
&DecodeParameters::default(),
&limits,
)
.expect("60 px is over max_pixels=8 but inside the 64 px bilevel budget");
assert_eq!((out.width, out.height), (12, 5));
}
#[test]
fn renderer_byte_ceiling_limits_retained_decoder_state() {
let limits = DecodeLimits {
max_output_bytes: 8192,
max_working_bytes: 4096,
..DecodeLimits::default()
};
let mapped = decoder_limits(&limits, limits.max_pixels_at_bpp(1));
assert_eq!(mapped.max_retained_bytes, 4096);
let loose = decoder_limits(&DecodeLimits::default(), u64::MAX);
assert_eq!(
loose.max_retained_bytes,
Jbig2Limits::default().max_retained_bytes
);
}
}