jdhuff.c 25 KB

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