Team Fortress 2 Source Code as on 22/4/2020
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.

1541 lines
47 KiB

  1. /*
  2. * jdhuff.c
  3. *
  4. * Copyright (C) 1991-1997, Thomas G. Lane.
  5. * Modified 2006-2009 by Guido Vollbeding.
  6. * This file is part of the Independent JPEG Group's software.
  7. * For conditions of distribution and use, see the accompanying README file.
  8. *
  9. * This file contains Huffman entropy decoding routines.
  10. * Both sequential and progressive modes are supported in this single module.
  11. *
  12. * Much of the complexity here has to do with supporting input suspension.
  13. * If the data source module demands suspension, we want to be able to back
  14. * up to the start of the current MCU. To do this, we copy state variables
  15. * into local working storage, and update them back to the permanent
  16. * storage only upon successful completion of an MCU.
  17. */
  18. #define JPEG_INTERNALS
  19. #include "jinclude.h"
  20. #include "jpeglib.h"
  21. /* Derived data constructed for each Huffman table */
  22. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  23. typedef struct {
  24. /* Basic tables: (element [0] of each array is unused) */
  25. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  26. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  27. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  28. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  29. * the smallest code of length k; so given a code of length k, the
  30. * corresponding symbol is huffval[code + valoffset[k]]
  31. */
  32. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  33. JHUFF_TBL *pub;
  34. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  35. * the input data stream. If the next Huffman code is no more
  36. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  37. * the corresponding symbol directly from these tables.
  38. */
  39. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  40. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  41. } d_derived_tbl;
  42. /*
  43. * Fetching the next N bits from the input stream is a time-critical operation
  44. * for the Huffman decoders. We implement it with a combination of inline
  45. * macros and out-of-line subroutines. Note that N (the number of bits
  46. * demanded at one time) never exceeds 15 for JPEG use.
  47. *
  48. * We read source bytes into get_buffer and dole out bits as needed.
  49. * If get_buffer already contains enough bits, they are fetched in-line
  50. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  51. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  52. * as full as possible (not just to the number of bits needed; this
  53. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  54. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  55. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  56. * at least the requested number of bits --- dummy zeroes are inserted if
  57. * necessary.
  58. */
  59. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  60. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  61. /* If long is > 32 bits on your machine, and shifting/masking longs is
  62. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  63. * appropriately should be a win. Unfortunately we can't define the size
  64. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  65. * because not all machines measure sizeof in 8-bit bytes.
  66. */
  67. typedef struct { /* Bitreading state saved across MCUs */
  68. bit_buf_type get_buffer; /* current bit-extraction buffer */
  69. int bits_left; /* # of unused bits in it */
  70. } bitread_perm_state;
  71. typedef struct { /* Bitreading working state within an MCU */
  72. /* Current data source location */
  73. /* We need a copy, rather than munging the original, in case of suspension */
  74. const JOCTET * next_input_byte; /* => next byte to read from source */
  75. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  76. /* Bit input buffer --- note these values are kept in register variables,
  77. * not in this struct, inside the inner loops.
  78. */
  79. bit_buf_type get_buffer; /* current bit-extraction buffer */
  80. int bits_left; /* # of unused bits in it */
  81. /* Pointer needed by jpeg_fill_bit_buffer. */
  82. j_decompress_ptr cinfo; /* back link to decompress master record */
  83. } bitread_working_state;
  84. /* Macros to declare and load/save bitread local variables. */
  85. #define BITREAD_STATE_VARS \
  86. bit_buf_type get_buffer; \
  87. int bits_left; \
  88. bitread_working_state br_state
  89. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  90. br_state.cinfo = cinfop; \
  91. br_state.next_input_byte = cinfop->src->next_input_byte; \
  92. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  93. get_buffer = permstate.get_buffer; \
  94. bits_left = permstate.bits_left;
  95. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  96. cinfop->src->next_input_byte = br_state.next_input_byte; \
  97. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  98. permstate.get_buffer = get_buffer; \
  99. permstate.bits_left = bits_left
  100. /*
  101. * These macros provide the in-line portion of bit fetching.
  102. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  103. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  104. * The variables get_buffer and bits_left are assumed to be locals,
  105. * but the state struct might not be (jpeg_huff_decode needs this).
  106. * CHECK_BIT_BUFFER(state,n,action);
  107. * Ensure there are N bits in get_buffer; if suspend, take action.
  108. * val = GET_BITS(n);
  109. * Fetch next N bits.
  110. * val = PEEK_BITS(n);
  111. * Fetch next N bits without removing them from the buffer.
  112. * DROP_BITS(n);
  113. * Discard next N bits.
  114. * The value N should be a simple variable, not an expression, because it
  115. * is evaluated multiple times.
  116. */
  117. #define CHECK_BIT_BUFFER(state,nbits,action) \
  118. { if (bits_left < (nbits)) { \
  119. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  120. { action; } \
  121. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  122. #define GET_BITS(nbits) \
  123. (((int) (get_buffer >> (bits_left -= (nbits)))) & BIT_MASK(nbits))
  124. #define PEEK_BITS(nbits) \
  125. (((int) (get_buffer >> (bits_left - (nbits)))) & BIT_MASK(nbits))
  126. #define DROP_BITS(nbits) \
  127. (bits_left -= (nbits))
  128. /*
  129. * Code for extracting next Huffman-coded symbol from input bit stream.
  130. * Again, this is time-critical and we make the main paths be macros.
  131. *
  132. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  133. * without looping. Usually, more than 95% of the Huffman codes will be 8
  134. * or fewer bits long. The few overlength codes are handled with a loop,
  135. * which need not be inline code.
  136. *
  137. * Notes about the HUFF_DECODE macro:
  138. * 1. Near the end of the data segment, we may fail to get enough bits
  139. * for a lookahead. In that case, we do it the hard way.
  140. * 2. If the lookahead table contains no entry, the next code must be
  141. * more than HUFF_LOOKAHEAD bits long.
  142. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  143. */
  144. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  145. { int nb, look; \
  146. if (bits_left < HUFF_LOOKAHEAD) { \
  147. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  148. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  149. if (bits_left < HUFF_LOOKAHEAD) { \
  150. nb = 1; goto slowlabel; \
  151. } \
  152. } \
  153. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  154. if ((nb = htbl->look_nbits[look]) != 0) { \
  155. DROP_BITS(nb); \
  156. result = htbl->look_sym[look]; \
  157. } else { \
  158. nb = HUFF_LOOKAHEAD+1; \
  159. slowlabel: \
  160. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  161. { failaction; } \
  162. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  163. } \
  164. }
  165. /*
  166. * Expanded entropy decoder object for Huffman decoding.
  167. *
  168. * The savable_state subrecord contains fields that change within an MCU,
  169. * but must not be updated permanently until we complete the MCU.
  170. */
  171. typedef struct {
  172. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  174. } savable_state;
  175. /* This macro is to work around compilers with missing or broken
  176. * structure assignment. You'll need to fix this code if you have
  177. * such a compiler and you change MAX_COMPS_IN_SCAN.
  178. */
  179. #ifndef NO_STRUCT_ASSIGN
  180. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  181. #else
  182. #if MAX_COMPS_IN_SCAN == 4
  183. #define ASSIGN_STATE(dest,src) \
  184. ((dest).EOBRUN = (src).EOBRUN, \
  185. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  186. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  187. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  188. (dest).last_dc_val[3] = (src).last_dc_val[3])
  189. #endif
  190. #endif
  191. typedef struct {
  192. struct jpeg_entropy_decoder pub; /* public fields */
  193. /* These fields are loaded into local variables at start of each MCU.
  194. * In case of suspension, we exit WITHOUT updating them.
  195. */
  196. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  197. savable_state saved; /* Other state at start of MCU */
  198. /* These fields are NOT loaded into local working state. */
  199. boolean insufficient_data; /* set TRUE after emitting warning */
  200. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  201. /* Following two fields used only in progressive mode */
  202. /* Pointers to derived tables (these workspaces have image lifespan) */
  203. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  204. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  205. /* Following fields used only in sequential mode */
  206. /* Pointers to derived tables (these workspaces have image lifespan) */
  207. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  208. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  209. /* Precalculated info set up by start_pass for use in decode_mcu: */
  210. /* Pointers to derived tables to be used for each block within an MCU */
  211. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  212. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  213. /* Whether we care about the DC and AC coefficient values for each block */
  214. int coef_limit[D_MAX_BLOCKS_IN_MCU];
  215. } huff_entropy_decoder;
  216. typedef huff_entropy_decoder * huff_entropy_ptr;
  217. static const int jpeg_zigzag_order[8][8] = {
  218. { 0, 1, 5, 6, 14, 15, 27, 28 },
  219. { 2, 4, 7, 13, 16, 26, 29, 42 },
  220. { 3, 8, 12, 17, 25, 30, 41, 43 },
  221. { 9, 11, 18, 24, 31, 40, 44, 53 },
  222. { 10, 19, 23, 32, 39, 45, 52, 54 },
  223. { 20, 22, 33, 38, 46, 51, 55, 60 },
  224. { 21, 34, 37, 47, 50, 56, 59, 61 },
  225. { 35, 36, 48, 49, 57, 58, 62, 63 }
  226. };
  227. static const int jpeg_zigzag_order7[7][7] = {
  228. { 0, 1, 5, 6, 14, 15, 27 },
  229. { 2, 4, 7, 13, 16, 26, 28 },
  230. { 3, 8, 12, 17, 25, 29, 38 },
  231. { 9, 11, 18, 24, 30, 37, 39 },
  232. { 10, 19, 23, 31, 36, 40, 45 },
  233. { 20, 22, 32, 35, 41, 44, 46 },
  234. { 21, 33, 34, 42, 43, 47, 48 }
  235. };
  236. static const int jpeg_zigzag_order6[6][6] = {
  237. { 0, 1, 5, 6, 14, 15 },
  238. { 2, 4, 7, 13, 16, 25 },
  239. { 3, 8, 12, 17, 24, 26 },
  240. { 9, 11, 18, 23, 27, 32 },
  241. { 10, 19, 22, 28, 31, 33 },
  242. { 20, 21, 29, 30, 34, 35 }
  243. };
  244. static const int jpeg_zigzag_order5[5][5] = {
  245. { 0, 1, 5, 6, 14 },
  246. { 2, 4, 7, 13, 15 },
  247. { 3, 8, 12, 16, 21 },
  248. { 9, 11, 17, 20, 22 },
  249. { 10, 18, 19, 23, 24 }
  250. };
  251. static const int jpeg_zigzag_order4[4][4] = {
  252. { 0, 1, 5, 6 },
  253. { 2, 4, 7, 12 },
  254. { 3, 8, 11, 13 },
  255. { 9, 10, 14, 15 }
  256. };
  257. static const int jpeg_zigzag_order3[3][3] = {
  258. { 0, 1, 5 },
  259. { 2, 4, 6 },
  260. { 3, 7, 8 }
  261. };
  262. static const int jpeg_zigzag_order2[2][2] = {
  263. { 0, 1 },
  264. { 2, 3 }
  265. };
  266. /*
  267. * Compute the derived values for a Huffman table.
  268. * This routine also performs some validation checks on the table.
  269. */
  270. LOCAL(void)
  271. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  272. d_derived_tbl ** pdtbl)
  273. {
  274. JHUFF_TBL *htbl;
  275. d_derived_tbl *dtbl;
  276. int p, i, l, si, numsymbols;
  277. int lookbits, ctr;
  278. char huffsize[257];
  279. unsigned int huffcode[257];
  280. unsigned int code;
  281. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  282. * paralleling the order of the symbols themselves in htbl->huffval[].
  283. */
  284. /* Find the input Huffman table */
  285. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  286. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  287. htbl =
  288. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  289. if (htbl == NULL)
  290. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  291. /* Allocate a workspace if we haven't already done so. */
  292. if (*pdtbl == NULL)
  293. *pdtbl = (d_derived_tbl *)
  294. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  295. SIZEOF(d_derived_tbl));
  296. dtbl = *pdtbl;
  297. dtbl->pub = htbl; /* fill in back link */
  298. /* Figure C.1: make table of Huffman code length for each symbol */
  299. p = 0;
  300. for (l = 1; l <= 16; l++) {
  301. i = (int) htbl->bits[l];
  302. if (i < 0 || p + i > 256) /* protect against table overrun */
  303. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  304. while (i--)
  305. huffsize[p++] = (char) l;
  306. }
  307. huffsize[p] = 0;
  308. numsymbols = p;
  309. /* Figure C.2: generate the codes themselves */
  310. /* We also validate that the counts represent a legal Huffman code tree. */
  311. code = 0;
  312. si = huffsize[0];
  313. p = 0;
  314. while (huffsize[p]) {
  315. while (((int) huffsize[p]) == si) {
  316. huffcode[p++] = code;
  317. code++;
  318. }
  319. /* code is now 1 more than the last code used for codelength si; but
  320. * it must still fit in si bits, since no code is allowed to be all ones.
  321. */
  322. if (((INT32) code) >= (((INT32) 1) << si))
  323. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  324. code <<= 1;
  325. si++;
  326. }
  327. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  328. p = 0;
  329. for (l = 1; l <= 16; l++) {
  330. if (htbl->bits[l]) {
  331. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  332. * minus the minimum code of length l
  333. */
  334. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  335. p += htbl->bits[l];
  336. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  337. } else {
  338. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  339. }
  340. }
  341. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  342. /* Compute lookahead tables to speed up decoding.
  343. * First we set all the table entries to 0, indicating "too long";
  344. * then we iterate through the Huffman codes that are short enough and
  345. * fill in all the entries that correspond to bit sequences starting
  346. * with that code.
  347. */
  348. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  349. p = 0;
  350. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  351. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  352. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  353. /* Generate left-justified code followed by all possible bit sequences */
  354. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  355. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  356. dtbl->look_nbits[lookbits] = l;
  357. dtbl->look_sym[lookbits] = htbl->huffval[p];
  358. lookbits++;
  359. }
  360. }
  361. }
  362. /* Validate symbols as being reasonable.
  363. * For AC tables, we make no check, but accept all byte values 0..255.
  364. * For DC tables, we require the symbols to be in range 0..15.
  365. * (Tighter bounds could be applied depending on the data depth and mode,
  366. * but this is sufficient to ensure safe decoding.)
  367. */
  368. if (isDC) {
  369. for (i = 0; i < numsymbols; i++) {
  370. int sym = htbl->huffval[i];
  371. if (sym < 0 || sym > 15)
  372. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  373. }
  374. }
  375. }
  376. /*
  377. * Out-of-line code for bit fetching.
  378. * Note: current values of get_buffer and bits_left are passed as parameters,
  379. * but are returned in the corresponding fields of the state struct.
  380. *
  381. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  382. * of get_buffer to be used. (On machines with wider words, an even larger
  383. * buffer could be used.) However, on some machines 32-bit shifts are
  384. * quite slow and take time proportional to the number of places shifted.
  385. * (This is true with most PC compilers, for instance.) In this case it may
  386. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  387. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  388. */
  389. #ifdef SLOW_SHIFT_32
  390. #define MIN_GET_BITS 15 /* minimum allowable value */
  391. #else
  392. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  393. #endif
  394. LOCAL(boolean)
  395. jpeg_fill_bit_buffer (bitread_working_state * state,
  396. bit_buf_type get_buffer, int bits_left,
  397. int nbits)
  398. /* Load up the bit buffer to a depth of at least nbits */
  399. {
  400. /* Copy heavily used state fields into locals (hopefully registers) */
  401. const JOCTET * next_input_byte = state->next_input_byte;
  402. size_t bytes_in_buffer = state->bytes_in_buffer;
  403. j_decompress_ptr cinfo = state->cinfo;
  404. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  405. /* (It is assumed that no request will be for more than that many bits.) */
  406. /* We fail to do so only if we hit a marker or are forced to suspend. */
  407. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  408. while (bits_left < MIN_GET_BITS) {
  409. int c;
  410. /* Attempt to read a byte */
  411. if (bytes_in_buffer == 0) {
  412. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  413. return FALSE;
  414. next_input_byte = cinfo->src->next_input_byte;
  415. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  416. }
  417. bytes_in_buffer--;
  418. c = GETJOCTET(*next_input_byte++);
  419. /* If it's 0xFF, check and discard stuffed zero byte */
  420. if (c == 0xFF) {
  421. /* Loop here to discard any padding FF's on terminating marker,
  422. * so that we can save a valid unread_marker value. NOTE: we will
  423. * accept multiple FF's followed by a 0 as meaning a single FF data
  424. * byte. This data pattern is not valid according to the standard.
  425. */
  426. do {
  427. if (bytes_in_buffer == 0) {
  428. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  429. return FALSE;
  430. next_input_byte = cinfo->src->next_input_byte;
  431. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  432. }
  433. bytes_in_buffer--;
  434. c = GETJOCTET(*next_input_byte++);
  435. } while (c == 0xFF);
  436. if (c == 0) {
  437. /* Found FF/00, which represents an FF data byte */
  438. c = 0xFF;
  439. } else {
  440. /* Oops, it's actually a marker indicating end of compressed data.
  441. * Save the marker code for later use.
  442. * Fine point: it might appear that we should save the marker into
  443. * bitread working state, not straight into permanent state. But
  444. * once we have hit a marker, we cannot need to suspend within the
  445. * current MCU, because we will read no more bytes from the data
  446. * source. So it is OK to update permanent state right away.
  447. */
  448. cinfo->unread_marker = c;
  449. /* See if we need to insert some fake zero bits. */
  450. goto no_more_bytes;
  451. }
  452. }
  453. /* OK, load c into get_buffer */
  454. get_buffer = (get_buffer << 8) | c;
  455. bits_left += 8;
  456. } /* end while */
  457. } else {
  458. no_more_bytes:
  459. /* We get here if we've read the marker that terminates the compressed
  460. * data segment. There should be enough bits in the buffer register
  461. * to satisfy the request; if so, no problem.
  462. */
  463. if (nbits > bits_left) {
  464. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  465. * the data stream, so that we can produce some kind of image.
  466. * We use a nonvolatile flag to ensure that only one warning message
  467. * appears per data segment.
  468. */
  469. if (! ((huff_entropy_ptr) cinfo->entropy)->insufficient_data) {
  470. WARNMS(cinfo, JWRN_HIT_MARKER);
  471. ((huff_entropy_ptr) cinfo->entropy)->insufficient_data = TRUE;
  472. }
  473. /* Fill the buffer with zero bits */
  474. get_buffer <<= MIN_GET_BITS - bits_left;
  475. bits_left = MIN_GET_BITS;
  476. }
  477. }
  478. /* Unload the local registers */
  479. state->next_input_byte = next_input_byte;
  480. state->bytes_in_buffer = bytes_in_buffer;
  481. state->get_buffer = get_buffer;
  482. state->bits_left = bits_left;
  483. return TRUE;
  484. }
  485. /*
  486. * Figure F.12: extend sign bit.
  487. * On some machines, a shift and sub will be faster than a table lookup.
  488. */
  489. #ifdef AVOID_TABLES
  490. #define BIT_MASK(nbits) ((1<<(nbits))-1)
  491. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))
  492. #else
  493. #define BIT_MASK(nbits) bmask[nbits]
  494. #define HUFF_EXTEND(x,s) ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))
  495. static const int bmask[16] = /* bmask[n] is mask for n rightmost bits */
  496. { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  497. 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
  498. #endif /* AVOID_TABLES */
  499. /*
  500. * Out-of-line code for Huffman code decoding.
  501. */
  502. LOCAL(int)
  503. jpeg_huff_decode (bitread_working_state * state,
  504. bit_buf_type get_buffer, int bits_left,
  505. d_derived_tbl * htbl, int min_bits)
  506. {
  507. int l = min_bits;
  508. INT32 code;
  509. /* HUFF_DECODE has determined that the code is at least min_bits */
  510. /* bits long, so fetch that many bits in one swoop. */
  511. CHECK_BIT_BUFFER(*state, l, return -1);
  512. code = GET_BITS(l);
  513. /* Collect the rest of the Huffman code one bit at a time. */
  514. /* This is per Figure F.16 in the JPEG spec. */
  515. while (code > htbl->maxcode[l]) {
  516. code <<= 1;
  517. CHECK_BIT_BUFFER(*state, 1, return -1);
  518. code |= GET_BITS(1);
  519. l++;
  520. }
  521. /* Unload the local registers */
  522. state->get_buffer = get_buffer;
  523. state->bits_left = bits_left;
  524. /* With garbage input we may reach the sentinel value l = 17. */
  525. if (l > 16) {
  526. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  527. return 0; /* fake a zero as the safest result */
  528. }
  529. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  530. }
  531. /*
  532. * Check for a restart marker & resynchronize decoder.
  533. * Returns FALSE if must suspend.
  534. */
  535. LOCAL(boolean)
  536. process_restart (j_decompress_ptr cinfo)
  537. {
  538. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  539. int ci;
  540. /* Throw away any unused bits remaining in bit buffer; */
  541. /* include any full bytes in next_marker's count of discarded bytes */
  542. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  543. entropy->bitstate.bits_left = 0;
  544. /* Advance past the RSTn marker */
  545. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  546. return FALSE;
  547. /* Re-initialize DC predictions to 0 */
  548. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  549. entropy->saved.last_dc_val[ci] = 0;
  550. /* Re-init EOB run count, too */
  551. entropy->saved.EOBRUN = 0;
  552. /* Reset restart counter */
  553. entropy->restarts_to_go = cinfo->restart_interval;
  554. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  555. * against a marker. In that case we will end up treating the next data
  556. * segment as empty, and we can avoid producing bogus output pixels by
  557. * leaving the flag set.
  558. */
  559. if (cinfo->unread_marker == 0)
  560. entropy->insufficient_data = FALSE;
  561. return TRUE;
  562. }
  563. /*
  564. * Huffman MCU decoding.
  565. * Each of these routines decodes and returns one MCU's worth of
  566. * Huffman-compressed coefficients.
  567. * The coefficients are reordered from zigzag order into natural array order,
  568. * but are not dequantized.
  569. *
  570. * The i'th block of the MCU is stored into the block pointed to by
  571. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  572. * (Wholesale zeroing is usually a little faster than retail...)
  573. *
  574. * We return FALSE if data source requested suspension. In that case no
  575. * changes have been made to permanent state. (Exception: some output
  576. * coefficients may already have been assigned. This is harmless for
  577. * spectral selection, since we'll just re-assign them on the next call.
  578. * Successive approximation AC refinement has to be more careful, however.)
  579. */
  580. /*
  581. * MCU decoding for DC initial scan (either spectral selection,
  582. * or first pass of successive approximation).
  583. */
  584. METHODDEF(boolean)
  585. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  586. {
  587. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  588. int Al = cinfo->Al;
  589. int s, r;
  590. int blkn, ci;
  591. JBLOCKROW block;
  592. BITREAD_STATE_VARS;
  593. savable_state state;
  594. d_derived_tbl * tbl;
  595. jpeg_component_info * compptr;
  596. /* Process restart marker if needed; may have to suspend */
  597. if (cinfo->restart_interval) {
  598. if (entropy->restarts_to_go == 0)
  599. if (! process_restart(cinfo))
  600. return FALSE;
  601. }
  602. /* If we've run out of data, just leave the MCU set to zeroes.
  603. * This way, we return uniform gray for the remainder of the segment.
  604. */
  605. if (! entropy->insufficient_data) {
  606. /* Load up working state */
  607. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  608. ASSIGN_STATE(state, entropy->saved);
  609. /* Outer loop handles each block in the MCU */
  610. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  611. block = MCU_data[blkn];
  612. ci = cinfo->MCU_membership[blkn];
  613. compptr = cinfo->cur_comp_info[ci];
  614. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  615. /* Decode a single block's worth of coefficients */
  616. /* Section F.2.2.1: decode the DC coefficient difference */
  617. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  618. if (s) {
  619. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  620. r = GET_BITS(s);
  621. s = HUFF_EXTEND(r, s);
  622. }
  623. /* Convert DC difference to actual value, update last_dc_val */
  624. s += state.last_dc_val[ci];
  625. state.last_dc_val[ci] = s;
  626. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  627. (*block)[0] = (JCOEF) (s << Al);
  628. }
  629. /* Completed MCU, so update state */
  630. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  631. ASSIGN_STATE(entropy->saved, state);
  632. }
  633. /* Account for restart interval (no-op if not using restarts) */
  634. entropy->restarts_to_go--;
  635. return TRUE;
  636. }
  637. /*
  638. * MCU decoding for AC initial scan (either spectral selection,
  639. * or first pass of successive approximation).
  640. */
  641. METHODDEF(boolean)
  642. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  643. {
  644. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  645. int s, k, r;
  646. unsigned int EOBRUN;
  647. int Se, Al;
  648. const int * natural_order;
  649. JBLOCKROW block;
  650. BITREAD_STATE_VARS;
  651. d_derived_tbl * tbl;
  652. /* Process restart marker if needed; may have to suspend */
  653. if (cinfo->restart_interval) {
  654. if (entropy->restarts_to_go == 0)
  655. if (! process_restart(cinfo))
  656. return FALSE;
  657. }
  658. /* If we've run out of data, just leave the MCU set to zeroes.
  659. * This way, we return uniform gray for the remainder of the segment.
  660. */
  661. if (! entropy->insufficient_data) {
  662. Se = cinfo->Se;
  663. Al = cinfo->Al;
  664. natural_order = cinfo->natural_order;
  665. /* Load up working state.
  666. * We can avoid loading/saving bitread state if in an EOB run.
  667. */
  668. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  669. /* There is always only one block per MCU */
  670. if (EOBRUN > 0) /* if it's a band of zeroes... */
  671. EOBRUN--; /* ...process it now (we do nothing) */
  672. else {
  673. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  674. block = MCU_data[0];
  675. tbl = entropy->ac_derived_tbl;
  676. for (k = cinfo->Ss; k <= Se; k++) {
  677. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  678. r = s >> 4;
  679. s &= 15;
  680. if (s) {
  681. k += r;
  682. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  683. r = GET_BITS(s);
  684. s = HUFF_EXTEND(r, s);
  685. /* Scale and output coefficient in natural (dezigzagged) order */
  686. (*block)[natural_order[k]] = (JCOEF) (s << Al);
  687. } else {
  688. if (r == 15) { /* ZRL */
  689. k += 15; /* skip 15 zeroes in band */
  690. } else { /* EOBr, run length is 2^r + appended bits */
  691. EOBRUN = 1 << r;
  692. if (r) { /* EOBr, r > 0 */
  693. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  694. r = GET_BITS(r);
  695. EOBRUN += r;
  696. }
  697. EOBRUN--; /* this band is processed at this moment */
  698. break; /* force end-of-band */
  699. }
  700. }
  701. }
  702. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  703. }
  704. /* Completed MCU, so update state */
  705. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  706. }
  707. /* Account for restart interval (no-op if not using restarts) */
  708. entropy->restarts_to_go--;
  709. return TRUE;
  710. }
  711. /*
  712. * MCU decoding for DC successive approximation refinement scan.
  713. * Note: we assume such scans can be multi-component, although the spec
  714. * is not very clear on the point.
  715. */
  716. METHODDEF(boolean)
  717. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  718. {
  719. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  720. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  721. int blkn;
  722. JBLOCKROW block;
  723. BITREAD_STATE_VARS;
  724. /* Process restart marker if needed; may have to suspend */
  725. if (cinfo->restart_interval) {
  726. if (entropy->restarts_to_go == 0)
  727. if (! process_restart(cinfo))
  728. return FALSE;
  729. }
  730. /* Not worth the cycles to check insufficient_data here,
  731. * since we will not change the data anyway if we read zeroes.
  732. */
  733. /* Load up working state */
  734. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  735. /* Outer loop handles each block in the MCU */
  736. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  737. block = MCU_data[blkn];
  738. /* Encoded data is simply the next bit of the two's-complement DC value */
  739. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  740. if (GET_BITS(1))
  741. (*block)[0] |= p1;
  742. /* Note: since we use |=, repeating the assignment later is safe */
  743. }
  744. /* Completed MCU, so update state */
  745. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  746. /* Account for restart interval (no-op if not using restarts) */
  747. entropy->restarts_to_go--;
  748. return TRUE;
  749. }
  750. /*
  751. * MCU decoding for AC successive approximation refinement scan.
  752. */
  753. METHODDEF(boolean)
  754. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  755. {
  756. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  757. int s, k, r;
  758. unsigned int EOBRUN;
  759. int Se, p1, m1;
  760. const int * natural_order;
  761. JBLOCKROW block;
  762. JCOEFPTR thiscoef;
  763. BITREAD_STATE_VARS;
  764. d_derived_tbl * tbl;
  765. int num_newnz;
  766. int newnz_pos[DCTSIZE2];
  767. /* Process restart marker if needed; may have to suspend */
  768. if (cinfo->restart_interval) {
  769. if (entropy->restarts_to_go == 0)
  770. if (! process_restart(cinfo))
  771. return FALSE;
  772. }
  773. /* If we've run out of data, don't modify the MCU.
  774. */
  775. if (! entropy->insufficient_data) {
  776. Se = cinfo->Se;
  777. p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  778. m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  779. natural_order = cinfo->natural_order;
  780. /* Load up working state */
  781. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  782. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  783. /* There is always only one block per MCU */
  784. block = MCU_data[0];
  785. tbl = entropy->ac_derived_tbl;
  786. /* If we are forced to suspend, we must undo the assignments to any newly
  787. * nonzero coefficients in the block, because otherwise we'd get confused
  788. * next time about which coefficients were already nonzero.
  789. * But we need not undo addition of bits to already-nonzero coefficients;
  790. * instead, we can test the current bit to see if we already did it.
  791. */
  792. num_newnz = 0;
  793. /* initialize coefficient loop counter to start of band */
  794. k = cinfo->Ss;
  795. if (EOBRUN == 0) {
  796. for (; k <= Se; k++) {
  797. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  798. r = s >> 4;
  799. s &= 15;
  800. if (s) {
  801. if (s != 1) /* size of new coef should always be 1 */
  802. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  803. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  804. if (GET_BITS(1))
  805. s = p1; /* newly nonzero coef is positive */
  806. else
  807. s = m1; /* newly nonzero coef is negative */
  808. } else {
  809. if (r != 15) {
  810. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  811. if (r) {
  812. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  813. r = GET_BITS(r);
  814. EOBRUN += r;
  815. }
  816. break; /* rest of block is handled by EOB logic */
  817. }
  818. /* note s = 0 for processing ZRL */
  819. }
  820. /* Advance over already-nonzero coefs and r still-zero coefs,
  821. * appending correction bits to the nonzeroes. A correction bit is 1
  822. * if the absolute value of the coefficient must be increased.
  823. */
  824. do {
  825. thiscoef = *block + natural_order[k];
  826. if (*thiscoef != 0) {
  827. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  828. if (GET_BITS(1)) {
  829. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  830. if (*thiscoef >= 0)
  831. *thiscoef += p1;
  832. else
  833. *thiscoef += m1;
  834. }
  835. }
  836. } else {
  837. if (--r < 0)
  838. break; /* reached target zero coefficient */
  839. }
  840. k++;
  841. } while (k <= Se);
  842. if (s) {
  843. int pos = natural_order[k];
  844. /* Output newly nonzero coefficient */
  845. (*block)[pos] = (JCOEF) s;
  846. /* Remember its position in case we have to suspend */
  847. newnz_pos[num_newnz++] = pos;
  848. }
  849. }
  850. }
  851. if (EOBRUN > 0) {
  852. /* Scan any remaining coefficient positions after the end-of-band
  853. * (the last newly nonzero coefficient, if any). Append a correction
  854. * bit to each already-nonzero coefficient. A correction bit is 1
  855. * if the absolute value of the coefficient must be increased.
  856. */
  857. for (; k <= Se; k++) {
  858. thiscoef = *block + natural_order[k];
  859. if (*thiscoef != 0) {
  860. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  861. if (GET_BITS(1)) {
  862. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  863. if (*thiscoef >= 0)
  864. *thiscoef += p1;
  865. else
  866. *thiscoef += m1;
  867. }
  868. }
  869. }
  870. }
  871. /* Count one block completed in EOB run */
  872. EOBRUN--;
  873. }
  874. /* Completed MCU, so update state */
  875. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  876. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  877. }
  878. /* Account for restart interval (no-op if not using restarts) */
  879. entropy->restarts_to_go--;
  880. return TRUE;
  881. undoit:
  882. /* Re-zero any output coefficients that we made newly nonzero */
  883. while (num_newnz > 0)
  884. (*block)[newnz_pos[--num_newnz]] = 0;
  885. return FALSE;
  886. }
  887. /*
  888. * Decode one MCU's worth of Huffman-compressed coefficients,
  889. * partial blocks.
  890. */
  891. METHODDEF(boolean)
  892. decode_mcu_sub (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  893. {
  894. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  895. const int * natural_order;
  896. int Se, blkn;
  897. BITREAD_STATE_VARS;
  898. savable_state state;
  899. /* Process restart marker if needed; may have to suspend */
  900. if (cinfo->restart_interval) {
  901. if (entropy->restarts_to_go == 0)
  902. if (! process_restart(cinfo))
  903. return FALSE;
  904. }
  905. /* If we've run out of data, just leave the MCU set to zeroes.
  906. * This way, we return uniform gray for the remainder of the segment.
  907. */
  908. if (! entropy->insufficient_data) {
  909. natural_order = cinfo->natural_order;
  910. Se = cinfo->lim_Se;
  911. /* Load up working state */
  912. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  913. ASSIGN_STATE(state, entropy->saved);
  914. /* Outer loop handles each block in the MCU */
  915. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  916. JBLOCKROW block = MCU_data[blkn];
  917. d_derived_tbl * htbl;
  918. int s, k, r;
  919. int coef_limit, ci;
  920. /* Decode a single block's worth of coefficients */
  921. /* Section F.2.2.1: decode the DC coefficient difference */
  922. htbl = entropy->dc_cur_tbls[blkn];
  923. HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
  924. htbl = entropy->ac_cur_tbls[blkn];
  925. k = 1;
  926. coef_limit = entropy->coef_limit[blkn];
  927. if (coef_limit) {
  928. /* Convert DC difference to actual value, update last_dc_val */
  929. if (s) {
  930. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  931. r = GET_BITS(s);
  932. s = HUFF_EXTEND(r, s);
  933. }
  934. ci = cinfo->MCU_membership[blkn];
  935. s += state.last_dc_val[ci];
  936. state.last_dc_val[ci] = s;
  937. /* Output the DC coefficient */
  938. (*block)[0] = (JCOEF) s;
  939. /* Section F.2.2.2: decode the AC coefficients */
  940. /* Since zeroes are skipped, output area must be cleared beforehand */
  941. for (; k < coef_limit; k++) {
  942. HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
  943. r = s >> 4;
  944. s &= 15;
  945. if (s) {
  946. k += r;
  947. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  948. r = GET_BITS(s);
  949. s = HUFF_EXTEND(r, s);
  950. /* Output coefficient in natural (dezigzagged) order.
  951. * Note: the extra entries in natural_order[] will save us
  952. * if k > Se, which could happen if the data is corrupted.
  953. */
  954. (*block)[natural_order[k]] = (JCOEF) s;
  955. } else {
  956. if (r != 15)
  957. goto EndOfBlock;
  958. k += 15;
  959. }
  960. }
  961. } else {
  962. if (s) {
  963. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  964. DROP_BITS(s);
  965. }
  966. }
  967. /* Section F.2.2.2: decode the AC coefficients */
  968. /* In this path we just discard the values */
  969. for (; k <= Se; k++) {
  970. HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
  971. r = s >> 4;
  972. s &= 15;
  973. if (s) {
  974. k += r;
  975. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  976. DROP_BITS(s);
  977. } else {
  978. if (r != 15)
  979. break;
  980. k += 15;
  981. }
  982. }
  983. EndOfBlock: ;
  984. }
  985. /* Completed MCU, so update state */
  986. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  987. ASSIGN_STATE(entropy->saved, state);
  988. }
  989. /* Account for restart interval (no-op if not using restarts) */
  990. entropy->restarts_to_go--;
  991. return TRUE;
  992. }
  993. /*
  994. * Decode one MCU's worth of Huffman-compressed coefficients,
  995. * full-size blocks.
  996. */
  997. METHODDEF(boolean)
  998. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  999. {
  1000. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1001. int blkn;
  1002. BITREAD_STATE_VARS;
  1003. savable_state state;
  1004. /* Process restart marker if needed; may have to suspend */
  1005. if (cinfo->restart_interval) {
  1006. if (entropy->restarts_to_go == 0)
  1007. if (! process_restart(cinfo))
  1008. return FALSE;
  1009. }
  1010. /* If we've run out of data, just leave the MCU set to zeroes.
  1011. * This way, we return uniform gray for the remainder of the segment.
  1012. */
  1013. if (! entropy->insufficient_data) {
  1014. /* Load up working state */
  1015. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  1016. ASSIGN_STATE(state, entropy->saved);
  1017. /* Outer loop handles each block in the MCU */
  1018. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  1019. JBLOCKROW block = MCU_data[blkn];
  1020. d_derived_tbl * htbl;
  1021. int s, k, r;
  1022. int coef_limit, ci;
  1023. /* Decode a single block's worth of coefficients */
  1024. /* Section F.2.2.1: decode the DC coefficient difference */
  1025. htbl = entropy->dc_cur_tbls[blkn];
  1026. HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
  1027. htbl = entropy->ac_cur_tbls[blkn];
  1028. k = 1;
  1029. coef_limit = entropy->coef_limit[blkn];
  1030. if (coef_limit) {
  1031. /* Convert DC difference to actual value, update last_dc_val */
  1032. if (s) {
  1033. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1034. r = GET_BITS(s);
  1035. s = HUFF_EXTEND(r, s);
  1036. }
  1037. ci = cinfo->MCU_membership[blkn];
  1038. s += state.last_dc_val[ci];
  1039. state.last_dc_val[ci] = s;
  1040. /* Output the DC coefficient */
  1041. (*block)[0] = (JCOEF) s;
  1042. /* Section F.2.2.2: decode the AC coefficients */
  1043. /* Since zeroes are skipped, output area must be cleared beforehand */
  1044. for (; k < coef_limit; k++) {
  1045. HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
  1046. r = s >> 4;
  1047. s &= 15;
  1048. if (s) {
  1049. k += r;
  1050. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1051. r = GET_BITS(s);
  1052. s = HUFF_EXTEND(r, s);
  1053. /* Output coefficient in natural (dezigzagged) order.
  1054. * Note: the extra entries in jpeg_natural_order[] will save us
  1055. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  1056. */
  1057. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  1058. } else {
  1059. if (r != 15)
  1060. goto EndOfBlock;
  1061. k += 15;
  1062. }
  1063. }
  1064. } else {
  1065. if (s) {
  1066. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1067. DROP_BITS(s);
  1068. }
  1069. }
  1070. /* Section F.2.2.2: decode the AC coefficients */
  1071. /* In this path we just discard the values */
  1072. for (; k < DCTSIZE2; k++) {
  1073. HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
  1074. r = s >> 4;
  1075. s &= 15;
  1076. if (s) {
  1077. k += r;
  1078. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1079. DROP_BITS(s);
  1080. } else {
  1081. if (r != 15)
  1082. break;
  1083. k += 15;
  1084. }
  1085. }
  1086. EndOfBlock: ;
  1087. }
  1088. /* Completed MCU, so update state */
  1089. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  1090. ASSIGN_STATE(entropy->saved, state);
  1091. }
  1092. /* Account for restart interval (no-op if not using restarts) */
  1093. entropy->restarts_to_go--;
  1094. return TRUE;
  1095. }
  1096. /*
  1097. * Initialize for a Huffman-compressed scan.
  1098. */
  1099. METHODDEF(void)
  1100. start_pass_huff_decoder (j_decompress_ptr cinfo)
  1101. {
  1102. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1103. int ci, blkn, tbl, i;
  1104. jpeg_component_info * compptr;
  1105. if (cinfo->progressive_mode) {
  1106. /* Validate progressive scan parameters */
  1107. if (cinfo->Ss == 0) {
  1108. if (cinfo->Se != 0)
  1109. goto bad;
  1110. } else {
  1111. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  1112. if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se)
  1113. goto bad;
  1114. /* AC scans may have only one component */
  1115. if (cinfo->comps_in_scan != 1)
  1116. goto bad;
  1117. }
  1118. if (cinfo->Ah != 0) {
  1119. /* Successive approximation refinement scan: must have Al = Ah-1. */
  1120. if (cinfo->Ah-1 != cinfo->Al)
  1121. goto bad;
  1122. }
  1123. if (cinfo->Al > 13) { /* need not check for < 0 */
  1124. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  1125. * but the spec doesn't say so, and we try to be liberal about what we
  1126. * accept. Note: large Al values could result in out-of-range DC
  1127. * coefficients during early scans, leading to bizarre displays due to
  1128. * overflows in the IDCT math. But we won't crash.
  1129. */
  1130. bad:
  1131. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  1132. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  1133. }
  1134. /* Update progression status, and verify that scan order is legal.
  1135. * Note that inter-scan inconsistencies are treated as warnings
  1136. * not fatal errors ... not clear if this is right way to behave.
  1137. */
  1138. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1139. int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
  1140. int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  1141. if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  1142. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  1143. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  1144. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  1145. if (cinfo->Ah != expected)
  1146. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  1147. coef_bit_ptr[coefi] = cinfo->Al;
  1148. }
  1149. }
  1150. /* Select MCU decoding routine */
  1151. if (cinfo->Ah == 0) {
  1152. if (cinfo->Ss == 0)
  1153. entropy->pub.decode_mcu = decode_mcu_DC_first;
  1154. else
  1155. entropy->pub.decode_mcu = decode_mcu_AC_first;
  1156. } else {
  1157. if (cinfo->Ss == 0)
  1158. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  1159. else
  1160. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  1161. }
  1162. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1163. compptr = cinfo->cur_comp_info[ci];
  1164. /* Make sure requested tables are present, and compute derived tables.
  1165. * We may build same derived table more than once, but it's not expensive.
  1166. */
  1167. if (cinfo->Ss == 0) {
  1168. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  1169. tbl = compptr->dc_tbl_no;
  1170. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  1171. & entropy->derived_tbls[tbl]);
  1172. }
  1173. } else {
  1174. tbl = compptr->ac_tbl_no;
  1175. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  1176. & entropy->derived_tbls[tbl]);
  1177. /* remember the single active table */
  1178. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  1179. }
  1180. /* Initialize DC predictions to 0 */
  1181. entropy->saved.last_dc_val[ci] = 0;
  1182. }
  1183. /* Initialize private state variables */
  1184. entropy->saved.EOBRUN = 0;
  1185. } else {
  1186. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  1187. * This ought to be an error condition, but we make it a warning because
  1188. * there are some baseline files out there with all zeroes in these bytes.
  1189. */
  1190. if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||
  1191. ((cinfo->is_baseline || cinfo->Se < DCTSIZE2) &&
  1192. cinfo->Se != cinfo->lim_Se))
  1193. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  1194. /* Select MCU decoding routine */
  1195. /* We retain the hard-coded case for full-size blocks.
  1196. * This is not necessary, but it appears that this version is slightly
  1197. * more performant in the given implementation.
  1198. * With an improved implementation we would prefer a single optimized
  1199. * function.
  1200. */
  1201. if (cinfo->lim_Se != DCTSIZE2-1)
  1202. entropy->pub.decode_mcu = decode_mcu_sub;
  1203. else
  1204. entropy->pub.decode_mcu = decode_mcu;
  1205. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1206. compptr = cinfo->cur_comp_info[ci];
  1207. /* Compute derived values for Huffman tables */
  1208. /* We may do this more than once for a table, but it's not expensive */
  1209. tbl = compptr->dc_tbl_no;
  1210. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  1211. & entropy->dc_derived_tbls[tbl]);
  1212. if (cinfo->lim_Se) { /* AC needs no table when not present */
  1213. tbl = compptr->ac_tbl_no;
  1214. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  1215. & entropy->ac_derived_tbls[tbl]);
  1216. }
  1217. /* Initialize DC predictions to 0 */
  1218. entropy->saved.last_dc_val[ci] = 0;
  1219. }
  1220. /* Precalculate decoding info for each block in an MCU of this scan */
  1221. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  1222. ci = cinfo->MCU_membership[blkn];
  1223. compptr = cinfo->cur_comp_info[ci];
  1224. /* Precalculate which table to use for each block */
  1225. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  1226. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  1227. /* Decide whether we really care about the coefficient values */
  1228. if (compptr->component_needed) {
  1229. ci = compptr->DCT_v_scaled_size;
  1230. i = compptr->DCT_h_scaled_size;
  1231. switch (cinfo->lim_Se) {
  1232. case (1*1-1):
  1233. entropy->coef_limit[blkn] = 1;
  1234. break;
  1235. case (2*2-1):
  1236. if (ci <= 0 || ci > 2) ci = 2;
  1237. if (i <= 0 || i > 2) i = 2;
  1238. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order2[ci - 1][i - 1];
  1239. break;
  1240. case (3*3-1):
  1241. if (ci <= 0 || ci > 3) ci = 3;
  1242. if (i <= 0 || i > 3) i = 3;
  1243. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order3[ci - 1][i - 1];
  1244. break;
  1245. case (4*4-1):
  1246. if (ci <= 0 || ci > 4) ci = 4;
  1247. if (i <= 0 || i > 4) i = 4;
  1248. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order4[ci - 1][i - 1];
  1249. break;
  1250. case (5*5-1):
  1251. if (ci <= 0 || ci > 5) ci = 5;
  1252. if (i <= 0 || i > 5) i = 5;
  1253. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order5[ci - 1][i - 1];
  1254. break;
  1255. case (6*6-1):
  1256. if (ci <= 0 || ci > 6) ci = 6;
  1257. if (i <= 0 || i > 6) i = 6;
  1258. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order6[ci - 1][i - 1];
  1259. break;
  1260. case (7*7-1):
  1261. if (ci <= 0 || ci > 7) ci = 7;
  1262. if (i <= 0 || i > 7) i = 7;
  1263. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order7[ci - 1][i - 1];
  1264. break;
  1265. default:
  1266. if (ci <= 0 || ci > 8) ci = 8;
  1267. if (i <= 0 || i > 8) i = 8;
  1268. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];
  1269. break;
  1270. }
  1271. } else {
  1272. entropy->coef_limit[blkn] = 0;
  1273. }
  1274. }
  1275. }
  1276. /* Initialize bitread state variables */
  1277. entropy->bitstate.bits_left = 0;
  1278. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  1279. entropy->insufficient_data = FALSE;
  1280. /* Initialize restart counter */
  1281. entropy->restarts_to_go = cinfo->restart_interval;
  1282. }
  1283. /*
  1284. * Module initialization routine for Huffman entropy decoding.
  1285. */
  1286. GLOBAL(void)
  1287. jinit_huff_decoder (j_decompress_ptr cinfo)
  1288. {
  1289. huff_entropy_ptr entropy;
  1290. int i;
  1291. entropy = (huff_entropy_ptr)
  1292. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1293. SIZEOF(huff_entropy_decoder));
  1294. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  1295. entropy->pub.start_pass = start_pass_huff_decoder;
  1296. if (cinfo->progressive_mode) {
  1297. /* Create progression status table */
  1298. int *coef_bit_ptr, ci;
  1299. cinfo->coef_bits = (int (*)[DCTSIZE2])
  1300. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1301. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  1302. coef_bit_ptr = & cinfo->coef_bits[0][0];
  1303. for (ci = 0; ci < cinfo->num_components; ci++)
  1304. for (i = 0; i < DCTSIZE2; i++)
  1305. *coef_bit_ptr++ = -1;
  1306. /* Mark derived tables unallocated */
  1307. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1308. entropy->derived_tbls[i] = NULL;
  1309. }
  1310. } else {
  1311. /* Mark tables unallocated */
  1312. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1313. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  1314. }
  1315. }
  1316. }