jdhuff.c 25 KB

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