team-ljyzipelo

공개
963줄40 KB
1/*
2 * Copyright (c) 2023.
3 *
4 * This software is free software;
5 *
6 * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
7 */
8
9use alloc::vec::Vec;
10use alloc::{format, vec};
11use core::cmp::min;
12
13use zune_core::bytestream::ZByteReaderTrait;
14use zune_core::colorspace::ColorSpace;
15use zune_core::colorspace::ColorSpace::Luma;
16use zune_core::log::{error, trace, warn};
17
18use crate::bitstream::BitStream;
19use crate::components::SampleRatios;
20use crate::decoder::MAX_COMPONENTS;
21use crate::errors::DecodeErrors;
22use crate::marker::Marker;
23use crate::mcu_prog::get_marker;
24use crate::misc::{calculate_padded_width, setup_component_params};
25use crate::worker::{color_convert, upsample};
26use crate::JpegDecoder;
27
28/// The size of a DC block for a MCU.
29
30pub const DCT_BLOCK: usize = 64;
31
32impl<T: ZByteReaderTrait> JpegDecoder<T> {
33 /// Check for existence of DC and AC Huffman Tables
34 pub(crate) fn check_tables(&self) -> Result<(), DecodeErrors> {
35 // check that dc and AC tables exist outside the hot path
36 for component in &self.components {
37 let _ = &self
38 .dc_huffman_tables
39 .get(component.dc_huff_table)
40 .as_ref()
41 .ok_or_else(|| {
42 DecodeErrors::HuffmanDecode(format!(
43 "No Huffman DC table for component {:?} ",
44 component.component_id
45 ))
46 })?
47 .as_ref()
48 .ok_or_else(|| {
49 DecodeErrors::HuffmanDecode(format!(
50 "No DC table for component {:?}",
51 component.component_id
52 ))
53 })?;
54
55 let _ = &self
56 .ac_huffman_tables
57 .get(component.ac_huff_table)
58 .as_ref()
59 .ok_or_else(|| {
60 DecodeErrors::HuffmanDecode(format!(
61 "No Huffman AC table for component {:?} ",
62 component.component_id
63 ))
64 })?
65 .as_ref()
66 .ok_or_else(|| {
67 DecodeErrors::HuffmanDecode(format!(
68 "No AC table for component {:?}",
69 component.component_id
70 ))
71 })?;
72 }
73 Ok(())
74 }
75
76 /// Decode MCUs and carry out post processing.
77 ///
78 /// This is the main decoder loop for the library, the hot path.
79 ///
80 /// Because of this, we pull in some very crazy optimization tricks hence readability is a pinch
81 /// here.
82 #[allow(
83 clippy::similar_names,
84 clippy::too_many_lines,
85 clippy::cast_possible_truncation
86 )]
87 #[inline(never)]
88 pub(crate) fn decode_mcu_ycbcr_baseline(
89 &mut self, pixels: &mut [u8]
90 ) -> Result<(), DecodeErrors> {
91 setup_component_params(self)?;
92
93 // check dc and AC tables
94 self.check_tables()?;
95
96 let (mut mcu_width, mut mcu_height);
97
98 if self.is_interleaved {
99 // set upsampling functions
100 self.set_upsampling()?;
101
102 mcu_width = self.mcu_x;
103 mcu_height = self.mcu_y;
104 } else {
105 // For non-interleaved images( (1*1) subsampling)
106 // number of MCU's are the widths (+7 to account for paddings) divided bu 8.
107 mcu_width = (self.info.width as usize + 7) / 8;
108 mcu_height = (self.info.height as usize + 7) / 8;
109 }
110 if self.is_interleaved
111 && self.input_colorspace.num_components() > 1
112 && self.options.jpeg_get_out_colorspace().num_components() == 1
113 && (self.info.sample_ratio == SampleRatios::V
114 || self.info.sample_ratio == SampleRatios::HV)
115 {
116 // For a specific set of images, e.g interleaved,
117 // when converting from YcbCr to grayscale, we need to
118 // take into account mcu height since the MCU decoding needs to take
119 // it into account for padding purposes and the post processor
120 // parses two rows per mcu width.
121 //
122 // set coeff to be 2 to ensure that we increment two rows
123 // for every mcu processed also
124 mcu_height *= self.v_max;
125 mcu_height /= self.h_max;
126 self.coeff = 2;
127 }
128
129 if self.input_colorspace == ColorSpace::Luma && self.is_interleaved {
130 warn!("Grayscale image with down-sampled component, resetting component details");
131
132 self.reset_params();
133
134 mcu_width = ((self.info.width + 7) / 8) as usize;
135 mcu_height = ((self.info.height + 7) / 8) as usize;
136 }
137 let width = usize::from(self.info.width);
138
139 let padded_width = calculate_padded_width(width, self.info.sample_ratio);
140
141 let mut stream = BitStream::new();
142 let mut tmp = [0_i32; DCT_BLOCK];
143
144 let comp_len = self.components.len();
145
146 for (pos, comp) in self.components.iter_mut().enumerate() {
147 // Allocate only needed components.
148 //
149 // For special colorspaces i.e YCCK and CMYK, just allocate all of the needed
150 // components.
151 if min(
152 self.options.jpeg_get_out_colorspace().num_components() - 1,
153 pos
154 ) == pos
155 || comp_len == 4
156 // Special colorspace
157 {
158 // allocate enough space to hold a whole MCU width
159 // this means we should take into account sampling ratios
160 // `*8` is because each MCU spans 8 widths.
161 let len = comp.width_stride * comp.vertical_sample * 8;
162
163 comp.needed = true;
164 comp.raw_coeff = vec![0; len];
165 } else {
166 comp.needed = false;
167 }
168 }
169
170 // If all components are contained in the first scan of MCUs, then we can process into
171 // (upsampled) pixels immediately after each MCU, for convenience we use each row of MCUS.
172 // Otherwise, we must first wait until following SOS provide the remaining components.
173 let all_components_in_first_scan = usize::from(self.num_scans) == self.components.len();
174 let mut progressive_mcus: [Vec<i16>; 4] = core::array::from_fn(|_| vec![]);
175
176 if !all_components_in_first_scan {
177 for (component, mcu) in self.components.iter().zip(&mut progressive_mcus) {
178 let len = mcu_width
179 * component.vertical_sample
180 * component.horizontal_sample
181 * mcu_height
182 * 64;
183 *mcu = vec![0; len];
184 }
185 }
186
187 let mut pixels_written = 0;
188
189 let is_hv = usize::from(self.is_interleaved);
190 let upsampler_scratch_size = is_hv * self.components.iter().map(|x| x.width_stride).max().unwrap_or(0) * 8;
191 let mut upsampler_scratch_space = vec![0; upsampler_scratch_size];
192
193 'sos: loop {
194 trace!(
195 "Baseline decoding of components: {:?}",
196 &self.z_order[..usize::from(self.num_scans)]
197 );
198
199 trace!("Decoding MCU width: {mcu_width}, height: {mcu_height}");
200
201 for i in 0..mcu_height {
202 if stream.overread_by > 0 {
203 pixels.get_mut(pixels_written..).map(|v| v.fill(128));
204 if self.options.strict_mode() {
205 return Err(DecodeErrors::FormatStatic("Premature end of buffer"));
206 };
207
208 error!("Premature end of buffer");
209 break;
210 }
211
212 // decode a whole MCU width,
213 // this takes into account interleaved components.
214 let terminate = if all_components_in_first_scan {
215 self.decode_mcu_width::<false>(
216 mcu_width,
217 i,
218 &mut tmp,
219 &mut stream,
220 &mut progressive_mcus
221 )?
222 } else {
223 /* NB: (cae). This code was added due to the issue at https://github.com/etemesi254/zune-image/issues/277
224 *
225 * There is a particular set of images that interleave the start of scan (SOS) with the MCU,
226 * E.g if it's a three component image, we have SOS->MCU ->SOS->MCU ->SOS->MCU
227 * which presents a problem on decoding, we need to buffer the whole image before continuing since
228 * we won't have a row containing all the component data which will be needed e.g for color conversion.
229 *
230 * The mechanisms is that we decode the whole image upfront, which goes against the normal
231 * routine of decoding MCU width , so this requires more memory upfront than initial routines
232 * but it is a single image out of the many corpuses that exist, so its fine.
233 * (image in test-images/jpeg/sos_news.jpeg)
234
235 * Code contributed by Aurelia Molzer (https://github.com/197g)
236
237 *
238 */
239
240 self.decode_mcu_width::<true>(
241 mcu_width,
242 i,
243 &mut tmp,
244 &mut stream,
245 &mut progressive_mcus
246 )?
247 };
248
249 // process that width up until it's impossible. This is faster than allocation the
250 // full components, which we skipped earlier.
251 if all_components_in_first_scan {
252 self.post_process(
253 pixels,
254 i,
255 mcu_height,
256 width,
257 padded_width,
258 &mut pixels_written,
259 &mut upsampler_scratch_space
260 )?;
261 }
262
263 match terminate {
264 McuContinuation::Ok => {}
265 McuContinuation::AnotherSos if all_components_in_first_scan => {
266 warn!("More than one SOS despite already having all components");
267 return Ok(());
268 }
269 McuContinuation::AnotherSos => continue 'sos,
270 McuContinuation::InterScanMarker(marker) => {
271 // Handle inter-scan markers (DHT/DQT/etc) uniformly here.
272 // This keeps all marker handling in the outer loop.
273 if self.advance_to_next_sos(marker, &mut stream)? {
274 continue 'sos;
275 } else {
276 // Hit EOI
277 break;
278 }
279 }
280 McuContinuation::Terminate => {
281 warn!("Got terminate signal, will not process further");
282 pixels.get_mut(pixels_written..).map(|v| v.fill(128));
283 return Ok(());
284 }
285 }
286 }
287
288 // Breaks if we get here, looping only if we have restarted, i.e. found another SOS and
289 // continued at `'sos'.
290 break;
291 }
292
293 if !all_components_in_first_scan {
294 self.finish_baseline_decoding(&progressive_mcus, mcu_width, pixels)?;
295 }
296
297 // it may happen that some images don't have the whole buffer
298 // so we can't panic in case of that
299 // assert_eq!(pixels_written, pixels.len());
300
301 if all_components_in_first_scan && pixels_written != pixels.len() {
302 return Err(DecodeErrors::FormatStatic("Incomplete decoded image buffer"));
303 }
304
305 // For UHD usecases that tie two images separating them with EOI and
306 // SOI markers, it may happen that we do not reach this image end of image
307 // So this ensures we reach it
308 // Ensure we read EOI
309 if !stream.seen_eoi {
310 let marker = get_marker(&mut self.stream, &mut stream);
311 match marker {
312 Ok(_m) => {
313 trace!("Found marker {:?}", _m);
314 }
315 Err(_) => {
316 // ignore error
317 }
318 }
319 }
320
321 trace!("Finished decoding image");
322
323 Ok(())
324 }
325
326 /// Process all MCUs when baseline decoding has been processing them component-after-component.
327 /// For simplicity this assembles the dequantized blocks in the order that the post processing
328 /// of an interleaved baseline decoding would use.
329 #[allow(clippy::too_many_lines)]
330 #[allow(clippy::cast_sign_loss)]
331 pub(crate) fn finish_baseline_decoding(
332 &mut self, block: &[Vec<i16>; MAX_COMPONENTS], _mcu_width: usize, pixels: &mut [u8]
333 ) -> Result<(), DecodeErrors> {
334 let mcu_height = self.mcu_y;
335
336 // Size of our output image(width*height)
337 let is_hv = usize::from(self.is_interleaved);
338 let upsampler_scratch_size = is_hv * self.components[0].width_stride;
339 let width = usize::from(self.info.width);
340 let padded_width = calculate_padded_width(width, self.info.sample_ratio);
341
342 let mut upsampler_scratch_space = vec![0; upsampler_scratch_size];
343
344 for (pos, comp) in self.components.iter_mut().enumerate() {
345 // Mark only needed components for computing output colors.
346 if min(
347 self.options.jpeg_get_out_colorspace().num_components() - 1,
348 pos
349 ) == pos
350 || self.input_colorspace == ColorSpace::YCCK
351 || self.input_colorspace == ColorSpace::CMYK
352 {
353 comp.needed = true;
354 } else {
355 comp.needed = false;
356 }
357 }
358
359 let mut pixels_written = 0;
360
361 // dequantize and idct have been performed, only color convert.
362 for i in 0..mcu_height {
363 // All the data is already in the right order, we just need to be able to pass it to
364 // the post_process & upsample method. That expects all the data to be stored as one
365 // row of MCUs in each component's `raw_coeff`.
366 'component: for (position, component) in &mut self.components.iter_mut().enumerate() {
367 if !component.needed {
368 continue 'component;
369 }
370
371 // step is the number of pixels this iteration wil be handling
372 // Given by the number of mcu's height and the length of the component block
373 // Since the component block contains the whole channel as raw pixels
374 // we this evenly divides the pixels into MCU blocks
375 //
376 // For interleaved images, this gives us the exact pixels comprising a whole MCU
377 // block
378 let step = block[position].len() / mcu_height;
379
380 // where we will be reading our pixels from.
381 let slice = &block[position][i * step..][..step];
382 let temp_channel = &mut component.raw_coeff;
383 temp_channel[..step].copy_from_slice(slice);
384 }
385
386 // process that whole stripe of MCUs
387 self.post_process(
388 pixels,
389 i,
390 mcu_height,
391 width,
392 padded_width,
393 &mut pixels_written,
394 &mut upsampler_scratch_space
395 )?;
396 }
397
398 return Ok(());
399 }
400
401 fn decode_mcu_width<const PROGRESSIVE: bool>(
402 &mut self, mcu_width: usize, mcu_height: usize, tmp: &mut [i32; 64],
403 stream: &mut BitStream, progressive: &mut [Vec<i16>; 4]
404 ) -> Result<McuContinuation, DecodeErrors> {
405 let is_one_by_one = !self.scan_subsampled;
406
407 // The definition of MCU depends on the sampling factor of involved scans. When components
408 // have different factors then each Minimal-Coding-Unit is the least common multiple such
409 // that we have an integer number of blocks from each component. But the decoding of these
410 // components differs from it otherwise, we need an inner loop with a dynamic amount of
411 // coefficients per component, whereas otherwise we have exactly one block of coefficients
412 // encoded for each component in the bitstream order.
413 //
414 // We statically specialize on this to improve code generation of the common case a little
415 // bit. We could also special case common sub-sampling cases but be mindful of code bloat.
416 if is_one_by_one {
417 self.inner_decode_mcu_width::<PROGRESSIVE, false>(
418 mcu_width,
419 mcu_height,
420 tmp,
421 stream,
422 progressive
423 )
424 } else {
425 self.inner_decode_mcu_width::<PROGRESSIVE, true>(
426 mcu_width,
427 mcu_height,
428 tmp,
429 stream,
430 progressive
431 )
432 }
433 }
434
435 // Inline-never ensures we do get this function optimize on its own, into two different
436 // versions, without the optimizer tripping up over the complexity that comes with the
437 // constant folding. And constant folding is quite important for performance here as
438 // when `not SAMPLED` then the inner loop has exactly one iteration per component in
439 // the scan. The difference was ~1% or a bit more.
440 fn inner_decode_mcu_width<const PROGRESSIVE: bool, const SAMPLED: bool>(
441 &mut self, mcu_width: usize, mcu_height: usize, tmp: &mut [i32; 64],
442 stream: &mut BitStream, progressive: &mut [Vec<i16>; 4]
443 ) -> Result<McuContinuation, DecodeErrors> {
444 let z_order = self.z_order;
445 let z_scans = &z_order[..usize::from(self.num_scans)];
446
447 // How much of the head of `tmp` was written by the last MCU decoding? We only check for
448 // two different cases and not all possible outcomes as this is only used to optimize the
449 // bytes written in `fill`. Since the clobber happens in UNZIGZAG order we'd be straddling
450 // most cache lines anyways even if we did a partial write with the exact length of the
451 // coefficient data which was written into `tmp`.
452 let mut clobber_more_than_4x4 = true;
453
454 // For non-interleaved scans (PROGRESSIVE=true), each scan contains a single component
455 // and we iterate over that component's actual data unit count, not the interleaved MCU
456 // width multiplied by sampling factor.
457 let mut scan_du_width = if PROGRESSIVE {
458 let k = z_scans[0];
459 let comp = &self.components[k];
460 // Calculate actual data units for this component: ceil(width / (8 * subsampling_ratio))
461 (self.info.width as usize * comp.horizontal_sample + self.h_max * 8 - 1)
462 / (self.h_max * 8)
463 } else {
464 mcu_width
465 };
466 // In malformed scans that list multiple components, clamp to the smallest row capacity
467 // to avoid writing past the row buffer.
468 if PROGRESSIVE && z_scans.len() > 1 {
469 let min_du = z_scans
470 .iter()
471 .map(|&k| self.components[k].width_stride / 8)
472 .min()
473 .unwrap_or(0);
474 scan_du_width = scan_du_width.min(min_du);
475 }
476
477 for j in 0..scan_du_width {
478 // iterate over components
479 for &k in z_scans {
480 // we made this loop body massive due to several different paths that depend on
481 // static conditions. Note we (potentially) call into other functions so the
482 // compiler will not unroll anything here anyways. The gains from separating
483 // differently optimized loop bodies are much greater than a single additional jump
484 // here.
485 let component = &mut self.components[k];
486
487 let dc_table = self.dc_huffman_tables[component.dc_huff_table % MAX_COMPONENTS]
488 .as_ref()
489 .ok_or(DecodeErrors::FormatStatic("DC table not found"))?;
490
491 let ac_table = self.ac_huffman_tables[component.ac_huff_table % MAX_COMPONENTS]
492 .as_ref()
493 .ok_or(DecodeErrors::FormatStatic("AC table not found"))?;
494
495 let qt_table = &component.quantization_table;
496 let channel = if PROGRESSIVE {
497 let offset =
498 mcu_height * component.width_stride * 8 * component.vertical_sample;
499 // Small stopgap for https://github.com/etemesi254/zune-image/issues/362
500 if offset >= progressive[k].len(){
501 return Err(DecodeErrors::FormatStatic("Would panic on slice iteration"))
502 }
503 &mut progressive[k][offset..]
504 } else {
505 &mut component.raw_coeff
506 };
507
508 let component_samples_needed = component.needed;
509
510 // If image is interleaved iterate over scan components,
511 // otherwise if it-s non-interleaved, these routines iterate in
512 // trivial scanline order(Y,Cb,Cr)
513 //
514 // Turn the bounds into a compile time constant for a common special case. This
515 // allows the compiler to unroll the loop and then do a bunch of interleaving.
516 //
517 // For PROGRESSIVE (non-interleaved), we iterate data units directly so
518 // h_samp/v_samp loops run exactly once.
519 let v_step =
520 if SAMPLED && !PROGRESSIVE { 0..component.vertical_sample } else { 0..1 };
521
522 for v_samp in v_step {
523 let h_step =
524 if SAMPLED && !PROGRESSIVE { 0..component.horizontal_sample } else { 0..1 };
525
526 for h_samp in h_step {
527 let result = if component_samples_needed {
528 // Fill the array with zeroes, decode_mcu_block expects
529 // a zero based array. Clobber is in zig-zag order though.
530 // Writing consecutive entries is basically free in terms
531 // of memory throughput so we opt for a larger power of
532 // two which lets the compiler turn this into a repeated
533 // write of a zeroed vector register, which does not have
534 // any branches, instead of a more difficult pattern where
535 // we attempt to overwrite exactly one coefficient.
536 let clobber_len = if !clobber_more_than_4x4 { 32 } else { 64 };
537
538 tmp[..clobber_len].fill(0);
539
540 stream.decode_mcu_block(
541 &mut self.stream,
542 dc_table,
543 ac_table,
544 qt_table,
545 tmp,
546 &mut component.dc_pred
547 )
548 } else {
549 // We do not touch tmp so there is no need to reset it.
550 stream.discard_mcu_block(&mut self.stream, dc_table, ac_table)
551 };
552
553 // If an error occurs we can either propagate it
554 // as an error or print it and call terminate.
555 //
556 // This allows even corrupt images to render something,
557 // even if its bad, matching browsers.
558 //
559 // See example in https://github.com/etemesi254/zune-image/issues/293
560 let len = if let Ok(len) = result {
561 len
562 } else {
563 // result.is_err()
564 return if self.options.strict_mode() {
565 Err(result.err().unwrap())
566 } else {
567 error!("{}", result.err().unwrap());
568 Ok(McuContinuation::Terminate)
569 };
570 };
571
572 if component_samples_needed {
573 // tmp was only written partially, note that len is in ZigZag order.
574 clobber_more_than_4x4 = len > 10;
575
576 let idct_position = if PROGRESSIVE {
577 // For non-interleaved, j indexes data units directly
578 j * 8
579 } else {
580 // derived from stb and rewritten for my tastes
581 let c2 = v_samp * 8;
582 let c3 = ((j * component.horizontal_sample) + h_samp) * 8;
583
584 component.width_stride * c2 + c3
585 };
586
587 let idct_pos = channel.get_mut(idct_position..).unwrap();
588
589 if len <= 1 {
590 (self.idct_1x1_func)(tmp, idct_pos, component.width_stride);
591 } else if len <= 10 {
592 (self.idct_4x4_func)(tmp, idct_pos, component.width_stride);
593 } else {
594 // call idct.
595 (self.idct_func)(tmp, idct_pos, component.width_stride);
596 }
597 }
598 }
599 }
600 }
601
602 self.todo = self.todo.wrapping_sub(1);
603
604 if self.todo == 0 {
605 self.handle_rst_main(stream)?;
606 continue;
607 }
608
609 if stream.marker.is_some() && stream.bits_left == 0 {
610 break;
611 }
612 }
613
614 stream.require_input()?;
615 self.check_stream_marker_after_mcu_width(stream)
616 }
617
618 fn check_stream_marker_after_mcu_width(
619 &mut self, stream: &mut BitStream
620 ) -> Result<McuContinuation, DecodeErrors> {
621 // After all interleaved components, that's an MCU
622 // handle stream markers
623 //
624 // In some corrupt images, it may occur that header markers occur in the stream.
625 // The spec EXPLICITLY FORBIDS this, specifically, in
626 // routine F.2.2.5 it says
627 // `The only valid marker which may occur within the Huffman coded data is the RSTm marker.`
628 //
629 // But libjpeg-turbo allows it because of some weird reason. so I'll also
630 // allow it because of some weird reason.
631 if let Some(m) = stream.marker {
632 if m == Marker::EOI {
633 // acknowledge and ignore EOI marker.
634 stream.marker.take();
635 trace!("Found EOI marker");
636 // Google Introduced the Ultra-HD image format which is basically
637 // stitching two images into one container.
638 // They basically separate two images via a EOI and SOI marker
639 // so let's just ensure if we ever see EOI, we never read past that
640 // ever.
641 // https://github.com/google/libultrahdr
642 stream.seen_eoi = true;
643 } else if let Marker::RST(_) = m {
644 //debug_assert_eq!(self.todo, 0);
645 if self.todo == 0 {
646 self.handle_rst(stream)?;
647 }
648 } else if let Marker::SOS = m {
649 self.parse_marker_inner(m)?;
650 stream.marker.take();
651 stream.reset();
652 trace!("Found SOS marker");
653 return Ok(McuContinuation::AnotherSos);
654 } else if matches!(m, Marker::DHT | Marker::DQT | Marker::DRI | Marker::COM)
655 || matches!(m, Marker::APP(_))
656 {
657 // For non-interleaved images, setup markers can appear between scans.
658 // Signal the caller to handle this marker and find the next SOS.
659 // This keeps all marker parsing in the caller's loop.
660 stream.marker.take();
661 trace!("Found inter-scan marker {:?}", m);
662 return Ok(McuContinuation::InterScanMarker(m));
663 } else {
664 if self.options.strict_mode() {
665 return Err(DecodeErrors::Format(format!(
666 "Marker {m:?} found where not expected"
667 )));
668 }
669 error!(
670 "Marker `{:?}` Found within Huffman Stream, possibly corrupt jpeg",
671 m
672 );
673
674 self.parse_marker_inner(m)?;
675 stream.marker.take();
676 stream.reset();
677 return Ok(McuContinuation::Terminate);
678 }
679 }
680
681 Ok(McuContinuation::Ok)
682 }
683
684 /// Scan for the next SOS marker, parsing setup markers along the way.
685 ///
686 /// This is the unified marker scanning function used after encountering an
687 /// inter-scan marker. It handles DHT, DQT, DRI, COM, and APP markers that
688 /// can appear between scans in non-interleaved images.
689 ///
690 /// # Arguments
691 /// * `first_marker` - The first marker that was already detected (not yet parsed)
692 /// * `stream` - The bitstream state
693 ///
694 /// # Returns
695 /// * `Ok(true)` - Found SOS, ready to continue decoding
696 /// * `Ok(false)` - Found EOI, decoding complete
697 /// * `Err(_)` - Error (too many markers, unexpected marker in strict mode, etc.)
698 fn advance_to_next_sos(
699 &mut self,
700 first_marker: Marker,
701 stream: &mut BitStream
702 ) -> Result<bool, DecodeErrors> {
703 // Limit iterations to prevent DoS from malicious files.
704 const MAX_INTER_SCAN_MARKERS: usize = 64;
705
706 // Parse the first marker that triggered this call
707 self.parse_marker_inner(first_marker)?;
708 stream.reset();
709
710 for _ in 0..MAX_INTER_SCAN_MARKERS {
711 let marker = get_marker(&mut self.stream, stream)?;
712
713 match marker {
714 Marker::SOS => {
715 self.parse_marker_inner(Marker::SOS)?;
716 stream.reset();
717 trace!("Found SOS marker, continuing decode");
718 return Ok(true);
719 }
720 Marker::EOI => {
721 stream.seen_eoi = true;
722 trace!("Found EOI marker");
723 return Ok(false);
724 }
725 Marker::DHT | Marker::DQT | Marker::DRI | Marker::COM => {
726 trace!("Parsing inter-scan marker {:?}", marker);
727 self.parse_marker_inner(marker)?;
728 }
729 Marker::APP(_) => {
730 trace!("Parsing inter-scan APP marker {:?}", marker);
731 self.parse_marker_inner(marker)?;
732 }
733 other => {
734 if self.options.strict_mode() {
735 return Err(DecodeErrors::Format(format!(
736 "Unexpected marker {:?} while scanning for SOS between scans",
737 other
738 )));
739 }
740 // Non-strict: skip unknown marker
741 warn!("Skipping unexpected marker {:?} between scans", other);
742 let length = self.stream.get_u16_be_err()?;
743 if length >= 2 {
744 self.stream.skip((length - 2) as usize)?;
745 }
746 }
747 }
748 }
749
750 Err(DecodeErrors::FormatStatic(
751 "Too many markers between scans (exceeded limit of 64)"
752 ))
753 }
754
755 // handle RST markers.
756 // No-op if not using restarts
757 // this routine is shared with mcu_prog
758 #[cold]
759 pub(crate) fn handle_rst(&mut self, stream: &mut BitStream) -> Result<(), DecodeErrors> {
760 stream.require_input()?;
761 self.todo = self.restart_interval;
762
763 if let Some(marker) = stream.marker {
764 // Found a marker
765 // Read stream and see what marker is stored there
766 match marker {
767 Marker::RST(_) => {
768 // reset stream
769 stream.reset();
770 // Initialize dc predictions to zero for all components
771 self.components.iter_mut().for_each(|x| x.dc_pred = 0);
772 // Start iterating again. from position.
773 }
774 Marker::EOI => {
775 // silent pass
776 }
777 // Valid markers that can appear between scans at a restart boundary
778 // (restart interval aligns with end of scan). Leave for caller.
779 Marker::SOS | Marker::DHT | Marker::DQT | Marker::DRI | Marker::COM
780 | Marker::APP(_) => {}
781 _ => {
782 if self.options.strict_mode() {
783 return Err(DecodeErrors::MCUError(format!(
784 "Unexpected marker {marker:?} at restart boundary"
785 )));
786 }
787 warn!("Unexpected marker {:?} at restart boundary", marker);
788 }
789 }
790 }
791 Ok(())
792 }
793 #[allow(clippy::too_many_lines, clippy::too_many_arguments)]
794 pub(crate) fn post_process(
795 &mut self, pixels: &mut [u8], i: usize, mcu_height: usize, width: usize,
796 padded_width: usize, pixels_written: &mut usize, upsampler_scratch_space: &mut [i16]
797 ) -> Result<(), DecodeErrors> {
798 let out_colorspace_components = self.options.jpeg_get_out_colorspace().num_components();
799
800 let mut px = *pixels_written;
801 // indicates whether image is vertically up-sampled
802 let is_vertically_sampled = self
803 .components
804 .iter()
805 .any(|c| c.sample_ratio == SampleRatios::HV || c.sample_ratio == SampleRatios::V);
806
807 let mut comp_len = self.components.len();
808
809 // If we are moving from YCbCr -> Luma, we do not allocate storage for other components, so we
810 // will panic when we are trying to read samples, so for that case,
811 // hardcode it so that we don't panic when doing
812 // *samp = &samples[j][pos * padded_width..(pos + 1) * padded_width]
813 if out_colorspace_components < comp_len && self.options.jpeg_get_out_colorspace() == Luma {
814 comp_len = out_colorspace_components;
815 }
816 let mut color_conv_function =
817 |num_iters: usize, samples: [&[i16]; 4]| -> Result<(), DecodeErrors> {
818 for (pos, output) in pixels[px..]
819 .chunks_exact_mut(width * out_colorspace_components)
820 .take(num_iters)
821 .enumerate()
822 {
823 let mut raw_samples: [&[i16]; 4] = [&[], &[], &[], &[]];
824
825 // iterate over each line, since color-convert needs only
826 // one line
827 for (j, samp) in raw_samples.iter_mut().enumerate().take(comp_len) {
828 let temp = &samples[j].get(pos * padded_width..(pos + 1) * padded_width);
829 if temp.is_none() {
830 return Err(DecodeErrors::FormatStatic("Missing samples"));
831 }
832 *samp = temp.unwrap();
833 }
834 color_convert(
835 &raw_samples,
836 self.color_convert_16,
837 self.input_colorspace,
838 self.options.jpeg_get_out_colorspace(),
839 output,
840 width,
841 padded_width
842 )?;
843 px += width * out_colorspace_components;
844 }
845 Ok(())
846 };
847
848 let comps = &mut self.components[..];
849
850 if self.is_interleaved && self.options.jpeg_get_out_colorspace() != ColorSpace::Luma {
851 for comp in comps.iter_mut() {
852 upsample(
853 comp,
854 mcu_height,
855 i,
856 upsampler_scratch_space,
857 is_vertically_sampled
858 )?;
859 }
860
861 if is_vertically_sampled {
862 if i > 0 {
863 // write the last line, it wasn't up-sampled as we didn't have row_down
864 // yet
865 let mut samples: [&[i16]; 4] = [&[], &[], &[], &[]];
866
867 for (samp, component) in samples.iter_mut().zip(comps.iter()) {
868 *samp = &component.first_row_upsample_dest;
869 }
870
871 // ensure length matches for all samples
872 let _first_len = samples[0].len();
873
874 // This was a good check, but can be caused to panic, esp on invalid/corrupt images.
875 // See one in issue https://github.com/etemesi254/zune-image/issues/262, so for now
876 // we just ignore and generate invalid images at the end.
877
878 //
879 //
880 // for samp in samples.iter().take(comp_len) {
881 // assert_eq!(first_len, samp.len());
882 // }
883 let num_iters = self.coeff * self.v_max;
884
885 color_conv_function(num_iters, samples)?;
886 }
887
888 // After up-sampling the last row, save any row that can be used for
889 // a later up-sampling,
890 //
891 // E.g the Y sample is not sampled but we haven't finished upsampling the last row of
892 // the previous mcu, since we don't have the down row, so save it
893 for component in comps.iter_mut() {
894 if component.sample_ratio != SampleRatios::H {
895 // We don't care about H sampling factors, since it's copied in the workers function
896
897 // copy last row to be used for the next color conversion
898 let size = component.vertical_sample
899 * component.width_stride
900 * component.sample_ratio.sample();
901
902 let last_bytes =
903 component.raw_coeff.rchunks_exact_mut(size).next().unwrap();
904
905 component
906 .first_row_upsample_dest
907 .copy_from_slice(last_bytes);
908 }
909 }
910 }
911
912 let mut samples: [&[i16]; 4] = [&[], &[], &[], &[]];
913
914 for (samp, component) in samples.iter_mut().zip(comps.iter()) {
915 *samp = if component.sample_ratio == SampleRatios::None {
916 &component.raw_coeff
917 } else {
918 &component.upsample_dest
919 };
920 }
921
922 // we either do 7 or 8 MCU's depending on the state, this only applies to
923 // vertically sampled images
924 //
925 // for rows up until the last MCU, we do not upsample the last stride of the MCU
926 // which means that the number of iterations should take that into account is one less the
927 // up-sampled size
928 //
929 // For the last MCU, we upsample the last stride, meaning that if we hit the last MCU, we
930 // should sample full raw coeffs
931 let is_last_considered = is_vertically_sampled && (i != mcu_height.saturating_sub(1));
932
933 let num_iters = (8 - usize::from(is_last_considered)) * self.coeff * self.v_max;
934
935 color_conv_function(num_iters, samples)?;
936 } else {
937 let mut channels_ref: [&[i16]; MAX_COMPONENTS] = [&[]; MAX_COMPONENTS];
938
939 self.components
940 .iter()
941 .enumerate()
942 .for_each(|(pos, x)| channels_ref[pos] = &x.raw_coeff);
943
944 if let SampleRatios::Generic(_, v) = self.info.sample_ratio {
945 color_conv_function(8 * v * self.coeff, channels_ref)?;
946 } else {
947 color_conv_function(8 * self.coeff, channels_ref)?;
948 }
949 }
950
951 *pixels_written = px;
952 Ok(())
953 }
954}
955
956enum McuContinuation {
957 Ok,
958 AnotherSos,
959 /// Found an inter-scan marker (DHT/DQT/DRI/COM/APP) that needs handling.
960 /// The caller should parse it and scan for the next SOS.
961 InterScanMarker(Marker),
962 Terminate
963}