use super::image::*;
use super::jp2::*;
#[cfg(feature = "event-handlers")]
use super::consts::*;
use super::stream::Stream;
use super::types::*;
use super::api::{DecodeArea, DecodeError, DecodeLimits, EncoderParameters, Error, Result};
use super::event::*;
use super::fprintf::StringWriter;
use super::j2k::*;
use crate::J2KFormat;
#[allow(clippy::large_enum_variant)]
pub(crate) enum CodecFormat {
J2K(J2k),
JP2(Jp2),
}
#[derive(Clone, Copy, Default, Debug)]
pub struct DecoderSettings {
pub layers: u32,
pub reduce: u32,
pub ignore_pclr_cmap_cdef: bool,
pub dump_state: bool,
pub threads: usize,
}
pub struct HeaderImage(CoreImage);
impl HeaderImage {
pub fn width(&self) -> u32 {
self.0.x1 - self.0.x0
}
pub fn height(&self) -> u32 {
self.0.y1 - self.0.y0
}
pub fn num_components(&self) -> u32 {
self.0.numcomps
}
pub fn into_core_image(self) -> CoreImage {
self.0
}
}
#[derive(Clone, Default, Debug)]
pub struct TileInfo {
pub index: u32,
pub data_size: Option<u32>,
pub x0: i32,
pub y0: i32,
pub x1: i32,
pub y1: i32,
pub nb_comps: u32,
pub go_on: bool,
}
pub struct Decoder {
pub(crate) m_codec: CodecFormat,
pub(crate) m_event_mgr: EventMgr,
header: Option<CoreImage>,
pending_area: Option<DecodeArea>,
threads: usize,
#[cfg(feature = "rayon")]
pool: Option<std::rc::Rc<rayon::ThreadPool>>,
}
pub struct Encoder {
pub(crate) m_codec: CodecFormat,
pub(crate) m_event_mgr: EventMgr,
}
macro_rules! codec_common {
($ty:ty) => {
impl $ty {
#[cfg(feature = "event-handlers")]
pub fn set_info_handler(&mut self, handler: impl FnMut(&str) + Send + 'static) {
self.m_event_mgr.set_info_handler(handler);
}
#[cfg(feature = "event-handlers")]
pub fn set_warning_handler(&mut self, handler: impl FnMut(&str) + Send + 'static) {
self.m_event_mgr.set_warning_handler(handler);
}
#[cfg(feature = "event-handlers")]
pub fn set_error_handler(&mut self, handler: impl FnMut(&str) + Send + 'static) {
self.m_event_mgr.set_error_handler(handler);
}
pub fn set_threads(&mut self, num_threads: i32) -> Result<()> {
if num_threads < 0i32 {
return Err(Error::Unsupported("negative thread count".into()));
}
let ok = match &mut self.m_codec {
CodecFormat::J2K(j2k) => j2k_set_threads(j2k, num_threads as u32),
CodecFormat::JP2(jp2) => jp2_set_threads(jp2, num_threads as u32),
};
if ok.is_ok() {
Ok(())
} else {
Err(Error::Unsupported(
"threading is unavailable or the count is out of range".into(),
))
}
}
pub fn dump_codec<W: StringWriter>(&self, mut info_flag: i32, mut output_stream: &mut W) {
match &self.m_codec {
CodecFormat::J2K(j2k) => j2k_dump(j2k, info_flag, output_stream),
CodecFormat::JP2(jp2) => jp2_dump(jp2, info_flag, output_stream),
}
}
pub fn cstr_info(&self) -> Option<crate::j2k::CstrInfoV2> {
match &self.m_codec {
CodecFormat::J2K(j2k) => crate::j2k::j2k_get_cstr_info_owned(j2k),
CodecFormat::JP2(jp2) => crate::j2k::j2k_get_cstr_info_owned(&jp2.j2k),
}
}
pub fn cstr_index(&self) -> Option<crate::j2k::CodestreamIndex> {
match &self.m_codec {
CodecFormat::J2K(j2k) => j2k.cstr_index.as_deref().cloned(),
CodecFormat::JP2(jp2) => jp2.j2k.cstr_index.as_deref().cloned(),
}
}
pub fn get_tile_geometry(&self) -> (u32, u32, u32, u32) {
let j2k = match &self.m_codec {
CodecFormat::J2K(j2k) => j2k,
CodecFormat::JP2(jp2) => &jp2.j2k,
};
let tcp = j2k.m_specific_param.m_decoder.m_default_tcp.as_deref();
let (cblkw, cblkh) = match tcp {
Some(t) => (t.tccps[0].cblkw, t.tccps[0].cblkh),
None => (0, 0),
};
(j2k.m_cp.tdx, j2k.m_cp.tdy, cblkw, cblkh)
}
#[cfg(feature = "event-handlers")]
#[doc(hidden)]
pub fn emit_error_event(&mut self, msg: &str) {
event_msg!(&mut self.m_event_mgr, EVT_ERROR, "{}", msg);
}
}
};
}
codec_common!(Decoder);
codec_common!(Encoder);
impl Decoder {
pub fn new(format: J2KFormat) -> Result<Self> {
let m_codec = match format {
J2KFormat::J2K => CodecFormat::J2K(
j2k_create_decompress().ok_or_else(|| Error::Decode("failed to create decoder".into()))?,
),
J2KFormat::JP2 => {
CodecFormat::JP2(
jp2_create(true).ok_or_else(|| Error::Decode("failed to create decoder".into()))?,
)
}
other => {
return Err(Error::Unsupported(format!(
"codec format {:?} is not supported for decoding",
other
)));
}
};
Ok(Decoder {
m_codec,
m_event_mgr: Default::default(),
header: None,
pending_area: None,
threads: 0,
#[cfg(feature = "rayon")]
pool: None,
})
}
pub fn apply_settings(&mut self, settings: &DecoderSettings) -> Result<()> {
self.threads = settings.threads;
match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_setup_decoder(dec, settings),
CodecFormat::JP2(dec) => jp2_setup_decoder(dec, settings),
}
Ok(())
}
fn with_pool<T>(&mut self, f: impl FnOnce(&mut Self) -> T) -> T {
#[cfg(feature = "rayon")]
{
if self.threads == 0 {
return f(self);
}
if self.pool.is_none() {
self.pool = rayon::ThreadPoolBuilder::new()
.num_threads(self.threads)
.build()
.ok()
.map(std::rc::Rc::new);
}
match &self.pool {
Some(pool) => {
let _guard = crate::par::set_current_pool(pool);
f(self)
}
None => f(self),
}
}
#[cfg(not(feature = "rayon"))]
{
let _ = self.threads;
f(self)
}
}
pub fn set_strict(&mut self, strict: bool) -> Result<()> {
match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_decoder_set_strict_mode(dec, strict),
CodecFormat::JP2(dec) => jp2_decoder_set_strict_mode(dec, strict),
}
Ok(())
}
pub fn set_limits(&mut self, limits: DecodeLimits) -> Result<()> {
match &mut self.m_codec {
CodecFormat::J2K(dec) => {
dec.decode_limits = limits;
}
CodecFormat::JP2(dec) => {
dec.j2k.decode_limits = limits;
}
}
Ok(())
}
pub fn set_components(&mut self, components: &[u32]) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_set_decoded_components(dec, components, &mut self.m_event_mgr),
CodecFormat::JP2(dec) => jp2_set_decoded_components(dec, components, &mut self.m_event_mgr),
};
if ok.is_ok() {
Ok(())
} else {
Err(Error::Decode("set_decoded_components failed".into()))
}
}
pub fn set_decode_area(
&mut self,
header: &mut CoreImage,
area: Option<DecodeArea>,
) -> Result<()> {
self.pending_area = area;
if let Some(area) = area {
let ok = match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_set_decode_area(
dec,
header,
area.start_x as i32,
area.start_y as i32,
area.end_x as i32,
area.end_y as i32,
&mut self.m_event_mgr,
),
CodecFormat::JP2(dec) => jp2_set_decode_area(
dec,
header,
area.start_x as i32,
area.start_y as i32,
area.end_x as i32,
area.end_y as i32,
&mut self.m_event_mgr,
),
};
if ok.is_err() {
return Err(self.decode_error("set_decode_area failed"));
}
}
Ok(())
}
pub fn set_resolution_factor(&mut self, res_factor: u32) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(dec) => {
j2k_set_decoded_resolution_factor(dec, res_factor, &mut self.m_event_mgr)
}
CodecFormat::JP2(dec) => {
jp2_set_decoded_resolution_factor(dec, res_factor, &mut self.m_event_mgr)
}
};
if ok.is_ok() {
Ok(())
} else {
Err(Error::Decode("set_decoded_resolution_factor failed".into()))
}
}
pub fn read_header(&mut self, stream: &mut Stream) -> Result<HeaderImage> {
let image = match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_read_header(stream, dec, &mut self.m_event_mgr),
CodecFormat::JP2(dec) => jp2_read_header(stream, dec, &mut self.m_event_mgr),
}
.ok_or_else(|| self.decode_error("failed to read header"))?;
self.header = Some(image.clone());
Ok(HeaderImage(image))
}
pub fn decode(&mut self, stream: &mut Stream) -> Result<CoreImage> {
self.with_pool(|slf| slf.decode_body(stream))
}
fn decode_body(&mut self, stream: &mut Stream) -> Result<CoreImage> {
let mut image = self
.header
.clone()
.ok_or_else(|| self.decode_error("read_header must be called before decode"))?;
#[cfg(feature = "rayon")]
if self.pending_area.is_none() {
let (layer, reduce, strict) = self.state_summary();
if !strict && layer == 0 && reduce == 0 {
let full_header = image.clone();
if let Some(core) = self.decode_parallel(stream, &full_header, 0, 0, strict) {
return Ok(core);
}
}
}
if let Some(area) = self.pending_area {
#[cfg(feature = "rayon")]
let full_header = image.clone();
let ok = match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_set_decode_area(
dec,
&mut image,
area.start_x as i32,
area.start_y as i32,
area.end_x as i32,
area.end_y as i32,
&mut self.m_event_mgr,
),
CodecFormat::JP2(dec) => jp2_set_decode_area(
dec,
&mut image,
area.start_x as i32,
area.start_y as i32,
area.end_x as i32,
area.end_y as i32,
&mut self.m_event_mgr,
),
};
if ok.is_err() {
return Err(Error::Decode("set_decode_area failed".into()));
}
#[cfg(feature = "rayon")]
{
let (layer, reduce, strict) = self.state_summary();
if !strict && layer == 0 && reduce == 0 {
if let Some(core) = self.decode_parallel_area(stream, &full_header, &image) {
return Ok(core);
}
}
}
}
let (ok, strict) = match &mut self.m_codec {
CodecFormat::J2K(dec) => (
j2k_decode(dec, stream, &mut image, &mut self.m_event_mgr),
dec.m_cp.strict,
),
CodecFormat::JP2(dec) => (
jp2_decode(dec, stream, &mut image, &mut self.m_event_mgr),
dec.j2k.m_cp.strict,
),
};
if ok.is_err() {
if strict {
return Err(self.decode_error("decode failed"));
}
return Ok(image);
}
Ok(image)
}
pub fn end_decompress(&mut self, stream: &mut Stream) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_end_decompress(dec, stream, &mut self.m_event_mgr),
CodecFormat::JP2(dec) => jp2_end_decompress(dec, stream, &mut self.m_event_mgr),
};
if ok.is_ok() {
Ok(())
} else {
Err(self.decode_error("end_decompress failed"))
}
}
pub fn read_tile_header(&mut self, stream: &mut Stream) -> Result<TileInfo> {
let mut tile_info = TileInfo {
data_size: Some(0), ..Default::default()
};
let ok = match &mut self.m_codec {
CodecFormat::J2K(dec) => {
j2k_read_tile_header(dec, stream, &mut tile_info, &mut self.m_event_mgr)
}
CodecFormat::JP2(dec) => {
jp2_read_tile_header(dec, stream, &mut tile_info, &mut self.m_event_mgr)
}
};
if ok {
Ok(tile_info)
} else {
Err(self.decode_error("read_tile_header failed"))
}
}
pub fn decode_tile_data(
&mut self,
stream: &mut Stream,
tile: u32,
out: Option<&mut [u8]>,
) -> Result<()> {
self.with_pool(|slf| slf.decode_tile_data_body(stream, tile, out))
}
fn decode_tile_data_body(
&mut self,
stream: &mut Stream,
tile: u32,
out: Option<&mut [u8]>,
) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_decode_tile(dec, tile, out, stream, &mut self.m_event_mgr),
CodecFormat::JP2(dec) => jp2_decode_tile(dec, tile, out, stream, &mut self.m_event_mgr),
};
if ok.is_ok() {
Ok(())
} else {
Err(self.decode_error("decode_tile_data failed"))
}
}
pub fn get_decoded_tile(&mut self, stream: &mut Stream, tile: u32) -> Result<CoreImage> {
self.with_pool(|slf| slf.get_decoded_tile_body(stream, tile))
}
fn get_decoded_tile_body(&mut self, stream: &mut Stream, tile: u32) -> Result<CoreImage> {
let mut image = self
.header
.clone()
.ok_or_else(|| self.decode_error("read_header must be called before get_decoded_tile"))?;
let ok = match &mut self.m_codec {
CodecFormat::J2K(dec) => j2k_get_tile(dec, stream, &mut image, &mut self.m_event_mgr, tile),
CodecFormat::JP2(dec) => jp2_get_tile(dec, stream, &mut image, &mut self.m_event_mgr, tile),
};
if ok.is_ok() {
Ok(image)
} else {
Err(self.decode_error("get_decoded_tile failed"))
}
}
fn decode_error(&self, fallback: &str) -> Error {
match &self.m_codec {
CodecFormat::J2K(j2k) => Error::Decode(DecodeError {
message: fallback.into(),
marker: j2k.last_marker.map(|m| m as u16),
box_: None,
pos: j2k.last_pos,
}),
CodecFormat::JP2(jp2) => Error::Decode(DecodeError {
message: fallback.into(),
marker: jp2.j2k.last_marker.map(|m| m as u16),
box_: jp2.last_box,
pos: jp2.last_pos.or(jp2.j2k.last_pos),
}),
}
}
fn state_summary(&self) -> (u32, u32, bool) {
match &self.m_codec {
CodecFormat::J2K(j2k) => (
j2k.m_cp.m_specific_param.m_dec.m_layer,
j2k.m_cp.m_specific_param.m_dec.m_reduce,
j2k.m_cp.strict,
),
CodecFormat::JP2(jp2) => (
jp2.j2k.m_cp.m_specific_param.m_dec.m_layer,
jp2.j2k.m_cp.m_specific_param.m_dec.m_reduce,
jp2.j2k.m_cp.strict,
),
}
}
#[cfg(feature = "rayon")]
pub(crate) fn decode_parallel_area(
&mut self,
stream: &mut Stream,
header: &CoreImage,
area_image: &CoreImage,
) -> Option<CoreImage> {
let (cp, limits) = match &self.m_codec {
CodecFormat::J2K(j2k) => {
if j2k.m_header_partial {
return None;
}
(&j2k.m_cp, j2k.decode_limits)
}
CodecFormat::JP2(jp2) => {
if jp2.j2k.m_header_partial {
return None;
}
(&jp2.j2k.m_cp, jp2.j2k.decode_limits)
}
};
let info = self.cstr_info()?;
let num_tiles = info.tw.wrapping_mul(info.th);
let dec = match &self.m_codec {
CodecFormat::J2K(j2k) => &j2k.m_specific_param.m_decoder,
CodecFormat::JP2(jp2) => &jp2.j2k.m_specific_param.m_decoder,
};
let (start_x, start_y) = (dec.m_start_tile_x, dec.m_start_tile_y);
let (end_x, end_y) = (dec.m_end_tile_x, dec.m_end_tile_y);
if end_x <= start_x || end_y <= start_y {
return None;
}
let mut tiles = Vec::new();
for ty in start_y..end_y {
for tx in start_x..end_x {
tiles.push(ty.wrapping_mul(info.tw).wrapping_add(tx));
}
}
if tiles.len() <= 1 {
return None;
}
for &tile in &tiles {
let tx = tile % info.tw;
let ty = tile / info.tw;
let tile_x0 = tx.wrapping_mul(info.tdx).wrapping_add(cp.tx0);
let tile_y0 = ty.wrapping_mul(info.tdy).wrapping_add(cp.ty0);
let tile_x1 = (tile_x0.wrapping_add(info.tdx)).min(header.x1);
let tile_y1 = (tile_y0.wrapping_add(info.tdy)).min(header.y1);
if area_image.x0 > tile_x0
|| area_image.y0 > tile_y0
|| area_image.x1 < tile_x1
|| area_image.y1 < tile_y1
{
return None;
}
}
let cstr_index = self.cstr_index()?;
let layer = cp.m_specific_param.m_dec.m_layer;
let strict = cp.strict;
let mut core = crate::j2k::j2k_decode_tiles_parallel(
cp,
header,
num_tiles,
&tiles,
&cstr_index,
layer,
0,
strict,
Some(area_image),
area_image,
stream,
limits.effective_max_mem(),
)?;
if let CodecFormat::JP2(jp2) = &mut self.m_codec {
let mut manager = crate::event::EventMgr::default();
if crate::jp2::jp2_apply_color_postprocessing(jp2, &mut core, &mut manager).is_err() {
return None;
}
}
Some(core)
}
#[cfg(feature = "rayon")]
pub(crate) fn decode_parallel(
&mut self,
stream: &mut Stream,
header: &CoreImage,
layer: u32,
reduce: u32,
strict: bool,
) -> Option<CoreImage> {
let (cp, limits) = match &self.m_codec {
CodecFormat::J2K(j2k) => {
if j2k.m_header_partial {
return None;
}
(&j2k.m_cp, j2k.decode_limits)
}
CodecFormat::JP2(jp2) => {
if jp2.j2k.m_header_partial {
return None;
}
(&jp2.j2k.m_cp, jp2.j2k.decode_limits)
}
};
let info = self.cstr_info()?;
let num_tiles = info.tw.wrapping_mul(info.th);
if num_tiles <= 1 {
return None;
}
let cstr_index = self.cstr_index()?;
let tiles: Vec<u32> = (0..num_tiles).collect();
let mut merge = header.clone();
if reduce > 0 {
for comp in &mut merge.comps {
comp.factor = reduce;
}
let mut manager = crate::event::EventMgr::default();
if crate::j2k::j2k_update_image_dimensions(&mut merge, &mut manager).is_err() {
return None;
}
}
let mut core = crate::j2k::j2k_decode_tiles_parallel(
cp,
header,
num_tiles,
&tiles,
&cstr_index,
layer,
reduce,
strict,
None,
&merge,
stream,
limits.effective_max_mem(),
)?;
if let CodecFormat::JP2(jp2) = &mut self.m_codec {
let mut manager = crate::event::EventMgr::default();
if crate::jp2::jp2_apply_color_postprocessing(jp2, &mut core, &mut manager).is_err() {
return None;
}
}
Some(core)
}
}
impl Encoder {
pub fn new(format: J2KFormat) -> Result<Self> {
let m_codec = match format {
J2KFormat::J2K => CodecFormat::J2K(
j2k_create_compress().ok_or_else(|| Error::Encode("failed to create encoder".into()))?,
),
J2KFormat::JP2 => {
CodecFormat::JP2(
jp2_create(false).ok_or_else(|| Error::Encode("failed to create encoder".into()))?,
)
}
other => {
return Err(Error::Unsupported(format!(
"codec format {:?} is not supported for encoding",
other
)));
}
};
Ok(Encoder {
m_codec,
m_event_mgr: Default::default(),
})
}
pub fn setup(&mut self, parameters: &mut EncoderParameters, image: &mut CoreImage) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(enc) => j2k_setup_encoder(enc, parameters, image, &mut self.m_event_mgr),
CodecFormat::JP2(enc) => jp2_setup_encoder(enc, parameters, image, &mut self.m_event_mgr),
};
if ok.is_ok() {
Ok(())
} else {
Err(Error::Encode("setup_encoder failed".into()))
}
}
pub fn extra_options(&mut self, options: &[&str]) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(enc) => j2k_encoder_set_extra_options(enc, options, &mut self.m_event_mgr),
CodecFormat::JP2(enc) => jp2_encoder_set_extra_options(enc, options, &mut self.m_event_mgr),
};
if ok {
Ok(())
} else {
Err(Error::Encode("extra_options failed".into()))
}
}
pub fn start(&mut self, image: &mut CoreImage, stream: &mut Stream) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(enc) => j2k_start_compress(enc, stream, image, &mut self.m_event_mgr),
CodecFormat::JP2(enc) => jp2_start_compress(enc, stream, image, &mut self.m_event_mgr),
};
if ok.is_ok() {
Ok(())
} else {
Err(Error::Encode("start_compress failed".into()))
}
}
pub fn encode(&mut self, stream: &mut Stream) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(enc) => j2k_encode(enc, stream, &mut self.m_event_mgr),
CodecFormat::JP2(enc) => jp2_encode(enc, stream, &mut self.m_event_mgr),
};
if ok.is_ok() {
Ok(())
} else {
Err(Error::Encode("encode failed".into()))
}
}
pub fn finish(&mut self, stream: &mut Stream) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(enc) => j2k_end_compress(enc, stream, &mut self.m_event_mgr),
CodecFormat::JP2(enc) => jp2_end_compress(enc, stream, &mut self.m_event_mgr),
};
if ok.is_ok() {
Ok(())
} else {
Err(Error::Encode("end_compress failed".into()))
}
}
pub fn write_tile(&mut self, tile: u32, data: &[u8], stream: &mut Stream) -> Result<()> {
let ok = match &mut self.m_codec {
CodecFormat::J2K(enc) => j2k_write_tile(enc, tile, data, stream, &mut self.m_event_mgr),
CodecFormat::JP2(enc) => jp2_write_tile(enc, tile, data, stream, &mut self.m_event_mgr),
};
if ok.is_ok() {
Ok(())
} else {
Err(Error::Encode("write_tile failed".into()))
}
}
#[cfg(feature = "rayon")]
pub(crate) fn num_tiles(&self) -> u32 {
match &self.m_codec {
CodecFormat::J2K(j2k) => j2k.m_cp.tw.wrapping_mul(j2k.m_cp.th),
CodecFormat::JP2(jp2) => jp2.j2k.m_cp.tw.wrapping_mul(jp2.j2k.m_cp.th),
}
}
#[cfg(feature = "rayon")]
pub(crate) fn encode_parallel(&mut self, stream: &mut Stream) -> Option<bool> {
let j2k = match &mut self.m_codec {
CodecFormat::J2K(j2k) => j2k,
CodecFormat::JP2(jp2) => &mut jp2.j2k,
};
let num_tiles = j2k.m_cp.tw.wrapping_mul(j2k.m_cp.th);
if num_tiles <= 1 {
return None;
}
let mut manager = crate::event::EventMgr::default();
Some(crate::j2k::j2k_encode_tiles_parallel(j2k, stream, &mut manager).is_ok())
}
}