jdhuff.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581
  1. /*
  2. * jdhuff.c
  3. *
  4. * Copyright (C) 1991-1995, Thomas G. Lane.
  5. * This file is part of the Independent JPEG Group's software.
  6. * For conditions of distribution and use, see the accompanying README file.
  7. *
  8. * This file contains Huffman entropy decoding routines.
  9. *
  10. * Much of the complexity here has to do with supporting input suspension.
  11. * If the data source module demands suspension, we want to be able to back
  12. * up to the start of the current MCU. To do this, we copy state variables
  13. * into local working storage, and update them back to the permanent
  14. * storage only upon successful completion of an MCU.
  15. */
  16. // leave this as first line for PCH reasons...
  17. //
  18. #include "../server/exe_headers.h"
  19. #define JPEG_INTERNALS
  20. #include "jinclude.h"
  21. #include "jpeglib.h"
  22. #include "jdhuff.h" /* Declarations shared with jdphuff.c */
  23. /*
  24. * Expanded entropy decoder object for Huffman decoding.
  25. *
  26. * The savable_state subrecord contains fields that change within an MCU,
  27. * but must not be updated permanently until we complete the MCU.
  28. */
  29. typedef struct {
  30. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  31. } savable_state;
  32. /* This macro is to work around compilers with missing or broken
  33. * structure assignment. You'll need to fix this code if you have
  34. * such a compiler and you change MAX_COMPS_IN_SCAN.
  35. */
  36. #ifndef NO_STRUCT_ASSIGN
  37. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  38. #else
  39. #if MAX_COMPS_IN_SCAN == 4
  40. #define ASSIGN_STATE(dest,src) \
  41. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  42. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  43. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  44. (dest).last_dc_val[3] = (src).last_dc_val[3])
  45. #endif
  46. #endif
  47. typedef struct {
  48. struct jpeg_entropy_decoder pub; /* public fields */
  49. /* These fields are loaded into local variables at start of each MCU.
  50. * In case of suspension, we exit WITHOUT updating them.
  51. */
  52. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  53. savable_state saved; /* Other state at start of MCU */
  54. /* These fields are NOT loaded into local working state. */
  55. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  56. /* Pointers to derived tables (these workspaces have image lifespan) */
  57. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  58. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  59. } huff_entropy_decoder;
  60. typedef huff_entropy_decoder * huff_entropy_ptr;
  61. /*
  62. * Initialize for a Huffman-compressed scan.
  63. */
  64. METHODDEF void
  65. start_pass_huff_decoder (j_decompress_ptr cinfo)
  66. {
  67. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  68. int ci, dctbl, actbl;
  69. jpeg_component_info * compptr;
  70. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  71. * This ought to be an error condition, but we make it a warning because
  72. * there are some baseline files out there with all zeroes in these bytes.
  73. */
  74. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  75. cinfo->Ah != 0 || cinfo->Al != 0)
  76. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  77. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  78. compptr = cinfo->cur_comp_info[ci];
  79. dctbl = compptr->dc_tbl_no;
  80. actbl = compptr->ac_tbl_no;
  81. /* Make sure requested tables are present */
  82. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
  83. cinfo->dc_huff_tbl_ptrs[dctbl] == NULL)
  84. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  85. if (actbl < 0 || actbl >= NUM_HUFF_TBLS ||
  86. cinfo->ac_huff_tbl_ptrs[actbl] == NULL)
  87. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  88. /* Compute derived values for Huffman tables */
  89. /* We may do this more than once for a table, but it's not expensive */
  90. jpeg_make_d_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
  91. & entropy->dc_derived_tbls[dctbl]);
  92. jpeg_make_d_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
  93. & entropy->ac_derived_tbls[actbl]);
  94. /* Initialize DC predictions to 0 */
  95. entropy->saved.last_dc_val[ci] = 0;
  96. }
  97. /* Initialize bitread state variables */
  98. entropy->bitstate.bits_left = 0;
  99. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  100. entropy->bitstate.printed_eod = FALSE;
  101. /* Initialize restart counter */
  102. entropy->restarts_to_go = cinfo->restart_interval;
  103. }
  104. /*
  105. * Compute the derived values for a Huffman table.
  106. * Note this is also used by jdphuff.c.
  107. */
  108. GLOBAL void
  109. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, JHUFF_TBL * htbl,
  110. d_derived_tbl ** pdtbl)
  111. {
  112. d_derived_tbl *dtbl;
  113. int p, i, l, si;
  114. int lookbits, ctr;
  115. char huffsize[257];
  116. unsigned int huffcode[257];
  117. unsigned int code;
  118. /* Allocate a workspace if we haven't already done so. */
  119. if (*pdtbl == NULL)
  120. *pdtbl = (d_derived_tbl *)
  121. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  122. SIZEOF(d_derived_tbl));
  123. dtbl = *pdtbl;
  124. dtbl->pub = htbl; /* fill in back link */
  125. /* Figure C.1: make table of Huffman code length for each symbol */
  126. /* Note that this is in code-length order. */
  127. p = 0;
  128. for (l = 1; l <= 16; l++) {
  129. for (i = 1; i <= (int) htbl->bits[l]; i++)
  130. huffsize[p++] = (char) l;
  131. }
  132. huffsize[p] = 0;
  133. /* Figure C.2: generate the codes themselves */
  134. /* Note that this is in code-length order. */
  135. code = 0;
  136. si = huffsize[0];
  137. p = 0;
  138. while (huffsize[p]) {
  139. while (((int) huffsize[p]) == si) {
  140. huffcode[p++] = code;
  141. code++;
  142. }
  143. code <<= 1;
  144. si++;
  145. }
  146. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  147. p = 0;
  148. for (l = 1; l <= 16; l++) {
  149. if (htbl->bits[l]) {
  150. dtbl->valptr[l] = p; /* huffval[] index of 1st symbol of code length l */
  151. dtbl->mincode[l] = huffcode[p]; /* minimum code of length l */
  152. p += htbl->bits[l];
  153. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  154. } else {
  155. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  156. }
  157. }
  158. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  159. /* Compute lookahead tables to speed up decoding.
  160. * First we set all the table entries to 0, indicating "too long";
  161. * then we iterate through the Huffman codes that are short enough and
  162. * fill in all the entries that correspond to bit sequences starting
  163. * with that code.
  164. */
  165. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  166. p = 0;
  167. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  168. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  169. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170. /* Generate left-justified code followed by all possible bit sequences */
  171. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  172. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  173. dtbl->look_nbits[lookbits] = l;
  174. dtbl->look_sym[lookbits] = htbl->huffval[p];
  175. lookbits++;
  176. }
  177. }
  178. }
  179. }
  180. /*
  181. * Out-of-line code for bit fetching (shared with jdphuff.c).
  182. * See jdhuff.h for info about usage.
  183. * Note: current values of get_buffer and bits_left are passed as parameters,
  184. * but are returned in the corresponding fields of the state struct.
  185. *
  186. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  187. * of get_buffer to be used. (On machines with wider words, an even larger
  188. * buffer could be used.) However, on some machines 32-bit shifts are
  189. * quite slow and take time proportional to the number of places shifted.
  190. * (This is true with most PC compilers, for instance.) In this case it may
  191. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  192. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  193. */
  194. #ifdef SLOW_SHIFT_32
  195. #define MIN_GET_BITS 15 /* minimum allowable value */
  196. #else
  197. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  198. #endif
  199. GLOBAL boolean
  200. jpeg_fill_bit_buffer (bitread_working_state * state,
  201. register bit_buf_type get_buffer, register int bits_left,
  202. int nbits)
  203. /* Load up the bit buffer to a depth of at least nbits */
  204. {
  205. /* Copy heavily used state fields into locals (hopefully registers) */
  206. register const JOCTET * next_input_byte = state->next_input_byte;
  207. register size_t bytes_in_buffer = state->bytes_in_buffer;
  208. register int c;
  209. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  210. /* (It is assumed that no request will be for more than that many bits.) */
  211. while (bits_left < MIN_GET_BITS) {
  212. /* Attempt to read a byte */
  213. if (state->unread_marker != 0)
  214. goto no_more_data; /* can't advance past a marker */
  215. if (bytes_in_buffer == 0) {
  216. if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo))
  217. return FALSE;
  218. next_input_byte = state->cinfo->src->next_input_byte;
  219. bytes_in_buffer = state->cinfo->src->bytes_in_buffer;
  220. }
  221. bytes_in_buffer--;
  222. c = GETJOCTET(*next_input_byte++);
  223. /* If it's 0xFF, check and discard stuffed zero byte */
  224. if (c == 0xFF) {
  225. do {
  226. if (bytes_in_buffer == 0) {
  227. if (! (*state->cinfo->src->fill_input_buffer) (state->cinfo))
  228. return FALSE;
  229. next_input_byte = state->cinfo->src->next_input_byte;
  230. bytes_in_buffer = state->cinfo->src->bytes_in_buffer;
  231. }
  232. bytes_in_buffer--;
  233. c = GETJOCTET(*next_input_byte++);
  234. } while (c == 0xFF);
  235. if (c == 0) {
  236. /* Found FF/00, which represents an FF data byte */
  237. c = 0xFF;
  238. } else {
  239. /* Oops, it's actually a marker indicating end of compressed data. */
  240. /* Better put it back for use later */
  241. state->unread_marker = c;
  242. no_more_data:
  243. /* There should be enough bits still left in the data segment; */
  244. /* if so, just break out of the outer while loop. */
  245. if (bits_left >= nbits)
  246. break;
  247. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  248. * the data stream, so that we can produce some kind of image.
  249. * Note that this code will be repeated for each byte demanded
  250. * for the rest of the segment. We use a nonvolatile flag to ensure
  251. * that only one warning message appears.
  252. */
  253. if (! *(state->printed_eod_ptr)) {
  254. WARNMS(state->cinfo, JWRN_HIT_MARKER);
  255. *(state->printed_eod_ptr) = TRUE;
  256. }
  257. c = 0; /* insert a zero byte into bit buffer */
  258. }
  259. }
  260. /* OK, load c into get_buffer */
  261. get_buffer = (get_buffer << 8) | c;
  262. bits_left += 8;
  263. }
  264. /* Unload the local registers */
  265. state->next_input_byte = next_input_byte;
  266. state->bytes_in_buffer = bytes_in_buffer;
  267. state->get_buffer = get_buffer;
  268. state->bits_left = bits_left;
  269. return TRUE;
  270. }
  271. /*
  272. * Out-of-line code for Huffman code decoding.
  273. * See jdhuff.h for info about usage.
  274. */
  275. GLOBAL int
  276. jpeg_huff_decode (bitread_working_state * state,
  277. register bit_buf_type get_buffer, register int bits_left,
  278. d_derived_tbl * htbl, int min_bits)
  279. {
  280. register int l = min_bits;
  281. register INT32 code;
  282. /* HUFF_DECODE has determined that the code is at least min_bits */
  283. /* bits long, so fetch that many bits in one swoop. */
  284. CHECK_BIT_BUFFER(*state, l, return -1);
  285. code = GET_BITS(l);
  286. /* Collect the rest of the Huffman code one bit at a time. */
  287. /* This is per Figure F.16 in the JPEG spec. */
  288. while (code > htbl->maxcode[l]) {
  289. code <<= 1;
  290. CHECK_BIT_BUFFER(*state, 1, return -1);
  291. code |= GET_BITS(1);
  292. l++;
  293. }
  294. /* Unload the local registers */
  295. state->get_buffer = get_buffer;
  296. state->bits_left = bits_left;
  297. /* With garbage input we may reach the sentinel value l = 17. */
  298. if (l > 16) {
  299. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  300. return 0; /* fake a zero as the safest result */
  301. }
  302. return htbl->pub->huffval[ htbl->valptr[l] +
  303. ((int) (code - htbl->mincode[l])) ];
  304. }
  305. /*
  306. * Figure F.12: extend sign bit.
  307. * On some machines, a shift and add will be faster than a table lookup.
  308. */
  309. #ifdef AVOID_TABLES
  310. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  311. #else
  312. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  313. static const int extend_test[16] = /* entry n is 2**(n-1) */
  314. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  315. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  316. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  317. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  318. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  319. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  320. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  321. #endif /* AVOID_TABLES */
  322. /*
  323. * Check for a restart marker & resynchronize decoder.
  324. * Returns FALSE if must suspend.
  325. */
  326. LOCAL boolean
  327. process_restart (j_decompress_ptr cinfo)
  328. {
  329. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  330. int ci;
  331. /* Throw away any unused bits remaining in bit buffer; */
  332. /* include any full bytes in next_marker's count of discarded bytes */
  333. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  334. entropy->bitstate.bits_left = 0;
  335. /* Advance past the RSTn marker */
  336. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  337. return FALSE;
  338. /* Re-initialize DC predictions to 0 */
  339. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  340. entropy->saved.last_dc_val[ci] = 0;
  341. /* Reset restart counter */
  342. entropy->restarts_to_go = cinfo->restart_interval;
  343. /* Next segment can get another out-of-data warning */
  344. entropy->bitstate.printed_eod = FALSE;
  345. return TRUE;
  346. }
  347. /*
  348. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  349. * The coefficients are reordered from zigzag order into natural array order,
  350. * but are not dequantized.
  351. *
  352. * The i'th block of the MCU is stored into the block pointed to by
  353. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  354. * (Wholesale zeroing is usually a little faster than retail...)
  355. *
  356. * Returns FALSE if data source requested suspension. In that case no
  357. * changes have been made to permanent state. (Exception: some output
  358. * coefficients may already have been assigned. This is harmless for
  359. * this module, since we'll just re-assign them on the next call.)
  360. */
  361. METHODDEF boolean
  362. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  363. {
  364. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  365. register int s, k, r;
  366. int blkn, ci;
  367. JBLOCKROW block;
  368. BITREAD_STATE_VARS;
  369. savable_state state;
  370. d_derived_tbl * dctbl;
  371. d_derived_tbl * actbl;
  372. jpeg_component_info * compptr;
  373. /* Process restart marker if needed; may have to suspend */
  374. if (cinfo->restart_interval) {
  375. if (entropy->restarts_to_go == 0)
  376. if (! process_restart(cinfo))
  377. return FALSE;
  378. }
  379. /* Load up working state */
  380. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  381. ASSIGN_STATE(state, entropy->saved);
  382. /* Outer loop handles each block in the MCU */
  383. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  384. block = MCU_data[blkn];
  385. ci = cinfo->MCU_membership[blkn];
  386. compptr = cinfo->cur_comp_info[ci];
  387. dctbl = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  388. actbl = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  389. /* Decode a single block's worth of coefficients */
  390. /* Section F.2.2.1: decode the DC coefficient difference */
  391. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  392. if (s) {
  393. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  394. r = GET_BITS(s);
  395. s = HUFF_EXTEND(r, s);
  396. }
  397. /* Shortcut if component's values are not interesting */
  398. if (! compptr->component_needed)
  399. goto skip_ACs;
  400. /* Convert DC difference to actual value, update last_dc_val */
  401. s += state.last_dc_val[ci];
  402. state.last_dc_val[ci] = s;
  403. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  404. (*block)[0] = (JCOEF) s;
  405. /* Do we need to decode the AC coefficients for this component? */
  406. if (compptr->DCT_scaled_size > 1) {
  407. /* Section F.2.2.2: decode the AC coefficients */
  408. /* Since zeroes are skipped, output area must be cleared beforehand */
  409. for (k = 1; k < DCTSIZE2; k++) {
  410. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  411. r = s >> 4;
  412. s &= 15;
  413. if (s) {
  414. k += r;
  415. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  416. r = GET_BITS(s);
  417. s = HUFF_EXTEND(r, s);
  418. /* Output coefficient in natural (dezigzagged) order.
  419. * Note: the extra entries in jpeg_natural_order[] will save us
  420. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  421. */
  422. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  423. } else {
  424. if (r != 15)
  425. break;
  426. k += 15;
  427. }
  428. }
  429. } else {
  430. skip_ACs:
  431. /* Section F.2.2.2: decode the AC coefficients */
  432. /* In this path we just discard the values */
  433. for (k = 1; k < DCTSIZE2; k++) {
  434. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  435. r = s >> 4;
  436. s &= 15;
  437. if (s) {
  438. k += r;
  439. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  440. DROP_BITS(s);
  441. } else {
  442. if (r != 15)
  443. break;
  444. k += 15;
  445. }
  446. }
  447. }
  448. }
  449. /* Completed MCU, so update state */
  450. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  451. ASSIGN_STATE(entropy->saved, state);
  452. /* Account for restart interval (no-op if not using restarts) */
  453. entropy->restarts_to_go--;
  454. return TRUE;
  455. }
  456. /*
  457. * Module initialization routine for Huffman entropy decoding.
  458. */
  459. GLOBAL void
  460. jinit_huff_decoder (j_decompress_ptr cinfo)
  461. {
  462. huff_entropy_ptr entropy;
  463. int i;
  464. entropy = (huff_entropy_ptr)
  465. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  466. SIZEOF(huff_entropy_decoder));
  467. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  468. entropy->pub.start_pass = start_pass_huff_decoder;
  469. entropy->pub.decode_mcu = decode_mcu;
  470. /* Mark tables unallocated */
  471. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  472. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  473. }
  474. }