Source code of Windows XP (NT5)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

574 lines
17 KiB

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