jdhuff.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834
  1. /*
  2. * jdhuff.c
  3. *
  4. * This file was part of the Independent JPEG Group's software:
  5. * Copyright (C) 1991-1997, Thomas G. Lane.
  6. * libjpeg-turbo Modifications:
  7. * Copyright (C) 2009-2011, 2016, 2018-2019, D. R. Commander.
  8. * Copyright (C) 2018, Matthias Räncker.
  9. * For conditions of distribution and use, see the accompanying README.ijg
  10. * file.
  11. *
  12. * This file contains Huffman entropy decoding routines.
  13. *
  14. * Much of the complexity here has to do with supporting input suspension.
  15. * If the data source module demands suspension, we want to be able to back
  16. * up to the start of the current MCU. To do this, we copy state variables
  17. * into local working storage, and update them back to the permanent
  18. * storage only upon successful completion of an MCU.
  19. *
  20. * NOTE: All referenced figures are from
  21. * Recommendation ITU-T T.81 (1992) | ISO/IEC 10918-1:1994.
  22. */
  23. #define JPEG_INTERNALS
  24. #include "jinclude.h"
  25. #include "jpeglib.h"
  26. #include "jdhuff.h" /* Declarations shared with jdphuff.c */
  27. #include "jpegcomp.h"
  28. #include "jstdhuff.c"
  29. /*
  30. * Expanded entropy decoder object for Huffman decoding.
  31. *
  32. * The savable_state subrecord contains fields that change within an MCU,
  33. * but must not be updated permanently until we complete the MCU.
  34. */
  35. typedef struct {
  36. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  37. } savable_state;
  38. typedef struct {
  39. struct jpeg_entropy_decoder pub; /* public fields */
  40. /* These fields are loaded into local variables at start of each MCU.
  41. * In case of suspension, we exit WITHOUT updating them.
  42. */
  43. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  44. savable_state saved; /* Other state at start of MCU */
  45. /* These fields are NOT loaded into local working state. */
  46. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  47. /* Pointers to derived tables (these workspaces have image lifespan) */
  48. d_derived_tbl *dc_derived_tbls[NUM_HUFF_TBLS];
  49. d_derived_tbl *ac_derived_tbls[NUM_HUFF_TBLS];
  50. /* Precalculated info set up by start_pass for use in decode_mcu: */
  51. /* Pointers to derived tables to be used for each block within an MCU */
  52. d_derived_tbl *dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  53. d_derived_tbl *ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  54. /* Whether we care about the DC and AC coefficient values for each block */
  55. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  56. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  57. } huff_entropy_decoder;
  58. typedef huff_entropy_decoder *huff_entropy_ptr;
  59. /*
  60. * Initialize for a Huffman-compressed scan.
  61. */
  62. METHODDEF(void)
  63. start_pass_huff_decoder(j_decompress_ptr cinfo)
  64. {
  65. huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
  66. int ci, blkn, dctbl, actbl;
  67. d_derived_tbl **pdtbl;
  68. jpeg_component_info *compptr;
  69. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  70. * This ought to be an error condition, but we make it a warning because
  71. * there are some baseline files out there with all zeroes in these bytes.
  72. */
  73. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2 - 1 ||
  74. cinfo->Ah != 0 || cinfo->Al != 0)
  75. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  76. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  77. compptr = cinfo->cur_comp_info[ci];
  78. dctbl = compptr->dc_tbl_no;
  79. actbl = compptr->ac_tbl_no;
  80. /* Compute derived values for Huffman tables */
  81. /* We may do this more than once for a table, but it's not expensive */
  82. pdtbl = (d_derived_tbl **)(entropy->dc_derived_tbls) + dctbl;
  83. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl, pdtbl);
  84. pdtbl = (d_derived_tbl **)(entropy->ac_derived_tbls) + actbl;
  85. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl, pdtbl);
  86. /* Initialize DC predictions to 0 */
  87. entropy->saved.last_dc_val[ci] = 0;
  88. }
  89. /* Precalculate decoding info for each block in an MCU of this scan */
  90. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  91. ci = cinfo->MCU_membership[blkn];
  92. compptr = cinfo->cur_comp_info[ci];
  93. /* Precalculate which table to use for each block */
  94. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  95. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  96. /* Decide whether we really care about the coefficient values */
  97. if (compptr->component_needed) {
  98. entropy->dc_needed[blkn] = TRUE;
  99. /* we don't need the ACs if producing a 1/8th-size image */
  100. entropy->ac_needed[blkn] = (compptr->_DCT_scaled_size > 1);
  101. } else {
  102. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  103. }
  104. }
  105. /* Initialize bitread state variables */
  106. entropy->bitstate.bits_left = 0;
  107. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  108. entropy->pub.insufficient_data = FALSE;
  109. /* Initialize restart counter */
  110. entropy->restarts_to_go = cinfo->restart_interval;
  111. }
  112. /*
  113. * Compute the derived values for a Huffman table.
  114. * This routine also performs some validation checks on the table.
  115. *
  116. * Note this is also used by jdphuff.c.
  117. */
  118. GLOBAL(void)
  119. jpeg_make_d_derived_tbl(j_decompress_ptr cinfo, boolean isDC, int tblno,
  120. d_derived_tbl **pdtbl)
  121. {
  122. JHUFF_TBL *htbl;
  123. d_derived_tbl *dtbl;
  124. int p, i, l, si, numsymbols;
  125. int lookbits, ctr;
  126. char huffsize[257];
  127. unsigned int huffcode[257];
  128. unsigned int code;
  129. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  130. * paralleling the order of the symbols themselves in htbl->huffval[].
  131. */
  132. /* Find the input Huffman table */
  133. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  134. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  135. htbl =
  136. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  137. if (htbl == NULL)
  138. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  139. /* Allocate a workspace if we haven't already done so. */
  140. if (*pdtbl == NULL)
  141. *pdtbl = (d_derived_tbl *)
  142. (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
  143. sizeof(d_derived_tbl));
  144. dtbl = *pdtbl;
  145. dtbl->pub = htbl; /* fill in back link */
  146. /* Figure C.1: make table of Huffman code length for each symbol */
  147. p = 0;
  148. for (l = 1; l <= 16; l++) {
  149. i = (int)htbl->bits[l];
  150. if (i < 0 || p + i > 256) /* protect against table overrun */
  151. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  152. while (i--)
  153. huffsize[p++] = (char)l;
  154. }
  155. huffsize[p] = 0;
  156. numsymbols = p;
  157. /* Figure C.2: generate the codes themselves */
  158. /* We also validate that the counts represent a legal Huffman code tree. */
  159. code = 0;
  160. si = huffsize[0];
  161. p = 0;
  162. while (huffsize[p]) {
  163. while (((int)huffsize[p]) == si) {
  164. huffcode[p++] = code;
  165. code++;
  166. }
  167. /* code is now 1 more than the last code used for codelength si; but
  168. * it must still fit in si bits, since no code is allowed to be all ones.
  169. */
  170. if (((JLONG)code) >= (((JLONG)1) << si))
  171. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  172. code <<= 1;
  173. si++;
  174. }
  175. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  176. p = 0;
  177. for (l = 1; l <= 16; l++) {
  178. if (htbl->bits[l]) {
  179. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  180. * minus the minimum code of length l
  181. */
  182. dtbl->valoffset[l] = (JLONG)p - (JLONG)huffcode[p];
  183. p += htbl->bits[l];
  184. dtbl->maxcode[l] = huffcode[p - 1]; /* maximum code of length l */
  185. } else {
  186. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  187. }
  188. }
  189. dtbl->valoffset[17] = 0;
  190. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  191. /* Compute lookahead tables to speed up decoding.
  192. * First we set all the table entries to 0, indicating "too long";
  193. * then we iterate through the Huffman codes that are short enough and
  194. * fill in all the entries that correspond to bit sequences starting
  195. * with that code.
  196. */
  197. for (i = 0; i < (1 << HUFF_LOOKAHEAD); i++)
  198. dtbl->lookup[i] = (HUFF_LOOKAHEAD + 1) << HUFF_LOOKAHEAD;
  199. p = 0;
  200. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  201. for (i = 1; i <= (int)htbl->bits[l]; i++, p++) {
  202. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  203. /* Generate left-justified code followed by all possible bit sequences */
  204. lookbits = huffcode[p] << (HUFF_LOOKAHEAD - l);
  205. for (ctr = 1 << (HUFF_LOOKAHEAD - l); ctr > 0; ctr--) {
  206. dtbl->lookup[lookbits] = (l << HUFF_LOOKAHEAD) | htbl->huffval[p];
  207. lookbits++;
  208. }
  209. }
  210. }
  211. /* Validate symbols as being reasonable.
  212. * For AC tables, we make no check, but accept all byte values 0..255.
  213. * For DC tables, we require the symbols to be in range 0..15.
  214. * (Tighter bounds could be applied depending on the data depth and mode,
  215. * but this is sufficient to ensure safe decoding.)
  216. */
  217. if (isDC) {
  218. for (i = 0; i < numsymbols; i++) {
  219. int sym = htbl->huffval[i];
  220. if (sym < 0 || sym > 15)
  221. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  222. }
  223. }
  224. }
  225. /*
  226. * Out-of-line code for bit fetching (shared with jdphuff.c).
  227. * See jdhuff.h for info about usage.
  228. * Note: current values of get_buffer and bits_left are passed as parameters,
  229. * but are returned in the corresponding fields of the state struct.
  230. *
  231. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  232. * of get_buffer to be used. (On machines with wider words, an even larger
  233. * buffer could be used.) However, on some machines 32-bit shifts are
  234. * quite slow and take time proportional to the number of places shifted.
  235. * (This is true with most PC compilers, for instance.) In this case it may
  236. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  237. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  238. */
  239. #ifdef SLOW_SHIFT_32
  240. #define MIN_GET_BITS 15 /* minimum allowable value */
  241. #else
  242. #define MIN_GET_BITS (BIT_BUF_SIZE - 7)
  243. #endif
  244. GLOBAL(boolean)
  245. jpeg_fill_bit_buffer(bitread_working_state *state,
  246. register bit_buf_type get_buffer, register int bits_left,
  247. int nbits)
  248. /* Load up the bit buffer to a depth of at least nbits */
  249. {
  250. /* Copy heavily used state fields into locals (hopefully registers) */
  251. register const JOCTET *next_input_byte = state->next_input_byte;
  252. register size_t bytes_in_buffer = state->bytes_in_buffer;
  253. j_decompress_ptr cinfo = state->cinfo;
  254. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  255. /* (It is assumed that no request will be for more than that many bits.) */
  256. /* We fail to do so only if we hit a marker or are forced to suspend. */
  257. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  258. while (bits_left < MIN_GET_BITS) {
  259. register int c;
  260. /* Attempt to read a byte */
  261. if (bytes_in_buffer == 0) {
  262. if (!(*cinfo->src->fill_input_buffer) (cinfo))
  263. return FALSE;
  264. next_input_byte = cinfo->src->next_input_byte;
  265. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  266. }
  267. bytes_in_buffer--;
  268. c = *next_input_byte++;
  269. /* If it's 0xFF, check and discard stuffed zero byte */
  270. if (c == 0xFF) {
  271. /* Loop here to discard any padding FF's on terminating marker,
  272. * so that we can save a valid unread_marker value. NOTE: we will
  273. * accept multiple FF's followed by a 0 as meaning a single FF data
  274. * byte. This data pattern is not valid according to the standard.
  275. */
  276. do {
  277. if (bytes_in_buffer == 0) {
  278. if (!(*cinfo->src->fill_input_buffer) (cinfo))
  279. return FALSE;
  280. next_input_byte = cinfo->src->next_input_byte;
  281. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  282. }
  283. bytes_in_buffer--;
  284. c = *next_input_byte++;
  285. } while (c == 0xFF);
  286. if (c == 0) {
  287. /* Found FF/00, which represents an FF data byte */
  288. c = 0xFF;
  289. } else {
  290. /* Oops, it's actually a marker indicating end of compressed data.
  291. * Save the marker code for later use.
  292. * Fine point: it might appear that we should save the marker into
  293. * bitread working state, not straight into permanent state. But
  294. * once we have hit a marker, we cannot need to suspend within the
  295. * current MCU, because we will read no more bytes from the data
  296. * source. So it is OK to update permanent state right away.
  297. */
  298. cinfo->unread_marker = c;
  299. /* See if we need to insert some fake zero bits. */
  300. goto no_more_bytes;
  301. }
  302. }
  303. /* OK, load c into get_buffer */
  304. get_buffer = (get_buffer << 8) | c;
  305. bits_left += 8;
  306. } /* end while */
  307. } else {
  308. no_more_bytes:
  309. /* We get here if we've read the marker that terminates the compressed
  310. * data segment. There should be enough bits in the buffer register
  311. * to satisfy the request; if so, no problem.
  312. */
  313. if (nbits > bits_left) {
  314. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  315. * the data stream, so that we can produce some kind of image.
  316. * We use a nonvolatile flag to ensure that only one warning message
  317. * appears per data segment.
  318. */
  319. if (!cinfo->entropy->insufficient_data) {
  320. WARNMS(cinfo, JWRN_HIT_MARKER);
  321. cinfo->entropy->insufficient_data = TRUE;
  322. }
  323. /* Fill the buffer with zero bits */
  324. get_buffer <<= MIN_GET_BITS - bits_left;
  325. bits_left = MIN_GET_BITS;
  326. }
  327. }
  328. /* Unload the local registers */
  329. state->next_input_byte = next_input_byte;
  330. state->bytes_in_buffer = bytes_in_buffer;
  331. state->get_buffer = get_buffer;
  332. state->bits_left = bits_left;
  333. return TRUE;
  334. }
  335. /* Macro version of the above, which performs much better but does not
  336. handle markers. We have to hand off any blocks with markers to the
  337. slower routines. */
  338. #define GET_BYTE { \
  339. register int c0, c1; \
  340. c0 = *buffer++; \
  341. c1 = *buffer; \
  342. /* Pre-execute most common case */ \
  343. get_buffer = (get_buffer << 8) | c0; \
  344. bits_left += 8; \
  345. if (c0 == 0xFF) { \
  346. /* Pre-execute case of FF/00, which represents an FF data byte */ \
  347. buffer++; \
  348. if (c1 != 0) { \
  349. /* Oops, it's actually a marker indicating end of compressed data. */ \
  350. cinfo->unread_marker = c1; \
  351. /* Back out pre-execution and fill the buffer with zero bits */ \
  352. buffer -= 2; \
  353. get_buffer &= ~0xFF; \
  354. } \
  355. } \
  356. }
  357. #if SIZEOF_SIZE_T == 8 || defined(_WIN64) || (defined(__x86_64__) && defined(__ILP32__))
  358. /* Pre-fetch 48 bytes, because the holding register is 64-bit */
  359. #define FILL_BIT_BUFFER_FAST \
  360. if (bits_left <= 16) { \
  361. GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE GET_BYTE \
  362. }
  363. #else
  364. /* Pre-fetch 16 bytes, because the holding register is 32-bit */
  365. #define FILL_BIT_BUFFER_FAST \
  366. if (bits_left <= 16) { \
  367. GET_BYTE GET_BYTE \
  368. }
  369. #endif
  370. /*
  371. * Out-of-line code for Huffman code decoding.
  372. * See jdhuff.h for info about usage.
  373. */
  374. GLOBAL(int)
  375. jpeg_huff_decode(bitread_working_state *state,
  376. register bit_buf_type get_buffer, register int bits_left,
  377. d_derived_tbl *htbl, int min_bits)
  378. {
  379. register int l = min_bits;
  380. register JLONG code;
  381. /* HUFF_DECODE has determined that the code is at least min_bits */
  382. /* bits long, so fetch that many bits in one swoop. */
  383. CHECK_BIT_BUFFER(*state, l, return -1);
  384. code = GET_BITS(l);
  385. /* Collect the rest of the Huffman code one bit at a time. */
  386. /* This is per Figure F.16. */
  387. while (code > htbl->maxcode[l]) {
  388. code <<= 1;
  389. CHECK_BIT_BUFFER(*state, 1, return -1);
  390. code |= GET_BITS(1);
  391. l++;
  392. }
  393. /* Unload the local registers */
  394. state->get_buffer = get_buffer;
  395. state->bits_left = bits_left;
  396. /* With garbage input we may reach the sentinel value l = 17. */
  397. if (l > 16) {
  398. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  399. return 0; /* fake a zero as the safest result */
  400. }
  401. return htbl->pub->huffval[(int)(code + htbl->valoffset[l])];
  402. }
  403. /*
  404. * Figure F.12: extend sign bit.
  405. * On some machines, a shift and add will be faster than a table lookup.
  406. */
  407. #define AVOID_TABLES
  408. #ifdef AVOID_TABLES
  409. #define NEG_1 ((unsigned int)-1)
  410. #define HUFF_EXTEND(x, s) \
  411. ((x) + ((((x) - (1 << ((s) - 1))) >> 31) & (((NEG_1) << (s)) + 1)))
  412. #else
  413. #define HUFF_EXTEND(x, s) \
  414. ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  415. static const int extend_test[16] = { /* entry n is 2**(n-1) */
  416. 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  417. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000
  418. };
  419. static const int extend_offset[16] = { /* entry n is (-1 << n) + 1 */
  420. 0, ((-1) << 1) + 1, ((-1) << 2) + 1, ((-1) << 3) + 1, ((-1) << 4) + 1,
  421. ((-1) << 5) + 1, ((-1) << 6) + 1, ((-1) << 7) + 1, ((-1) << 8) + 1,
  422. ((-1) << 9) + 1, ((-1) << 10) + 1, ((-1) << 11) + 1, ((-1) << 12) + 1,
  423. ((-1) << 13) + 1, ((-1) << 14) + 1, ((-1) << 15) + 1
  424. };
  425. #endif /* AVOID_TABLES */
  426. /*
  427. * Check for a restart marker & resynchronize decoder.
  428. * Returns FALSE if must suspend.
  429. */
  430. LOCAL(boolean)
  431. process_restart(j_decompress_ptr cinfo)
  432. {
  433. huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
  434. int ci;
  435. /* Throw away any unused bits remaining in bit buffer; */
  436. /* include any full bytes in next_marker's count of discarded bytes */
  437. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  438. entropy->bitstate.bits_left = 0;
  439. /* Advance past the RSTn marker */
  440. if (!(*cinfo->marker->read_restart_marker) (cinfo))
  441. return FALSE;
  442. /* Re-initialize DC predictions to 0 */
  443. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  444. entropy->saved.last_dc_val[ci] = 0;
  445. /* Reset restart counter */
  446. entropy->restarts_to_go = cinfo->restart_interval;
  447. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  448. * against a marker. In that case we will end up treating the next data
  449. * segment as empty, and we can avoid producing bogus output pixels by
  450. * leaving the flag set.
  451. */
  452. if (cinfo->unread_marker == 0)
  453. entropy->pub.insufficient_data = FALSE;
  454. return TRUE;
  455. }
  456. #if defined(__has_feature)
  457. #if __has_feature(undefined_behavior_sanitizer)
  458. __attribute__((no_sanitize("signed-integer-overflow"),
  459. no_sanitize("unsigned-integer-overflow")))
  460. #endif
  461. #endif
  462. LOCAL(boolean)
  463. decode_mcu_slow(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  464. {
  465. huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
  466. BITREAD_STATE_VARS;
  467. int blkn;
  468. savable_state state;
  469. /* Outer loop handles each block in the MCU */
  470. /* Load up working state */
  471. BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
  472. state = entropy->saved;
  473. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  474. JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;
  475. d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];
  476. d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];
  477. register int s, k, r;
  478. /* Decode a single block's worth of coefficients */
  479. /* Section F.2.2.1: decode the DC coefficient difference */
  480. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  481. if (s) {
  482. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  483. r = GET_BITS(s);
  484. s = HUFF_EXTEND(r, s);
  485. }
  486. if (entropy->dc_needed[blkn]) {
  487. /* Convert DC difference to actual value, update last_dc_val */
  488. int ci = cinfo->MCU_membership[blkn];
  489. /* Certain malformed JPEG images produce repeated DC coefficient
  490. * differences of 2047 or -2047, which causes state.last_dc_val[ci] to
  491. * grow until it overflows or underflows a 32-bit signed integer. This
  492. * behavior is, to the best of our understanding, innocuous, and it is
  493. * unclear how to work around it without potentially affecting
  494. * performance. Thus, we (hopefully temporarily) suppress UBSan integer
  495. * overflow errors for this function and decode_mcu_fast().
  496. */
  497. s += state.last_dc_val[ci];
  498. state.last_dc_val[ci] = s;
  499. if (block) {
  500. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  501. (*block)[0] = (JCOEF)s;
  502. }
  503. }
  504. if (entropy->ac_needed[blkn] && block) {
  505. /* Section F.2.2.2: decode the AC coefficients */
  506. /* Since zeroes are skipped, output area must be cleared beforehand */
  507. for (k = 1; k < DCTSIZE2; k++) {
  508. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  509. r = s >> 4;
  510. s &= 15;
  511. if (s) {
  512. k += r;
  513. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  514. r = GET_BITS(s);
  515. s = HUFF_EXTEND(r, s);
  516. /* Output coefficient in natural (dezigzagged) order.
  517. * Note: the extra entries in jpeg_natural_order[] will save us
  518. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  519. */
  520. (*block)[jpeg_natural_order[k]] = (JCOEF)s;
  521. } else {
  522. if (r != 15)
  523. break;
  524. k += 15;
  525. }
  526. }
  527. } else {
  528. /* Section F.2.2.2: decode the AC coefficients */
  529. /* In this path we just discard the values */
  530. for (k = 1; k < DCTSIZE2; k++) {
  531. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  532. r = s >> 4;
  533. s &= 15;
  534. if (s) {
  535. k += r;
  536. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  537. DROP_BITS(s);
  538. } else {
  539. if (r != 15)
  540. break;
  541. k += 15;
  542. }
  543. }
  544. }
  545. }
  546. /* Completed MCU, so update state */
  547. BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
  548. entropy->saved = state;
  549. return TRUE;
  550. }
  551. #if defined(__has_feature)
  552. #if __has_feature(undefined_behavior_sanitizer)
  553. __attribute__((no_sanitize("signed-integer-overflow"),
  554. no_sanitize("unsigned-integer-overflow")))
  555. #endif
  556. #endif
  557. LOCAL(boolean)
  558. decode_mcu_fast(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  559. {
  560. huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
  561. BITREAD_STATE_VARS;
  562. JOCTET *buffer;
  563. int blkn;
  564. savable_state state;
  565. /* Outer loop handles each block in the MCU */
  566. /* Load up working state */
  567. BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
  568. buffer = (JOCTET *)br_state.next_input_byte;
  569. state = entropy->saved;
  570. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  571. JBLOCKROW block = MCU_data ? MCU_data[blkn] : NULL;
  572. d_derived_tbl *dctbl = entropy->dc_cur_tbls[blkn];
  573. d_derived_tbl *actbl = entropy->ac_cur_tbls[blkn];
  574. register int s, k, r, l;
  575. HUFF_DECODE_FAST(s, l, dctbl);
  576. if (s) {
  577. FILL_BIT_BUFFER_FAST
  578. r = GET_BITS(s);
  579. s = HUFF_EXTEND(r, s);
  580. }
  581. if (entropy->dc_needed[blkn]) {
  582. int ci = cinfo->MCU_membership[blkn];
  583. /* Refer to the comment in decode_mcu_slow() regarding the supression of
  584. * a UBSan integer overflow error in this line of code.
  585. */
  586. s += state.last_dc_val[ci];
  587. state.last_dc_val[ci] = s;
  588. if (block)
  589. (*block)[0] = (JCOEF)s;
  590. }
  591. if (entropy->ac_needed[blkn] && block) {
  592. for (k = 1; k < DCTSIZE2; k++) {
  593. HUFF_DECODE_FAST(s, l, actbl);
  594. r = s >> 4;
  595. s &= 15;
  596. if (s) {
  597. k += r;
  598. FILL_BIT_BUFFER_FAST
  599. r = GET_BITS(s);
  600. s = HUFF_EXTEND(r, s);
  601. (*block)[jpeg_natural_order[k]] = (JCOEF)s;
  602. } else {
  603. if (r != 15) break;
  604. k += 15;
  605. }
  606. }
  607. } else {
  608. for (k = 1; k < DCTSIZE2; k++) {
  609. HUFF_DECODE_FAST(s, l, actbl);
  610. r = s >> 4;
  611. s &= 15;
  612. if (s) {
  613. k += r;
  614. FILL_BIT_BUFFER_FAST
  615. DROP_BITS(s);
  616. } else {
  617. if (r != 15) break;
  618. k += 15;
  619. }
  620. }
  621. }
  622. }
  623. if (cinfo->unread_marker != 0) {
  624. cinfo->unread_marker = 0;
  625. return FALSE;
  626. }
  627. br_state.bytes_in_buffer -= (buffer - br_state.next_input_byte);
  628. br_state.next_input_byte = buffer;
  629. BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
  630. entropy->saved = state;
  631. return TRUE;
  632. }
  633. /*
  634. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  635. * The coefficients are reordered from zigzag order into natural array order,
  636. * but are not dequantized.
  637. *
  638. * The i'th block of the MCU is stored into the block pointed to by
  639. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  640. * (Wholesale zeroing is usually a little faster than retail...)
  641. *
  642. * Returns FALSE if data source requested suspension. In that case no
  643. * changes have been made to permanent state. (Exception: some output
  644. * coefficients may already have been assigned. This is harmless for
  645. * this module, since we'll just re-assign them on the next call.)
  646. */
  647. #define BUFSIZE (DCTSIZE2 * 8)
  648. METHODDEF(boolean)
  649. decode_mcu(j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  650. {
  651. huff_entropy_ptr entropy = (huff_entropy_ptr)cinfo->entropy;
  652. int usefast = 1;
  653. /* Process restart marker if needed; may have to suspend */
  654. if (cinfo->restart_interval) {
  655. if (entropy->restarts_to_go == 0)
  656. if (!process_restart(cinfo))
  657. return FALSE;
  658. usefast = 0;
  659. }
  660. if (cinfo->src->bytes_in_buffer < BUFSIZE * (size_t)cinfo->blocks_in_MCU ||
  661. cinfo->unread_marker != 0)
  662. usefast = 0;
  663. /* If we've run out of data, just leave the MCU set to zeroes.
  664. * This way, we return uniform gray for the remainder of the segment.
  665. */
  666. if (!entropy->pub.insufficient_data) {
  667. if (usefast) {
  668. if (!decode_mcu_fast(cinfo, MCU_data)) goto use_slow;
  669. } else {
  670. use_slow:
  671. if (!decode_mcu_slow(cinfo, MCU_data)) return FALSE;
  672. }
  673. }
  674. /* Account for restart interval (no-op if not using restarts) */
  675. if (cinfo->restart_interval)
  676. entropy->restarts_to_go--;
  677. return TRUE;
  678. }
  679. /*
  680. * Module initialization routine for Huffman entropy decoding.
  681. */
  682. GLOBAL(void)
  683. jinit_huff_decoder(j_decompress_ptr cinfo)
  684. {
  685. huff_entropy_ptr entropy;
  686. int i;
  687. /* Motion JPEG frames typically do not include the Huffman tables if they
  688. are the default tables. Thus, if the tables are not set by the time
  689. the Huffman decoder is initialized (usually within the body of
  690. jpeg_start_decompress()), we set them to default values. */
  691. std_huff_tables((j_common_ptr)cinfo);
  692. entropy = (huff_entropy_ptr)
  693. (*cinfo->mem->alloc_small) ((j_common_ptr)cinfo, JPOOL_IMAGE,
  694. sizeof(huff_entropy_decoder));
  695. cinfo->entropy = (struct jpeg_entropy_decoder *)entropy;
  696. entropy->pub.start_pass = start_pass_huff_decoder;
  697. entropy->pub.decode_mcu = decode_mcu;
  698. /* Mark tables unallocated */
  699. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  700. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  701. }
  702. }