#![allow(clippy::doc_markdown)]
use std::fs::read;
use std::io::{BufRead, Cursor, Read};
use std::num::NonZeroU32;
use std::path::Path;
use crate::color_convert::choose_ycbcr_to_rgb_convert_func;
use crate::components::{ComponentID, Components, SubSampRatios};
use crate::errors::{DecodeErrors, UnsupportedSchemes};
use crate::headers::{parse_dqt, parse_huffman, parse_sos, parse_start_of_frame};
use crate::huffman::HuffmanTable;
use crate::idct::choose_idct_func;
use crate::marker::Marker;
use crate::misc::{read_byte, read_u16_be, Aligned32, ColorSpace, SOFMarkers};
use crate::upsampler::{
choose_horizontal_samp_function, choose_hv_samp_function, upsample_vertical,
};
use crate::ZuneJpegOptions;
pub(crate) const MAX_COMPONENTS: usize = 4;
pub(crate) const MAX_DIMENSIONS: usize = 1 << 27;
pub type ColorConvert16Ptr = fn(&[i16; 16], &[i16; 16], &[i16; 16], &mut [u8], &mut usize);
pub type IDCTPtr = fn(&[i16], &Aligned32<[i32; 64]>, usize, usize, usize) -> Vec<i16>;
#[allow(clippy::upper_case_acronyms)]
pub struct Decoder
{
pub(crate) info: ImageInfo,
pub(crate) qt_tables: [Option<[i32; 64]>; MAX_COMPONENTS],
pub(crate) dc_huffman_tables: [Option<HuffmanTable>; MAX_COMPONENTS],
pub(crate) ac_huffman_tables: [Option<HuffmanTable>; MAX_COMPONENTS],
pub(crate) components: Vec<Components>,
pub(crate) h_max: usize,
pub(crate) v_max: usize,
pub(crate) mcu_width: usize,
pub(crate) mcu_height: usize,
pub(crate) mcu_x: usize,
pub(crate) mcu_y: usize,
pub(crate) interleaved: bool,
pub(crate) sub_sample_ratio: SubSampRatios,
pub(crate) input_colorspace: ColorSpace,
pub(crate) is_progressive: bool,
pub(crate) spec_start: u8,
pub(crate) spec_end: u8,
pub(crate) succ_high: u8,
pub(crate) succ_low: u8,
pub(crate) num_scans: u8,
pub(crate) idct_func: IDCTPtr,
pub(crate) color_convert_16: ColorConvert16Ptr,
pub(crate) z_order: [usize; 4],
pub(crate) restart_interval: usize,
pub(crate) todo: usize,
pub(crate) options: ZuneJpegOptions,
}
impl Decoder
{
fn default(options: ZuneJpegOptions) -> Self
{
let color_convert =
choose_ycbcr_to_rgb_convert_func(ColorSpace::RGB, options.get_use_unsafe()).unwrap();
Decoder {
info: ImageInfo::default(),
qt_tables: [None, None, None, None],
dc_huffman_tables: [None, None, None, None],
ac_huffman_tables: [None, None, None, None],
components: vec![],
h_max: 1,
v_max: 1,
mcu_height: 0,
mcu_width: 0,
mcu_x: 0,
mcu_y: 0,
interleaved: false,
sub_sample_ratio: SubSampRatios::None,
is_progressive: false,
spec_start: 0,
spec_end: 0,
succ_high: 0,
succ_low: 0,
num_scans: 0,
idct_func: choose_idct_func(options.get_use_unsafe()),
color_convert_16: color_convert,
input_colorspace: ColorSpace::YCbCr,
z_order: [0; 4],
restart_interval: 0,
todo: 0x7fff_ffff,
options,
}
}
pub fn decode_buffer(&mut self, buf: &[u8]) -> Result<Vec<u8>, DecodeErrors>
{
self.decode_internal(Cursor::new(buf.to_vec()))
}
#[must_use]
#[allow(clippy::new_without_default)]
pub fn new() -> Decoder
{
Decoder::default(ZuneJpegOptions::new())
}
pub fn decode_file<P>(&mut self, file: P) -> Result<Vec<u8>, DecodeErrors>
where
P: AsRef<Path> + Clone,
{
let buffer = Cursor::new(read(file)?);
info!("File size: {} bytes", buffer.get_ref().len());
self.decode_internal(buffer)
}
#[must_use]
pub fn info(&self) -> Option<ImageInfo>
{
if self.info == ImageInfo::default()
{
return None;
}
return Some(self.info.clone());
}
fn decode_headers_internal<R>(&mut self, buf: &mut R) -> Result<(), DecodeErrors>
where
R: Read + BufRead,
{
let magic_bytes = read_u16_be(buf)?;
let mut last_byte = 0;
let mut bytes_before_marker = 0;
if magic_bytes != 0xffd8
{
return Err(DecodeErrors::IllegalMagicBytes(magic_bytes));
}
loop
{
let m = read_byte(buf)?;
if last_byte == 0xFF
{
let marker = Marker::from_u8(m);
bytes_before_marker = 0;
if let Some(n) = marker
{
self.parse_marker_inner(n, buf)?;
if n == Marker::SOS
{
return Ok(());
}
}
else
{
warn!("Marker 0xFF{:X} not known", m);
let length = read_u16_be(buf)?;
if length < 2
{
return Err(DecodeErrors::Format(format!(
"Found a marker with invalid length : {}",
length
)));
}
warn!("Skipping {} bytes", length - 2);
buf.consume((length - 2) as usize);
}
}
last_byte = m;
bytes_before_marker += 1;
if self.options.get_strict_mode() && bytes_before_marker > 3
{
return Err(DecodeErrors::FormatStatic(
"[strict-mode]: Extra bytes between headers",
));
}
}
}
pub(crate) fn parse_marker_inner<R: Read + BufRead>(
&mut self, m: Marker, buf: &mut R,
) -> Result<(), DecodeErrors>
{
match m
{
Marker::SOF(0 | 2) =>
{
let marker = {
if m == Marker::SOF(0)
{
SOFMarkers::BaselineDct
}
else
{
self.is_progressive = true;
SOFMarkers::ProgressiveDctHuffman
}
};
info!("Image encoding scheme =`{:?}`", marker);
parse_start_of_frame(buf, marker, self)?;
}
Marker::SOF(v) =>
{
let feature = UnsupportedSchemes::from_int(v);
if let Some(feature) = feature
{
return Err(DecodeErrors::Unsupported(feature));
}
return Err(DecodeErrors::Format("Unsupported image format".to_string()));
}
Marker::DQT =>
{
parse_dqt(self, buf)?;
}
Marker::DHT =>
{
parse_huffman(self, buf)?;
}
Marker::SOS =>
{
parse_sos(buf, self)?;
return Ok(());
}
Marker::EOI => return Err(DecodeErrors::Format("Premature End of image".to_string())),
Marker::DAC | Marker::DNL =>
{
return Err(DecodeErrors::Format(format!(
"Parsing of the following header `{:?}` is not supported,\
cannot continue",
m
)));
}
Marker::DRI =>
{
info!("DRI marker present");
if read_u16_be(buf)? != 4
{
return Err(DecodeErrors::Format(
"Bad DRI length, Corrupt JPEG".to_string(),
));
}
self.restart_interval = usize::from(read_u16_be(buf)?);
self.todo = self.restart_interval;
}
_ =>
{
warn!(
"Capabilities for processing marker \"{:?}\" not implemented",
m
);
let length = read_u16_be(buf)?;
if length < 2
{
return Err(DecodeErrors::Format(format!(
"Found a marker with invalid length:{}\n",
length
)));
}
warn!("Skipping {} bytes", length - 2);
buf.consume((length - 2) as usize);
}
}
Ok(())
}
#[must_use]
pub fn get_output_colorspace(&self) -> ColorSpace
{
return self.options.get_out_colorspace();
}
fn decode_internal(&mut self, buf: Cursor<Vec<u8>>) -> Result<Vec<u8>, DecodeErrors>
{
let mut buf = buf;
self.decode_headers_internal(&mut buf)?;
if self.is_progressive
{
self.decode_mcu_ycbcr_progressive(&mut buf)
}
else
{
self.decode_mcu_ycbcr_baseline(&mut buf)
}
}
pub fn read_headers(&mut self, buf: &[u8]) -> Result<(), DecodeErrors>
{
let mut cursor = Cursor::new(buf);
self.decode_headers_internal(&mut cursor)?;
Ok(())
}
#[must_use]
pub fn new_with_options(options: ZuneJpegOptions) -> Decoder
{
Decoder::default(options)
}
pub(crate) fn set_upsampling(&mut self) -> Result<(), DecodeErrors>
{
if self.h_max == self.v_max && self.h_max == 1
{
return Ok(());
}
match (self.h_max, self.v_max)
{
(2, 1) =>
{
self.sub_sample_ratio = SubSampRatios::H;
info!("Horizontal sub-sampling (2,1)");
let up_sampler = choose_horizontal_samp_function(self.options.get_use_unsafe());
self.components[1..]
.iter_mut()
.for_each(|x| x.up_sampler = up_sampler);
}
(1, 2) =>
{
self.sub_sample_ratio = SubSampRatios::V;
info!("Vertical sub-sampling (1,2)");
self.components[1..]
.iter_mut()
.for_each(|x| x.up_sampler = upsample_vertical);
}
(2, 2) =>
{
self.sub_sample_ratio = SubSampRatios::HV;
info!("Vertical and horizontal sub-sampling(2,2)");
self.components[1..].iter_mut().for_each(|x| {
x.up_sampler = choose_hv_samp_function(self.options.get_use_unsafe());
});
}
(_, _) =>
{
return Err(DecodeErrors::Format(
"Unknown down-sampling method, cannot continue".to_string(),
));
}
}
return Ok(());
}
#[deprecated(
since = "0.2.0",
note = "Set options in the ZuneJpegOptions struct and then use new_with_options"
)]
pub fn rgba(&mut self)
{
self.options = self.options.set_out_colorspace(ColorSpace::RGBA);
}
#[deprecated(
since = "0.2.0",
note = "Set options in the ZuneJpegOptions struct and then use new_with_options"
)]
pub fn set_limits(&mut self, width: u16, height: u16)
{
self.options = self.options.set_max_width(width).set_max_height(height);
}
#[deprecated(
since = "0.2.0",
note = "Set options in the ZuneJpegOptions struct and then use new_with_options"
)]
pub fn set_output_colorspace(&mut self, colorspace: ColorSpace)
{
self.options = self.options.set_out_colorspace(colorspace);
}
#[must_use]
pub fn width(&self) -> u16
{
self.info.width
}
#[must_use]
pub fn height(&self) -> u16
{
self.info.height
}
#[deprecated(since = "0.2.0", note = "Use new_with_options to set options")]
#[allow(clippy::cast_possible_truncation)]
pub fn set_num_threads(&mut self, threads: usize) -> Result<(), DecodeErrors>
{
if threads == 0
{
return Err(DecodeErrors::FormatStatic(
"Cannot set zero threads to decode image",
));
}
self.options = self
.options
.set_num_threads(NonZeroU32::new(threads as u32).unwrap());
Ok(())
}
pub(crate) fn check_component_dimensions(&self) -> Result<(), DecodeErrors>
{
let y_comp = self
.components
.iter()
.find(|c| c.component_id == ComponentID::Y)
.ok_or(DecodeErrors::FormatStatic(
"Could not find Y component for the image",
))?;
let y_width = y_comp.width_stride;
let cb_cr_width = y_width / self.h_max;
for comp in &self.components
{
if comp.component_id == ComponentID::Y
{
continue;
}
if comp.width_stride != cb_cr_width
{
return Err(DecodeErrors::Format(format!("Invalid image width and height stride for component {:?}, expected {}, but found {}", comp.component_id, cb_cr_width, comp.width_stride)));
}
if (comp.horizontal_sample != 1 || comp.vertical_sample != 1)
&& comp.component_id != ComponentID::Y
{
return Err(DecodeErrors::Format(format!(
"Invalid component sample for component {:?}, expected (1,1), found ({},{})",
comp.component_id, comp.vertical_sample, comp.horizontal_sample
)));
}
}
Ok(())
}
}
#[derive(Default, Clone, Eq, PartialEq)]
#[allow(clippy::module_name_repetitions)]
pub struct ImageInfo
{
pub width: u16,
pub height: u16,
pub pixel_density: u8,
pub sof: SOFMarkers,
pub x_density: u16,
pub y_density: u16,
pub components: u8,
}
impl ImageInfo
{
pub(crate) fn set_width(&mut self, width: u16)
{
self.width = width;
}
pub(crate) fn set_height(&mut self, height: u16)
{
self.height = height;
}
pub(crate) fn set_density(&mut self, density: u8)
{
self.pixel_density = density;
}
pub(crate) fn set_sof_marker(&mut self, marker: SOFMarkers)
{
self.sof = marker;
}
#[allow(dead_code)]
pub(crate) fn set_x(&mut self, sample: u16)
{
self.x_density = sample;
}
#[allow(dead_code)]
pub(crate) fn set_y(&mut self, sample: u16)
{
self.y_density = sample;
}
}