use std::cmp::min;
use std::io::Cursor;
use std::sync::Arc;
use crate::bitstream::BitStream;
use crate::components::{ComponentID, SubSampRatios};
use crate::errors::DecodeErrors;
use crate::marker::Marker;
use crate::worker::post_process;
use crate::{ColorSpace, Decoder};
pub const DCT_BLOCK: usize = 64;
impl Decoder
{
pub(crate) fn check_tables(&self) -> Result<(), DecodeErrors>
{
for i in 0..self.input_colorspace.num_components()
{
let _ = &self
.dc_huffman_tables
.get(self.components[i].dc_huff_table)
.as_ref()
.ok_or_else(|| {
DecodeErrors::HuffmanDecode(format!(
"No Huffman DC table for component {:?} ",
self.components[i].component_id
))
})?
.as_ref()
.ok_or_else(|| {
DecodeErrors::HuffmanDecode(format!(
"No DC table for component {:?}",
self.components[i].component_id
))
})?;
let _ = &self
.ac_huffman_tables
.get(self.components[i].ac_huff_table)
.as_ref()
.ok_or_else(|| {
DecodeErrors::HuffmanDecode(format!(
"No Huffman AC table for component {:?} ",
self.components[i].component_id
))
})?
.as_ref()
.ok_or_else(|| {
DecodeErrors::HuffmanDecode(format!(
"No AC table for component {:?}",
self.components[i].component_id
))
})?;
}
Ok(())
}
#[allow(clippy::similar_names,clippy::too_many_lines,clippy::cast_possible_truncation)]
#[inline(never)]
#[rustfmt::skip]
pub(crate) fn decode_mcu_ycbcr_baseline(
&mut self, reader: &mut Cursor<Vec<u8>>,
) -> Result<Vec<u8>, DecodeErrors>
{
self.check_component_dimensions()?;
self.check_tables()?;
let mut scoped_pools = scoped_threadpool::Pool::new(
self.options.get_threads());
info!("Created {} worker threads", scoped_pools.thread_count());
let (mut mcu_width, mut mcu_height);
let mut bias = 1;
if self.interleaved
{
self.set_upsampling()?;
if self.sub_sample_ratio == SubSampRatios::H
{
mcu_width = self.mcu_x * 2;
mcu_height = self.mcu_y / 2;
} else if self.sub_sample_ratio == SubSampRatios::HV
{
mcu_width = self.mcu_x;
mcu_height = self.mcu_y / 2;
bias = 2;
} else {
mcu_width = self.mcu_x;
mcu_height = self.mcu_y;
}
} else {
mcu_width = ((self.info.width + 7) / 8) as usize;
mcu_height = ((self.info.height + 7) / 8) as usize;
}
if self.input_colorspace == ColorSpace::GRAYSCALE && self.interleaved {
if self.options.get_strict_mode(){
return Err(DecodeErrors::FormatStatic("[strict-mode]: Grayscale image with down-sampled component."))
}
warn!("Grayscale image with down-sampled component, resetting component details");
mcu_width = ((self.info.width + 7) / 8) as usize;
self.h_max = 1;
self.options = self.options.set_out_colorspace(ColorSpace::GRAYSCALE);
self.v_max = 1;
self.sub_sample_ratio = SubSampRatios::None;
self.components[0].vertical_sample = 1;
self.components[0].width_stride = mcu_width * 8;
self.components[0].horizontal_sample = 1;
mcu_height = ((self.info.height + 7) / 8) as usize;
bias = 1;
}
let capacity = usize::from(self.info.width + 8) * usize::from(self.info.height + 8);
let component_capacity = mcu_width * DCT_BLOCK;
let global_component = Arc::new(self.components.clone());
let is_hv = self.sub_sample_ratio == SubSampRatios::HV;
let extra_space = usize::from(self.interleaved) * 128 * usize::from(self.height()) * self.options.get_out_colorspace().num_components();
let input = self.input_colorspace;
let output = self.options.get_out_colorspace();
let idct_func = self.idct_func;
let color_convert_16 = self.color_convert_16;
let width = usize::from(self.width());
let h_max = self.h_max;
let v_max = self.v_max;
let width_stride = (component_capacity * self.components[0].vertical_sample * self.components[0].horizontal_sample * bias) >> 1;
let hv_width_stride = width_stride >> 1;
let mut stream = BitStream::new();
let mut global_channel = vec![0; (capacity * self.options.get_out_colorspace().num_components()) + extra_space];
let mut chunks =
global_channel.chunks_exact_mut(width * output.num_components() * 8 * h_max * v_max);
let mut tmp = [0; DCT_BLOCK];
scoped_pools.scoped::<_, Result<(), DecodeErrors>>(|scope| {
for _ in 0..mcu_height
{
let mut temporary = [vec![], vec![], vec![]];
for (pos, comp) in self.components.iter().enumerate()
{
if min(self.options.get_out_colorspace().num_components() - 1, pos) == pos
{
let len = component_capacity * comp.vertical_sample * comp.horizontal_sample * bias;
temporary[pos] = vec![0; len];
}
}
for v in 0..bias
{
for j in 0..mcu_width
{
for pos in 0..self.input_colorspace.num_components()
{
let component = &mut self.components[pos];
let dc_table = self.dc_huffman_tables[component.dc_huff_table & 3]
.as_ref()
.ok_or_else(|| {
DecodeErrors::HuffmanDecode(format!(
"No DC table for component {:?}",
component.component_id
))
})?;
let ac_table = self.ac_huffman_tables[component.ac_huff_table & 3]
.as_ref()
.ok_or_else(|| {
DecodeErrors::HuffmanDecode(format!(
"No AC table for component {:?}",
component.component_id
))
})?;
for v_samp in 0..component.vertical_sample
{
for h_samp in 0..component.horizontal_sample
{
if min(self.options.get_out_colorspace().num_components() - 1, pos) == pos
{
let is_y =
usize::from(component.component_id == ComponentID::Y);
let y_offset = is_y
* v
* (hv_width_stride
+ (hv_width_stride * (component.vertical_sample - 1)));
let another_stride =
(width_stride * v_samp * usize::from(!is_hv))
+ hv_width_stride * v_samp * usize::from(is_hv);
let yet_another_stride = usize::from(is_hv)
* (width_stride >> 2)
* v
* usize::from(component.component_id != ComponentID::Y);
let start = (j * 64 * component.horizontal_sample)
+ (h_samp * 64)
+ another_stride
+ y_offset
+ yet_another_stride;
let tmp: &mut [i16; 64] = temporary.get_mut(pos).unwrap().get_mut(start..start + 64).unwrap().try_into().unwrap();
stream.decode_mcu_block(reader, dc_table, ac_table, tmp, &mut component.dc_pred)?;
} else {
stream.decode_mcu_block(reader, dc_table, ac_table, &mut tmp, &mut component.dc_pred)?;
}
}
}
self.todo = self.todo.wrapping_sub(1);
if self.todo == 0
{
self.handle_rst(&mut stream)?;
}
if let Some(m) = stream.marker
{
if m == Marker::EOI
{
break;
}
if let Marker::RST(_) = m { continue }
error!("Marker `{:?}` Found within Huffman Stream, possibly corrupt jpeg",m);
self.parse_marker_inner(m, reader)?;
}
}
}
}
let component = global_component.clone();
let next_chunk = chunks.next().unwrap();
scope.execute(move || {
let mut coeff :[&[i16];3]=[&[];3];
temporary.iter().enumerate().for_each(|(pos,x)|{
coeff[pos] = x;
});
post_process(&coeff, &component,
idct_func, color_convert_16,
input, output, next_chunk,
width);
});
}
Ok(())
})?;
info!("Finished decoding image");
global_channel.truncate(
usize::from(self.width())
* usize::from(self.height())
* self.options.get_out_colorspace().num_components(),
);
return Ok(global_channel);
}
#[cold]
pub(crate) fn handle_rst(&mut self, stream: &mut BitStream) -> Result<(), DecodeErrors>
{
self.todo = self.restart_interval;
if let Some(marker) = stream.marker
{
match marker
{
Marker::RST(_) =>
{
stream.reset();
self.components.iter_mut().for_each(|x| x.dc_pred = 0);
}
Marker::EOI =>
{
}
_ =>
{
return Err(DecodeErrors::MCUError(format!(
"Marker {:?} found in bitstream, possibly corrupt jpeg",
marker
)));
}
}
}
Ok(())
}
}