team-ljyzipelo

공개
829줄30 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
9#![allow(
10 clippy::if_not_else,
11 clippy::similar_names,
12 clippy::inline_always,
13 clippy::doc_markdown,
14 clippy::cast_sign_loss,
15 clippy::cast_possible_truncation
16)]
17
18//! This file exposes a single struct that can decode a huffman encoded
19//! Bitstream in a JPEG file
20//!
21//! This code is optimized for speed.
22//! It's meant to be super duper super fast, because everyone else depends on this being fast.
23//! It's (annoyingly) serial hence we cant use parallel bitstreams(it's variable length coding.)
24//!
25//! Furthermore, on the case of refills, we have to do bytewise processing because the standard decided
26//! that we want to support markers in the middle of streams(seriously few people use RST markers).
27//!
28//! So we pull in all optimization steps:
29//! - use `inline[always]`? ,
30//! - pre-execute most common cases ,
31//! - add random comments
32//! - fast paths .
33//!
34//! Speed-wise: It is probably the fastest JPEG BitStream decoder to ever sail the seven seas because of
35//! a couple of optimization tricks.
36//! 1. Fast refills from libjpeg-turbo
37//! 2. As few as possible branches in decoder fast paths.
38//! 3. Accelerated AC table decoding borrowed from stb_image.h written by Fabian Gissen (@ rygorous),
39//! improved by me to handle more cases.
40//! 4. Safe and extensible routines(e.g. cool ways to eliminate bounds check)
41//! 5. No unsafe here
42//!
43//! Readability comes as a second priority(I tried with variable names this time, and we are wayy better than libjpeg).
44//!
45//! Anyway if you are reading this it means your cool and I hope you get whatever part of the code you are looking for
46//! (or learn something cool)
47//!
48//! Knock yourself out.
49use alloc::format;
50use alloc::string::ToString;
51use zune_core::log::warn;
52use core::cmp::min;
53
54use zune_core::bytestream::{ZByteReaderTrait, ZReader};
55
56use crate::errors::DecodeErrors;
57use crate::huffman::{HuffmanTable, HUFF_LOOKAHEAD};
58use crate::marker::Marker;
59use crate::mcu::DCT_BLOCK;
60use crate::misc::UN_ZIGZAG;
61
62macro_rules! decode_huff {
63 ($stream:tt,$symbol:tt,$table:tt) => {
64 let mut code_length = $symbol >> HUFF_LOOKAHEAD;
65
66 ($symbol) &= (1 << HUFF_LOOKAHEAD) - 1;
67
68 if code_length > i32::from(HUFF_LOOKAHEAD)
69 {
70 // if the symbol cannot be resolved in the first HUFF_LOOKAHEAD bits,
71 // we know it lies somewhere between HUFF_LOOKAHEAD and 16 bits since jpeg imposes 16 bit
72 // limit, we can therefore look 16 bits ahead and try to resolve the symbol
73 // starting from 1+HUFF_LOOKAHEAD bits.
74 $symbol = ($stream).peek_bits::<16>() as i32;
75 // (Credits to Sean T. Barrett stb library for this optimization)
76 // maxcode is pre-shifted 16 bytes long so that it has (16-code_length)
77 // zeroes at the end hence we do not need to shift in the inner loop.
78 while code_length < 17{
79 if $symbol < $table.maxcode[code_length as usize] {
80 break;
81 }
82 code_length += 1;
83 }
84
85 if code_length == 17{
86 // symbol could not be decoded.
87 //
88 // We may think, lets fake zeroes, noo
89 // panic, because Huffman codes are sensitive, probably everything
90 // after this will be corrupt, so no need to continue.
91 // panic!("Bad Huffman code length");
92 return Err(DecodeErrors::Format(format!("Bad Huffman Code 0x{:X}, corrupt JPEG",$symbol)))
93 }
94
95 $symbol >>= (16-code_length);
96 ($symbol) = i32::from(
97 ($table).values
98 [(($symbol + ($table).offset[code_length as usize]) & 0xFF) as usize],
99 );
100 }
101 if code_length> i32::from(($stream).bits_left){
102 return Err(DecodeErrors::Format(format!("Code length {code_length} more than bits left {}",($stream).bits_left)))
103 }
104 // drop bits read
105 ($stream).drop_bits(code_length as u8);
106 };
107}
108
109/// A `BitStream` struct, a bit by bit reader with super powers
110///
111#[rustfmt::skip]
112pub(crate) struct BitStream {
113 /// A MSB type buffer that is used for some certain operations
114 pub buffer: u64,
115 /// A TOP aligned MSB type buffer that is used to accelerate some operations like
116 /// peek_bits and get_bits.
117 ///
118 /// By top aligned, I mean the top bit (63) represents the top bit in the buffer.
119 aligned_buffer: u64,
120 /// Tell us the bits left the two buffer
121 pub(crate) bits_left: u8,
122 /// Did we find a marker(RST/EOF) during decoding?
123 pub marker: Option<Marker>,
124 /// An i16 with the bit corresponding to successive_low set to 1, others 0.
125 pub successive_low_mask: i16,
126 spec_start: u8,
127 spec_end: u8,
128 pub eob_run: i32,
129 pub overread_by: usize,
130 /// True if we have seen end of image marker.
131 /// Don't read anything after that.
132 pub seen_eoi: bool,
133 // 실제 입력 비트와 디코더가 보충한 비트의 소비를 구분함.
134 input_bits: u8,
135 exhausted_input: bool,
136}
137
138impl BitStream {
139 /// Create a new BitStream
140 #[rustfmt::skip]
141 pub(crate) const fn new() -> BitStream {
142 BitStream {
143 buffer: 0,
144 aligned_buffer: 0,
145 bits_left: 0,
146 marker: None,
147 successive_low_mask: 1,
148 spec_start: 0,
149 spec_end: 0,
150 eob_run: 0,
151 overread_by: 0,
152 seen_eoi: false,
153 input_bits: 0,
154 exhausted_input: false,
155 }
156 }
157
158 /// Create a new Bitstream for progressive decoding
159 #[allow(clippy::redundant_field_names)]
160 #[rustfmt::skip]
161 pub(crate) fn new_progressive(al: u8, spec_start: u8, spec_end: u8) -> BitStream {
162 BitStream {
163 buffer: 0,
164 aligned_buffer: 0,
165 bits_left: 0,
166 marker: None,
167 successive_low_mask: 1i16 << al,
168 spec_start: spec_start,
169 spec_end: spec_end,
170 eob_run: 0,
171 overread_by: 0,
172 seen_eoi: false,
173 input_bits: 0,
174 exhausted_input: false,
175 }
176 }
177
178 /// Refill the bit buffer by (a maximum of) 32 bits
179 ///
180 /// # Arguments
181 /// - `reader`:`&mut BufReader<R>`: A mutable reference to an underlying
182 /// File/Memory buffer containing a valid JPEG stream
183 ///
184 /// This function will only refill if `self.count` is less than 32
185 #[inline(always)] // to many call sites? ( perf improvement by 4%)
186 pub fn refill<T>(&mut self, reader: &mut ZReader<T>) -> Result<bool, DecodeErrors>
187 where
188 T: ZByteReaderTrait
189 {
190 /// Macro version of a single byte refill.
191 /// Arguments
192 /// buffer-> our io buffer, because rust macros cannot get values from
193 /// the surrounding environment bits_left-> number of bits left
194 /// to full refill
195 macro_rules! refill {
196 ($buffer:expr,$byte:expr,$bits_left:expr) => {
197 // read a byte from the stream
198 $byte = u64::from(reader.read_u8());
199 self.overread_by += usize::from(reader.eof()?);
200 // append to the buffer
201 // JPEG is a MSB type buffer so that means we append this
202 // to the lower end (0..8) of the buffer and push the rest bits above..
203 $buffer = ($buffer << 8) | $byte;
204 // Increment bits left
205 $bits_left += 8;
206 // Check for special case of OxFF, to see if it's a stream or a marker
207 if $byte == 0xff {
208 // read next byte
209 let mut next_byte = u64::from(reader.read_u8());
210 // Byte snuffing, if we encounter byte snuff, we skip the byte
211 if next_byte != 0x00 {
212 // skip that byte we read
213 while next_byte == 0xFF {
214 next_byte = u64::from(reader.read_u8());
215 }
216
217 if next_byte != 0x00 {
218 // Undo the byte append and return
219 $buffer >>= 8;
220 $bits_left -= 8;
221
222 if $bits_left != 0 {
223 self.aligned_buffer = $buffer << (64 - $bits_left);
224 }
225
226 let marker = Marker::from_u8(next_byte as u8);
227 self.marker = marker;
228
229 if let Some(Marker::UNKNOWN(_)) = marker{
230 return Err(DecodeErrors::Format("Unknown marker in bit stream".to_string()));
231 }
232 if next_byte == 0xD9 {
233 // special handling for eoi, fill some bytes,even if its zero,
234 // removes some panics
235 self.buffer <<= 8;
236 self.bits_left += 8;
237 self.aligned_buffer = self.buffer << (64 - self.bits_left);
238 }
239
240 return Ok(false);
241 }
242 }
243 }
244 if self.overread_by == 0 {
245 self.input_bits += 8;
246 }
247 };
248 }
249
250 self.require_input()?;
251 // 32 bits is enough for a decode(16 bits) and receive_extend(max 16 bits)
252 if self.bits_left < 32 {
253 if self.marker.is_some() || self.seen_eoi {
254 // found a marker, or we are in EOI
255 // also we are in over-reading mode, where we fill it with zeroes
256
257 // fill with zeroes
258 self.buffer <<= 32;
259 self.bits_left += 32;
260 self.aligned_buffer = self.buffer << (64 - self.bits_left);
261 return Ok(true);
262 }
263
264 if self.overread_by > 0 {
265 if self.bits_left == 0 {
266 return Err(DecodeErrors::ExhaustedData);
267 }
268 // We already hit EOF while refilling. Continue consuming the buffered bits
269 // but don't synthesize additional bytes from zero-fill.
270 return Ok(true);
271 }
272
273 // we optimize for the case where we don't have 255 in the stream and have 4 bytes left
274 // as it is the common case
275 //
276 // so we always read 4 bytes, if read_fixed_bytes errors out, the cursor is
277 // guaranteed not to advance in case of failure (is this true), so
278 // we revert the read later on (if we have 255), if this fails, we use the normal
279 // byte at a time read
280
281 if let Ok(bytes) = reader.read_fixed_bytes_or_error::<4>() {
282 // we have 4 bytes to spare, read the 4 bytes into a temporary buffer
283 // create buffer
284 let msb_buf = u32::from_be_bytes(bytes);
285 // check if we have 0xff
286 if !has_byte(msb_buf, 255) {
287 self.bits_left += 32;
288 self.input_bits += 32;
289 self.buffer <<= 32;
290 self.buffer |= u64::from(msb_buf);
291 self.aligned_buffer = self.buffer << (64 - self.bits_left);
292 return Ok(true);
293 }
294
295 reader.rewind(4)?;
296 }
297 // This serves two reasons,
298 // 1: Make clippy shut up
299 // 2: Favour register reuse
300 let mut byte;
301 // 4 refills, if all succeed the stream should contain enough bits to decode a
302 // value
303 refill!(self.buffer, byte, self.bits_left);
304 refill!(self.buffer, byte, self.bits_left);
305 refill!(self.buffer, byte, self.bits_left);
306 refill!(self.buffer, byte, self.bits_left);
307 // Construct an MSB buffer whose top bits are the bitstream we are currently holding.
308 self.aligned_buffer = self.buffer << (64 - self.bits_left);
309 }
310 return Ok(true);
311 }
312 /// Decode the DC coefficient in a MCU block.
313 ///
314 /// The decoded coefficient is written to `dc_prediction`
315 ///
316 #[allow(
317 clippy::cast_possible_truncation,
318 clippy::cast_sign_loss,
319 clippy::unwrap_used
320 )]
321 #[inline(always)]
322 fn decode_dc<T>(
323 &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, dc_prediction: &mut i32
324 ) -> Result<bool, DecodeErrors>
325 where
326 T: ZByteReaderTrait
327 {
328 let (mut symbol, r);
329
330 if self.bits_left < 32 {
331 self.refill(reader)?;
332 };
333 // look a head HUFF_LOOKAHEAD bits into the bitstream
334 symbol = self.peek_bits::<HUFF_LOOKAHEAD>();
335 symbol = dc_table.lookup[symbol as usize];
336
337 decode_huff!(self, symbol, dc_table);
338
339 if symbol != 0 {
340 r = self.get_bits(symbol as u8);
341 symbol = huff_extend(r, symbol);
342 }
343 // Update DC prediction
344 *dc_prediction = dc_prediction.wrapping_add(symbol);
345
346 return Ok(true);
347 }
348
349 /// Like `decode_dc` but we do not need the result of the component, we only want to remove it
350 /// from the bitstream of the MCU.
351 fn discard_dc<T>(
352 &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable
353 ) -> Result<bool, DecodeErrors>
354 where
355 T: ZByteReaderTrait
356 {
357 let mut symbol;
358
359 if self.bits_left < 32 {
360 self.refill(reader)?;
361 };
362 // look a head HUFF_LOOKAHEAD bits into the bitstream
363 symbol = self.peek_bits::<HUFF_LOOKAHEAD>();
364 symbol = dc_table.lookup[symbol as usize];
365
366 decode_huff!(self, symbol, dc_table);
367
368 if symbol != 0 {
369 let _ = self.get_bits(symbol as u8);
370 }
371
372 return Ok(true);
373 }
374
375 /// Decode a Minimum Code Unit(MCU) as quickly as possible
376 ///
377 /// # Arguments
378 /// - reader: The bitstream from where we read more bits.
379 /// - dc_table: The Huffman table used to decode the DC coefficient
380 /// - ac_table: The Huffman table used to decode AC values
381 /// - block: A memory region where we will write out the decoded values
382 /// - DC prediction: Last DC value for this component
383 ///
384 #[allow(
385 clippy::many_single_char_names,
386 clippy::cast_possible_truncation,
387 clippy::cast_sign_loss
388 )]
389 #[inline(never)]
390 pub fn decode_mcu_block<T>(
391 &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, ac_table: &HuffmanTable,
392 qt_table: &[i32; DCT_BLOCK], block: &mut [i32; 64], dc_prediction: &mut i32
393 ) -> Result<u16, DecodeErrors>
394 where
395 T: ZByteReaderTrait
396 {
397 // Get fast AC table as a reference before we enter the hot path
398 let ac_lookup = ac_table.ac_lookup.as_ref().unwrap();
399
400 let (mut symbol, mut r, mut fast_ac);
401 // Decode AC coefficients
402 let mut pos: usize = 1;
403 if self.bits_left < 1 && self.marker.is_some() {
404 return Err(DecodeErrors::Format(
405 "No more bytes left in stream before marker".to_string()
406 ));
407 }
408 // decode DC, dc prediction will contain the value
409 self.decode_dc(reader, dc_table, dc_prediction)?;
410
411 // set dc to be the dc prediction.
412 block[0] = *dc_prediction * qt_table[0];
413
414 while pos < 64 {
415 self.refill(reader)?;
416 symbol = self.peek_bits::<HUFF_LOOKAHEAD>();
417 fast_ac = ac_lookup[symbol as usize];
418 symbol = ac_table.lookup[symbol as usize];
419
420 if fast_ac != 0 {
421 // FAST AC path
422 pos += ((fast_ac >> 4) & 15) as usize; // run
423 let t_pos = UN_ZIGZAG[min(pos, 63)] & 63;
424
425 block[t_pos] = i32::from(fast_ac >> 8) * (qt_table[t_pos]); // Value
426 self.drop_bits((fast_ac & 15) as u8);
427 pos += 1;
428 } else {
429 decode_huff!(self, symbol, ac_table);
430
431 r = symbol >> 4;
432 symbol &= 15;
433
434 if symbol != 0 {
435 pos += r as usize;
436 r = self.get_bits(symbol as u8);
437 symbol = huff_extend(r, symbol);
438 let t_pos = UN_ZIGZAG[pos & 63] & 63;
439
440 block[t_pos] = symbol * qt_table[t_pos];
441
442 pos += 1;
443 } else if r != 15 {
444 return Ok(pos as u16);
445 } else {
446 pos += 16;
447 }
448 }
449 }
450
451 return Ok(64);
452 }
453
454 /// Advance the bitstream over a block but ignore the data contained.
455 ///
456 /// This updates DC prediction but we never dequantize and we never do any Zig-Zag translation
457 /// either. Still returns the index of the last component read.
458 pub fn discard_mcu_block<T>(
459 &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, ac_table: &HuffmanTable
460 ) -> Result<u16, DecodeErrors>
461 where
462 T: ZByteReaderTrait
463 {
464 // Get fast AC table as a reference before we enter the hot path
465 let ac_lookup = ac_table.ac_lookup.as_ref().unwrap();
466
467 let (mut symbol, mut r, mut fast_ac);
468 // Decode AC coefficients
469 let mut pos: usize = 1;
470
471 // decode DC, dc prediction will contain the value
472 self.discard_dc(reader, dc_table)?;
473
474 while pos < 64 {
475 self.refill(reader)?;
476 symbol = self.peek_bits::<HUFF_LOOKAHEAD>();
477 fast_ac = ac_lookup[symbol as usize];
478 symbol = ac_table.lookup[symbol as usize];
479
480 if fast_ac != 0 {
481 // FAST AC path
482 pos += ((fast_ac >> 4) & 15) as usize; // run
483
484 self.drop_bits((fast_ac & 15) as u8);
485 pos += 1;
486 } else {
487 decode_huff!(self, symbol, ac_table);
488
489 r = symbol >> 4;
490 symbol &= 15;
491
492 if symbol != 0 {
493 pos += r as usize;
494 // Advance over bits but ignore.
495 let _ = self.get_bits(symbol as u8);
496
497 pos += 1;
498 } else if r != 15 {
499 return Ok(pos as u16);
500 } else {
501 pos += 16;
502 }
503 }
504 }
505
506 return Ok(64);
507 }
508
509 /// Peek `look_ahead` bits ahead without discarding them from the buffer
510 #[inline(always)]
511 #[allow(clippy::cast_possible_truncation)]
512 const fn peek_bits<const LOOKAHEAD: u8>(&self) -> i32 {
513 (self.aligned_buffer >> (64 - LOOKAHEAD)) as i32
514 }
515
516 /// Discard the next `N` bits without checking
517 #[inline]
518 fn drop_bits(&mut self, n: u8) {
519 self.consume_input(n);
520 // PS: Its a good check, but triggers fuzzer and a lot of false positives
521 //debug_assert!(self.bits_left >= n);
522 //self.bits_left -= n;
523 self.bits_left = self.bits_left.saturating_sub(n);
524 self.aligned_buffer <<= n;
525 }
526
527 /// Read `n_bits` from the buffer and discard them
528 #[inline(always)]
529 #[allow(clippy::cast_possible_truncation)]
530 fn get_bits(&mut self, n_bits: u8) -> i32 {
531 self.consume_input(n_bits);
532 let mask = (1_u64 << n_bits) - 1;
533
534 self.aligned_buffer = self.aligned_buffer.rotate_left(u32::from(n_bits));
535 let bits = (self.aligned_buffer & mask) as i32;
536 self.bits_left = self.bits_left.wrapping_sub(n_bits);
537 bits
538 }
539
540 /// Decode a DC block
541 #[allow(clippy::cast_possible_truncation)]
542 #[inline]
543 pub(crate) fn decode_prog_dc_first<T>(
544 &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, block: &mut i16,
545 dc_prediction: &mut i32
546 ) -> Result<(), DecodeErrors>
547 where
548 T: ZByteReaderTrait
549 {
550 self.decode_dc(reader, dc_table, dc_prediction)?;
551 *block = (*dc_prediction as i16).wrapping_mul(self.successive_low_mask);
552 return Ok(());
553 }
554 #[inline]
555 pub(crate) fn decode_prog_dc_refine<T>(
556 &mut self, reader: &mut ZReader<T>, block: &mut i16
557 ) -> Result<(), DecodeErrors>
558 where
559 T: ZByteReaderTrait
560 {
561 // refinement scan
562 if self.bits_left < 1 {
563 self.refill(reader)?;
564 // if we find a marker, it may happens we don't refill.
565 // So let's confirm again that refill worked
566 if self.bits_left < 1 {
567 return Err(DecodeErrors::Format(
568 "Marker found where not expected in refine bit".to_string()
569 ));
570 }
571 }
572
573 if self.get_bit() == 1 {
574 *block = block.wrapping_add(self.successive_low_mask);
575 }
576
577 Ok(())
578 }
579
580 /// Get a single bit from the bitstream
581 fn get_bit(&mut self) -> u8 {
582 let k = (self.aligned_buffer >> 63) as u8;
583 // discard a bit
584 self.drop_bits(1);
585 return k;
586 }
587 pub(crate) fn decode_mcu_ac_first<T>(
588 &mut self, reader: &mut ZReader<T>, ac_table: &HuffmanTable, block: &mut [i16; 64]
589 ) -> Result<bool, DecodeErrors>
590 where
591 T: ZByteReaderTrait
592 {
593 let fast_ac = ac_table.ac_lookup.as_ref().unwrap();
594 let bit = self.successive_low_mask;
595
596 let mut k = self.spec_start as usize;
597 let (mut symbol, mut r, mut fac);
598
599 // EOB runs are handled in mcu_prog.rs
600 'block: loop {
601 self.refill(reader)?;
602 // Check for marker in the stream
603
604 symbol = self.peek_bits::<HUFF_LOOKAHEAD>();
605 fac = fast_ac[symbol as usize];
606 symbol = ac_table.lookup[symbol as usize];
607
608 if fac != 0 {
609 // fast ac path
610 k += ((fac >> 4) & 15) as usize; // run
611 block[UN_ZIGZAG[min(k, 63)] & 63] = (fac >> 8).wrapping_mul(bit); // value
612 self.drop_bits((fac & 15) as u8);
613 k += 1;
614 } else {
615 decode_huff!(self, symbol, ac_table);
616
617 r = symbol >> 4;
618 symbol &= 15;
619
620 if symbol != 0 {
621 k += r as usize;
622 r = self.get_bits(symbol as u8);
623 symbol = huff_extend(r, symbol);
624 block[UN_ZIGZAG[k & 63] & 63] = (symbol as i16).wrapping_mul(bit);
625 k += 1;
626 } else {
627 if r != 15 {
628 self.eob_run = 1 << r;
629 self.eob_run += self.get_bits(r as u8);
630 self.eob_run -= 1;
631 break;
632 }
633
634 k += 16;
635 }
636 }
637
638 if k > self.spec_end as usize {
639 break 'block;
640 }
641 }
642 return Ok(true);
643 }
644 #[allow(clippy::too_many_lines, clippy::op_ref)]
645 pub(crate) fn decode_mcu_ac_refine<T>(
646 &mut self, reader: &mut ZReader<T>, table: &HuffmanTable, block: &mut [i16; 64]
647 ) -> Result<bool, DecodeErrors>
648 where
649 T: ZByteReaderTrait
650 {
651 let bit = self.successive_low_mask;
652
653 let mut k = self.spec_start;
654 let (mut symbol, mut r);
655
656 if self.eob_run == 0 {
657 'no_eob: loop {
658 // Decode a coefficient from the bit stream
659 self.refill(reader)?;
660
661 symbol = self.peek_bits::<HUFF_LOOKAHEAD>();
662 symbol = table.lookup[symbol as usize];
663
664 decode_huff!(self, symbol, table);
665
666 r = symbol >> 4;
667 symbol &= 15;
668
669 if symbol == 0 {
670 if r != 15 {
671 // EOB run is 2^r + bits
672 self.eob_run = 1 << r;
673 self.eob_run += self.get_bits(r as u8);
674 // EOB runs are handled by the eob logic
675 break 'no_eob;
676 }
677 } else {
678 // libjpeg-turbo also doesn't return an error here, so let's also warn.
679 if symbol != 1 {
680 warn!("Bad Huffman code, corrupt JPEG?");
681 }
682 // get sign bit
683 // We assume we have enough bits, which should be correct for sane images
684 // since we refill by 32 above
685 if self.get_bit() == 1 {
686 symbol = i32::from(bit);
687 } else {
688 symbol = i32::from(-bit);
689 }
690 }
691
692 // Advance over already nonzero coefficients appending
693 // correction bits to the non-zeroes.
694 // A correction bit is 1 if the absolute value of the coefficient must be increased
695
696 if k <= self.spec_end {
697 'advance_nonzero: loop {
698 let coefficient = &mut block[UN_ZIGZAG[k as usize & 63] & 63];
699
700 if *coefficient != 0 {
701 if self.bits_left < 1 {
702 self.refill(reader)?;
703 if self.bits_left < 1 && self.marker.is_some() {
704 return Err(DecodeErrors::Format(
705 "Marker found where not expected in refine bit".to_string()
706 ));
707 }
708 }
709 if self.get_bit() == 1 && (*coefficient & bit) == 0 {
710 if *coefficient > 0 {
711 *coefficient = coefficient.wrapping_add(bit);
712 } else {
713 *coefficient = coefficient.wrapping_sub(bit);
714 }
715 }
716 } else {
717 r -= 1;
718
719 if r < 0 {
720 // reached target zero coefficient.
721 break 'advance_nonzero;
722 }
723 };
724
725 if k == self.spec_end {
726 break 'advance_nonzero;
727 }
728
729 k += 1;
730 }
731 }
732
733 if symbol != 0 {
734 let pos = UN_ZIGZAG[k as usize & 63];
735 // output new non-zero coefficient.
736 block[pos & 63] = symbol as i16;
737 }
738
739 k += 1;
740
741 if k > self.spec_end {
742 break 'no_eob;
743 }
744 }
745 }
746 if self.eob_run > 0 {
747 // only run if block does not consists of purely zeroes
748 if &block[1..] != &[0; 63] {
749 self.refill(reader)?;
750
751 while k <= self.spec_end {
752 let coefficient = &mut block[UN_ZIGZAG[k as usize & 63] & 63];
753
754 if *coefficient != 0 && self.get_bit() == 1 {
755 // check if we already modified it, if so do nothing, otherwise
756 // append the correction bit.
757 if (*coefficient & bit) == 0 {
758 if *coefficient >= 0 {
759 *coefficient = coefficient.wrapping_add(bit);
760 } else {
761 *coefficient = coefficient.wrapping_sub(bit);
762 }
763 }
764 }
765 if self.bits_left < 1 {
766 // refill at the last possible moment
767 self.refill(reader)?;
768 }
769 k += 1;
770 }
771 }
772 // count a block completed in EOB run
773 self.eob_run -= 1;
774 }
775 return Ok(true);
776 }
777
778 pub fn update_progressive_params(&mut self, _ah: u8, al: u8, spec_start: u8, spec_end: u8) {
779 self.successive_low_mask = 1i16 << al;
780 self.spec_start = spec_start;
781 self.spec_end = spec_end;
782 }
783
784 fn consume_input(&mut self, bits: u8) {
785 self.exhausted_input |= bits > self.input_bits;
786 self.input_bits = self.input_bits.saturating_sub(bits);
787 }
788
789 pub(crate) fn require_input(&self) -> Result<(), DecodeErrors> {
790 if self.exhausted_input {
791 return Err(DecodeErrors::FormatStatic("Incomplete entropy-coded image data"));
792 }
793 Ok(())
794 }
795
796 /// Reset the stream if we have a restart marker
797 ///
798 /// Restart markers indicate drop those bits in the stream and zero out
799 /// everything
800 #[cold]
801 pub fn reset(&mut self) {
802 self.bits_left = 0;
803 self.input_bits = 0;
804 self.exhausted_input = false;
805 self.marker = None;
806 self.buffer = 0;
807 self.aligned_buffer = 0;
808 self.eob_run = 0;
809 }
810}
811
812/// Do the equivalent of JPEG HUFF_EXTEND
813#[inline(always)]
814fn huff_extend(x: i32, s: i32) -> i32 {
815 // if x<s return x else return x+offset[s] where offset[s] = ( (-1<<s)+1)
816 (x) + ((((x) - (1 << ((s) - 1))) >> 31) & (((-1) << (s)) + 1))
817}
818
819const fn has_zero(v: u32) -> bool {
820 // Retrieved from Stanford bithacks
821 // @ https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
822 return !((((v & 0x7F7F_7F7F) + 0x7F7F_7F7F) | v) | 0x7F7F_7F7F) != 0;
823}
824
825const fn has_byte(b: u32, val: u8) -> bool {
826 // Retrieved from Stanford bithacks
827 // @ https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord
828 has_zero(b ^ ((!0_u32 / 255) * (val as u32)))
829}