jdhuff.c 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309
  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. register bit_buf_type get_buffer; \
  87. register 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. { register 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. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  200. /* Following two fields used only in progressive mode */
  201. /* Pointers to derived tables (these workspaces have image lifespan) */
  202. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  203. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  204. /* Following fields used only in sequential mode */
  205. /* Pointers to derived tables (these workspaces have image lifespan) */
  206. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  207. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  208. /* Precalculated info set up by start_pass for use in decode_mcu: */
  209. /* Pointers to derived tables to be used for each block within an MCU */
  210. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  211. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  212. /* Whether we care about the DC and AC coefficient values for each block */
  213. int coef_limit[D_MAX_BLOCKS_IN_MCU];
  214. } huff_entropy_decoder;
  215. typedef huff_entropy_decoder * huff_entropy_ptr;
  216. static const int jpeg_zigzag_order[8][8] = {
  217. { 0, 1, 5, 6, 14, 15, 27, 28 },
  218. { 2, 4, 7, 13, 16, 26, 29, 42 },
  219. { 3, 8, 12, 17, 25, 30, 41, 43 },
  220. { 9, 11, 18, 24, 31, 40, 44, 53 },
  221. { 10, 19, 23, 32, 39, 45, 52, 54 },
  222. { 20, 22, 33, 38, 46, 51, 55, 60 },
  223. { 21, 34, 37, 47, 50, 56, 59, 61 },
  224. { 35, 36, 48, 49, 57, 58, 62, 63 }
  225. };
  226. /*
  227. * Compute the derived values for a Huffman table.
  228. * This routine also performs some validation checks on the table.
  229. */
  230. LOCAL(void)
  231. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  232. d_derived_tbl ** pdtbl)
  233. {
  234. JHUFF_TBL *htbl;
  235. d_derived_tbl *dtbl;
  236. int p, i, l, si, numsymbols;
  237. int lookbits, ctr;
  238. char huffsize[257];
  239. unsigned int huffcode[257];
  240. unsigned int code;
  241. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  242. * paralleling the order of the symbols themselves in htbl->huffval[].
  243. */
  244. /* Find the input Huffman table */
  245. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  246. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  247. htbl =
  248. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  249. if (htbl == NULL)
  250. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  251. /* Allocate a workspace if we haven't already done so. */
  252. if (*pdtbl == NULL)
  253. *pdtbl = (d_derived_tbl *)
  254. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  255. SIZEOF(d_derived_tbl));
  256. dtbl = *pdtbl;
  257. dtbl->pub = htbl; /* fill in back link */
  258. /* Figure C.1: make table of Huffman code length for each symbol */
  259. p = 0;
  260. for (l = 1; l <= 16; l++) {
  261. i = (int) htbl->bits[l];
  262. if (i < 0 || p + i > 256) /* protect against table overrun */
  263. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  264. while (i--)
  265. huffsize[p++] = (char) l;
  266. }
  267. huffsize[p] = 0;
  268. numsymbols = p;
  269. /* Figure C.2: generate the codes themselves */
  270. /* We also validate that the counts represent a legal Huffman code tree. */
  271. code = 0;
  272. si = huffsize[0];
  273. p = 0;
  274. while (huffsize[p]) {
  275. while (((int) huffsize[p]) == si) {
  276. huffcode[p++] = code;
  277. code++;
  278. }
  279. /* code is now 1 more than the last code used for codelength si; but
  280. * it must still fit in si bits, since no code is allowed to be all ones.
  281. */
  282. if (((INT32) code) >= (((INT32) 1) << si))
  283. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  284. code <<= 1;
  285. si++;
  286. }
  287. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  288. p = 0;
  289. for (l = 1; l <= 16; l++) {
  290. if (htbl->bits[l]) {
  291. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  292. * minus the minimum code of length l
  293. */
  294. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  295. p += htbl->bits[l];
  296. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  297. } else {
  298. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  299. }
  300. }
  301. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  302. /* Compute lookahead tables to speed up decoding.
  303. * First we set all the table entries to 0, indicating "too long";
  304. * then we iterate through the Huffman codes that are short enough and
  305. * fill in all the entries that correspond to bit sequences starting
  306. * with that code.
  307. */
  308. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  309. p = 0;
  310. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  311. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  312. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  313. /* Generate left-justified code followed by all possible bit sequences */
  314. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  315. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  316. dtbl->look_nbits[lookbits] = l;
  317. dtbl->look_sym[lookbits] = htbl->huffval[p];
  318. lookbits++;
  319. }
  320. }
  321. }
  322. /* Validate symbols as being reasonable.
  323. * For AC tables, we make no check, but accept all byte values 0..255.
  324. * For DC tables, we require the symbols to be in range 0..15.
  325. * (Tighter bounds could be applied depending on the data depth and mode,
  326. * but this is sufficient to ensure safe decoding.)
  327. */
  328. if (isDC) {
  329. for (i = 0; i < numsymbols; i++) {
  330. int sym = htbl->huffval[i];
  331. if (sym < 0 || sym > 15)
  332. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  333. }
  334. }
  335. }
  336. /*
  337. * Out-of-line code for bit fetching.
  338. * Note: current values of get_buffer and bits_left are passed as parameters,
  339. * but are returned in the corresponding fields of the state struct.
  340. *
  341. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  342. * of get_buffer to be used. (On machines with wider words, an even larger
  343. * buffer could be used.) However, on some machines 32-bit shifts are
  344. * quite slow and take time proportional to the number of places shifted.
  345. * (This is true with most PC compilers, for instance.) In this case it may
  346. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  347. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  348. */
  349. #ifdef SLOW_SHIFT_32
  350. #define MIN_GET_BITS 15 /* minimum allowable value */
  351. #else
  352. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  353. #endif
  354. LOCAL(boolean)
  355. jpeg_fill_bit_buffer (bitread_working_state * state,
  356. register bit_buf_type get_buffer, register int bits_left,
  357. int nbits)
  358. /* Load up the bit buffer to a depth of at least nbits */
  359. {
  360. /* Copy heavily used state fields into locals (hopefully registers) */
  361. register const JOCTET * next_input_byte = state->next_input_byte;
  362. register size_t bytes_in_buffer = state->bytes_in_buffer;
  363. j_decompress_ptr cinfo = state->cinfo;
  364. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  365. /* (It is assumed that no request will be for more than that many bits.) */
  366. /* We fail to do so only if we hit a marker or are forced to suspend. */
  367. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  368. while (bits_left < MIN_GET_BITS) {
  369. register int c;
  370. /* Attempt to read a byte */
  371. if (bytes_in_buffer == 0) {
  372. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  373. return FALSE;
  374. next_input_byte = cinfo->src->next_input_byte;
  375. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  376. }
  377. bytes_in_buffer--;
  378. c = GETJOCTET(*next_input_byte++);
  379. /* If it's 0xFF, check and discard stuffed zero byte */
  380. if (c == 0xFF) {
  381. /* Loop here to discard any padding FF's on terminating marker,
  382. * so that we can save a valid unread_marker value. NOTE: we will
  383. * accept multiple FF's followed by a 0 as meaning a single FF data
  384. * byte. This data pattern is not valid according to the standard.
  385. */
  386. do {
  387. if (bytes_in_buffer == 0) {
  388. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  389. return FALSE;
  390. next_input_byte = cinfo->src->next_input_byte;
  391. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  392. }
  393. bytes_in_buffer--;
  394. c = GETJOCTET(*next_input_byte++);
  395. } while (c == 0xFF);
  396. if (c == 0) {
  397. /* Found FF/00, which represents an FF data byte */
  398. c = 0xFF;
  399. } else {
  400. /* Oops, it's actually a marker indicating end of compressed data.
  401. * Save the marker code for later use.
  402. * Fine point: it might appear that we should save the marker into
  403. * bitread working state, not straight into permanent state. But
  404. * once we have hit a marker, we cannot need to suspend within the
  405. * current MCU, because we will read no more bytes from the data
  406. * source. So it is OK to update permanent state right away.
  407. */
  408. cinfo->unread_marker = c;
  409. /* See if we need to insert some fake zero bits. */
  410. goto no_more_bytes;
  411. }
  412. }
  413. /* OK, load c into get_buffer */
  414. get_buffer = (get_buffer << 8) | c;
  415. bits_left += 8;
  416. } /* end while */
  417. } else {
  418. no_more_bytes:
  419. /* We get here if we've read the marker that terminates the compressed
  420. * data segment. There should be enough bits in the buffer register
  421. * to satisfy the request; if so, no problem.
  422. */
  423. if (nbits > bits_left) {
  424. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  425. * the data stream, so that we can produce some kind of image.
  426. * We use a nonvolatile flag to ensure that only one warning message
  427. * appears per data segment.
  428. */
  429. if (! cinfo->entropy->insufficient_data) {
  430. WARNMS(cinfo, JWRN_HIT_MARKER);
  431. cinfo->entropy->insufficient_data = TRUE;
  432. }
  433. /* Fill the buffer with zero bits */
  434. get_buffer <<= MIN_GET_BITS - bits_left;
  435. bits_left = MIN_GET_BITS;
  436. }
  437. }
  438. /* Unload the local registers */
  439. state->next_input_byte = next_input_byte;
  440. state->bytes_in_buffer = bytes_in_buffer;
  441. state->get_buffer = get_buffer;
  442. state->bits_left = bits_left;
  443. return TRUE;
  444. }
  445. /*
  446. * Figure F.12: extend sign bit.
  447. * On some machines, a shift and sub will be faster than a table lookup.
  448. */
  449. #ifdef AVOID_TABLES
  450. #define BIT_MASK(nbits) ((1<<(nbits))-1)
  451. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))
  452. #else
  453. #define BIT_MASK(nbits) bmask[nbits]
  454. #define HUFF_EXTEND(x,s) ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))
  455. static const int bmask[16] = /* bmask[n] is mask for n rightmost bits */
  456. { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  457. 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
  458. #endif /* AVOID_TABLES */
  459. /*
  460. * Out-of-line code for Huffman code decoding.
  461. */
  462. LOCAL(int)
  463. jpeg_huff_decode (bitread_working_state * state,
  464. register bit_buf_type get_buffer, register int bits_left,
  465. d_derived_tbl * htbl, int min_bits)
  466. {
  467. register int l = min_bits;
  468. register INT32 code;
  469. /* HUFF_DECODE has determined that the code is at least min_bits */
  470. /* bits long, so fetch that many bits in one swoop. */
  471. CHECK_BIT_BUFFER(*state, l, return -1);
  472. code = GET_BITS(l);
  473. /* Collect the rest of the Huffman code one bit at a time. */
  474. /* This is per Figure F.16 in the JPEG spec. */
  475. while (code > htbl->maxcode[l]) {
  476. code <<= 1;
  477. CHECK_BIT_BUFFER(*state, 1, return -1);
  478. code |= GET_BITS(1);
  479. l++;
  480. }
  481. /* Unload the local registers */
  482. state->get_buffer = get_buffer;
  483. state->bits_left = bits_left;
  484. /* With garbage input we may reach the sentinel value l = 17. */
  485. if (l > 16) {
  486. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  487. return 0; /* fake a zero as the safest result */
  488. }
  489. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  490. }
  491. /*
  492. * Check for a restart marker & resynchronize decoder.
  493. * Returns FALSE if must suspend.
  494. */
  495. LOCAL(boolean)
  496. process_restart (j_decompress_ptr cinfo)
  497. {
  498. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  499. int ci;
  500. /* Throw away any unused bits remaining in bit buffer; */
  501. /* include any full bytes in next_marker's count of discarded bytes */
  502. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  503. entropy->bitstate.bits_left = 0;
  504. /* Advance past the RSTn marker */
  505. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  506. return FALSE;
  507. /* Re-initialize DC predictions to 0 */
  508. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  509. entropy->saved.last_dc_val[ci] = 0;
  510. /* Re-init EOB run count, too */
  511. entropy->saved.EOBRUN = 0;
  512. /* Reset restart counter */
  513. entropy->restarts_to_go = cinfo->restart_interval;
  514. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  515. * against a marker. In that case we will end up treating the next data
  516. * segment as empty, and we can avoid producing bogus output pixels by
  517. * leaving the flag set.
  518. */
  519. if (cinfo->unread_marker == 0)
  520. entropy->pub.insufficient_data = FALSE;
  521. return TRUE;
  522. }
  523. /*
  524. * Huffman MCU decoding.
  525. * Each of these routines decodes and returns one MCU's worth of
  526. * Huffman-compressed coefficients.
  527. * The coefficients are reordered from zigzag order into natural array order,
  528. * but are not dequantized.
  529. *
  530. * The i'th block of the MCU is stored into the block pointed to by
  531. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  532. * (Wholesale zeroing is usually a little faster than retail...)
  533. *
  534. * We return FALSE if data source requested suspension. In that case no
  535. * changes have been made to permanent state. (Exception: some output
  536. * coefficients may already have been assigned. This is harmless for
  537. * spectral selection, since we'll just re-assign them on the next call.
  538. * Successive approximation AC refinement has to be more careful, however.)
  539. */
  540. /*
  541. * MCU decoding for DC initial scan (either spectral selection,
  542. * or first pass of successive approximation).
  543. */
  544. METHODDEF(boolean)
  545. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  546. {
  547. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  548. int Al = cinfo->Al;
  549. register int s, r;
  550. int blkn, ci;
  551. JBLOCKROW block;
  552. BITREAD_STATE_VARS;
  553. savable_state state;
  554. d_derived_tbl * tbl;
  555. jpeg_component_info * compptr;
  556. /* Process restart marker if needed; may have to suspend */
  557. if (cinfo->restart_interval) {
  558. if (entropy->restarts_to_go == 0)
  559. if (! process_restart(cinfo))
  560. return FALSE;
  561. }
  562. /* If we've run out of data, just leave the MCU set to zeroes.
  563. * This way, we return uniform gray for the remainder of the segment.
  564. */
  565. if (! entropy->pub.insufficient_data) {
  566. /* Load up working state */
  567. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  568. ASSIGN_STATE(state, entropy->saved);
  569. /* Outer loop handles each block in the MCU */
  570. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  571. block = MCU_data[blkn];
  572. ci = cinfo->MCU_membership[blkn];
  573. compptr = cinfo->cur_comp_info[ci];
  574. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  575. /* Decode a single block's worth of coefficients */
  576. /* Section F.2.2.1: decode the DC coefficient difference */
  577. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  578. if (s) {
  579. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  580. r = GET_BITS(s);
  581. s = HUFF_EXTEND(r, s);
  582. }
  583. /* Convert DC difference to actual value, update last_dc_val */
  584. s += state.last_dc_val[ci];
  585. state.last_dc_val[ci] = s;
  586. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  587. (*block)[0] = (JCOEF) (s << Al);
  588. }
  589. /* Completed MCU, so update state */
  590. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  591. ASSIGN_STATE(entropy->saved, state);
  592. }
  593. /* Account for restart interval (no-op if not using restarts) */
  594. entropy->restarts_to_go--;
  595. return TRUE;
  596. }
  597. /*
  598. * MCU decoding for AC initial scan (either spectral selection,
  599. * or first pass of successive approximation).
  600. */
  601. METHODDEF(boolean)
  602. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  603. {
  604. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  605. int Se = cinfo->Se;
  606. int Al = cinfo->Al;
  607. register int s, k, r;
  608. unsigned int EOBRUN;
  609. JBLOCKROW block;
  610. BITREAD_STATE_VARS;
  611. d_derived_tbl * tbl;
  612. /* Process restart marker if needed; may have to suspend */
  613. if (cinfo->restart_interval) {
  614. if (entropy->restarts_to_go == 0)
  615. if (! process_restart(cinfo))
  616. return FALSE;
  617. }
  618. /* If we've run out of data, just leave the MCU set to zeroes.
  619. * This way, we return uniform gray for the remainder of the segment.
  620. */
  621. if (! entropy->pub.insufficient_data) {
  622. /* Load up working state.
  623. * We can avoid loading/saving bitread state if in an EOB run.
  624. */
  625. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  626. /* There is always only one block per MCU */
  627. if (EOBRUN > 0) /* if it's a band of zeroes... */
  628. EOBRUN--; /* ...process it now (we do nothing) */
  629. else {
  630. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  631. block = MCU_data[0];
  632. tbl = entropy->ac_derived_tbl;
  633. for (k = cinfo->Ss; k <= Se; k++) {
  634. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  635. r = s >> 4;
  636. s &= 15;
  637. if (s) {
  638. k += r;
  639. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  640. r = GET_BITS(s);
  641. s = HUFF_EXTEND(r, s);
  642. /* Scale and output coefficient in natural (dezigzagged) order */
  643. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  644. } else {
  645. if (r == 15) { /* ZRL */
  646. k += 15; /* skip 15 zeroes in band */
  647. } else { /* EOBr, run length is 2^r + appended bits */
  648. EOBRUN = 1 << r;
  649. if (r) { /* EOBr, r > 0 */
  650. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  651. r = GET_BITS(r);
  652. EOBRUN += r;
  653. }
  654. EOBRUN--; /* this band is processed at this moment */
  655. break; /* force end-of-band */
  656. }
  657. }
  658. }
  659. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  660. }
  661. /* Completed MCU, so update state */
  662. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  663. }
  664. /* Account for restart interval (no-op if not using restarts) */
  665. entropy->restarts_to_go--;
  666. return TRUE;
  667. }
  668. /*
  669. * MCU decoding for DC successive approximation refinement scan.
  670. * Note: we assume such scans can be multi-component, although the spec
  671. * is not very clear on the point.
  672. */
  673. METHODDEF(boolean)
  674. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  675. {
  676. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  677. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  678. int blkn;
  679. JBLOCKROW block;
  680. BITREAD_STATE_VARS;
  681. /* Process restart marker if needed; may have to suspend */
  682. if (cinfo->restart_interval) {
  683. if (entropy->restarts_to_go == 0)
  684. if (! process_restart(cinfo))
  685. return FALSE;
  686. }
  687. /* Not worth the cycles to check insufficient_data here,
  688. * since we will not change the data anyway if we read zeroes.
  689. */
  690. /* Load up working state */
  691. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  692. /* Outer loop handles each block in the MCU */
  693. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  694. block = MCU_data[blkn];
  695. /* Encoded data is simply the next bit of the two's-complement DC value */
  696. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  697. if (GET_BITS(1))
  698. (*block)[0] |= p1;
  699. /* Note: since we use |=, repeating the assignment later is safe */
  700. }
  701. /* Completed MCU, so update state */
  702. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  703. /* Account for restart interval (no-op if not using restarts) */
  704. entropy->restarts_to_go--;
  705. return TRUE;
  706. }
  707. /*
  708. * MCU decoding for AC successive approximation refinement scan.
  709. */
  710. METHODDEF(boolean)
  711. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  712. {
  713. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  714. int Se = cinfo->Se;
  715. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  716. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  717. register int s, k, r;
  718. unsigned int EOBRUN;
  719. JBLOCKROW block;
  720. JCOEFPTR thiscoef;
  721. BITREAD_STATE_VARS;
  722. d_derived_tbl * tbl;
  723. int num_newnz;
  724. int newnz_pos[DCTSIZE2];
  725. /* Process restart marker if needed; may have to suspend */
  726. if (cinfo->restart_interval) {
  727. if (entropy->restarts_to_go == 0)
  728. if (! process_restart(cinfo))
  729. return FALSE;
  730. }
  731. /* If we've run out of data, don't modify the MCU.
  732. */
  733. if (! entropy->pub.insufficient_data) {
  734. /* Load up working state */
  735. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  736. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  737. /* There is always only one block per MCU */
  738. block = MCU_data[0];
  739. tbl = entropy->ac_derived_tbl;
  740. /* If we are forced to suspend, we must undo the assignments to any newly
  741. * nonzero coefficients in the block, because otherwise we'd get confused
  742. * next time about which coefficients were already nonzero.
  743. * But we need not undo addition of bits to already-nonzero coefficients;
  744. * instead, we can test the current bit to see if we already did it.
  745. */
  746. num_newnz = 0;
  747. /* initialize coefficient loop counter to start of band */
  748. k = cinfo->Ss;
  749. if (EOBRUN == 0) {
  750. for (; k <= Se; k++) {
  751. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  752. r = s >> 4;
  753. s &= 15;
  754. if (s) {
  755. if (s != 1) /* size of new coef should always be 1 */
  756. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  757. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  758. if (GET_BITS(1))
  759. s = p1; /* newly nonzero coef is positive */
  760. else
  761. s = m1; /* newly nonzero coef is negative */
  762. } else {
  763. if (r != 15) {
  764. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  765. if (r) {
  766. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  767. r = GET_BITS(r);
  768. EOBRUN += r;
  769. }
  770. break; /* rest of block is handled by EOB logic */
  771. }
  772. /* note s = 0 for processing ZRL */
  773. }
  774. /* Advance over already-nonzero coefs and r still-zero coefs,
  775. * appending correction bits to the nonzeroes. A correction bit is 1
  776. * if the absolute value of the coefficient must be increased.
  777. */
  778. do {
  779. thiscoef = *block + jpeg_natural_order[k];
  780. if (*thiscoef != 0) {
  781. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  782. if (GET_BITS(1)) {
  783. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  784. if (*thiscoef >= 0)
  785. *thiscoef += p1;
  786. else
  787. *thiscoef += m1;
  788. }
  789. }
  790. } else {
  791. if (--r < 0)
  792. break; /* reached target zero coefficient */
  793. }
  794. k++;
  795. } while (k <= Se);
  796. if (s) {
  797. int pos = jpeg_natural_order[k];
  798. /* Output newly nonzero coefficient */
  799. (*block)[pos] = (JCOEF) s;
  800. /* Remember its position in case we have to suspend */
  801. newnz_pos[num_newnz++] = pos;
  802. }
  803. }
  804. }
  805. if (EOBRUN > 0) {
  806. /* Scan any remaining coefficient positions after the end-of-band
  807. * (the last newly nonzero coefficient, if any). Append a correction
  808. * bit to each already-nonzero coefficient. A correction bit is 1
  809. * if the absolute value of the coefficient must be increased.
  810. */
  811. for (; k <= Se; k++) {
  812. thiscoef = *block + jpeg_natural_order[k];
  813. if (*thiscoef != 0) {
  814. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  815. if (GET_BITS(1)) {
  816. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  817. if (*thiscoef >= 0)
  818. *thiscoef += p1;
  819. else
  820. *thiscoef += m1;
  821. }
  822. }
  823. }
  824. }
  825. /* Count one block completed in EOB run */
  826. EOBRUN--;
  827. }
  828. /* Completed MCU, so update state */
  829. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  830. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  831. }
  832. /* Account for restart interval (no-op if not using restarts) */
  833. entropy->restarts_to_go--;
  834. return TRUE;
  835. undoit:
  836. /* Re-zero any output coefficients that we made newly nonzero */
  837. while (num_newnz > 0)
  838. (*block)[newnz_pos[--num_newnz]] = 0;
  839. return FALSE;
  840. }
  841. /*
  842. * Decode one MCU's worth of Huffman-compressed coefficients.
  843. */
  844. METHODDEF(boolean)
  845. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  846. {
  847. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  848. int blkn;
  849. BITREAD_STATE_VARS;
  850. savable_state state;
  851. /* Process restart marker if needed; may have to suspend */
  852. if (cinfo->restart_interval) {
  853. if (entropy->restarts_to_go == 0)
  854. if (! process_restart(cinfo))
  855. return FALSE;
  856. }
  857. /* If we've run out of data, just leave the MCU set to zeroes.
  858. * This way, we return uniform gray for the remainder of the segment.
  859. */
  860. if (! entropy->pub.insufficient_data) {
  861. /* Load up working state */
  862. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  863. ASSIGN_STATE(state, entropy->saved);
  864. /* Outer loop handles each block in the MCU */
  865. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  866. JBLOCKROW block = MCU_data[blkn];
  867. d_derived_tbl * htbl;
  868. register int s, k, r;
  869. int coef_limit, ci;
  870. /* Decode a single block's worth of coefficients */
  871. /* Section F.2.2.1: decode the DC coefficient difference */
  872. htbl = entropy->dc_cur_tbls[blkn];
  873. HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
  874. htbl = entropy->ac_cur_tbls[blkn];
  875. k = 1;
  876. coef_limit = entropy->coef_limit[blkn];
  877. if (coef_limit) {
  878. /* Convert DC difference to actual value, update last_dc_val */
  879. if (s) {
  880. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  881. r = GET_BITS(s);
  882. s = HUFF_EXTEND(r, s);
  883. }
  884. ci = cinfo->MCU_membership[blkn];
  885. s += state.last_dc_val[ci];
  886. state.last_dc_val[ci] = s;
  887. /* Output the DC coefficient */
  888. (*block)[0] = (JCOEF) s;
  889. /* Section F.2.2.2: decode the AC coefficients */
  890. /* Since zeroes are skipped, output area must be cleared beforehand */
  891. for (; k < coef_limit; k++) {
  892. HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
  893. r = s >> 4;
  894. s &= 15;
  895. if (s) {
  896. k += r;
  897. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  898. r = GET_BITS(s);
  899. s = HUFF_EXTEND(r, s);
  900. /* Output coefficient in natural (dezigzagged) order.
  901. * Note: the extra entries in jpeg_natural_order[] will save us
  902. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  903. */
  904. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  905. } else {
  906. if (r != 15)
  907. goto EndOfBlock;
  908. k += 15;
  909. }
  910. }
  911. } else {
  912. if (s) {
  913. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  914. DROP_BITS(s);
  915. }
  916. }
  917. /* Section F.2.2.2: decode the AC coefficients */
  918. /* In this path we just discard the values */
  919. for (; k < DCTSIZE2; k++) {
  920. HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
  921. r = s >> 4;
  922. s &= 15;
  923. if (s) {
  924. k += r;
  925. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  926. DROP_BITS(s);
  927. } else {
  928. if (r != 15)
  929. break;
  930. k += 15;
  931. }
  932. }
  933. EndOfBlock: ;
  934. }
  935. /* Completed MCU, so update state */
  936. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  937. ASSIGN_STATE(entropy->saved, state);
  938. }
  939. /* Account for restart interval (no-op if not using restarts) */
  940. entropy->restarts_to_go--;
  941. return TRUE;
  942. }
  943. /*
  944. * Initialize for a Huffman-compressed scan.
  945. */
  946. METHODDEF(void)
  947. start_pass_huff_decoder (j_decompress_ptr cinfo)
  948. {
  949. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  950. int ci, blkn, dctbl, actbl, i;
  951. jpeg_component_info * compptr;
  952. if (cinfo->progressive_mode) {
  953. /* Validate progressive scan parameters */
  954. if (cinfo->Ss == 0) {
  955. if (cinfo->Se != 0)
  956. goto bad;
  957. } else {
  958. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  959. if (cinfo->Se < cinfo->Ss || cinfo->Se >= DCTSIZE2)
  960. goto bad;
  961. /* AC scans may have only one component */
  962. if (cinfo->comps_in_scan != 1)
  963. goto bad;
  964. }
  965. if (cinfo->Ah != 0) {
  966. /* Successive approximation refinement scan: must have Al = Ah-1. */
  967. if (cinfo->Ah-1 != cinfo->Al)
  968. goto bad;
  969. }
  970. if (cinfo->Al > 13) { /* need not check for < 0 */
  971. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  972. * but the spec doesn't say so, and we try to be liberal about what we
  973. * accept. Note: large Al values could result in out-of-range DC
  974. * coefficients during early scans, leading to bizarre displays due to
  975. * overflows in the IDCT math. But we won't crash.
  976. */
  977. bad:
  978. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  979. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  980. }
  981. /* Update progression status, and verify that scan order is legal.
  982. * Note that inter-scan inconsistencies are treated as warnings
  983. * not fatal errors ... not clear if this is right way to behave.
  984. */
  985. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  986. int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
  987. int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  988. if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  989. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  990. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  991. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  992. if (cinfo->Ah != expected)
  993. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  994. coef_bit_ptr[coefi] = cinfo->Al;
  995. }
  996. }
  997. /* Select MCU decoding routine */
  998. if (cinfo->Ah == 0) {
  999. if (cinfo->Ss == 0)
  1000. entropy->pub.decode_mcu = decode_mcu_DC_first;
  1001. else
  1002. entropy->pub.decode_mcu = decode_mcu_AC_first;
  1003. } else {
  1004. if (cinfo->Ss == 0)
  1005. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  1006. else
  1007. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  1008. }
  1009. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1010. compptr = cinfo->cur_comp_info[ci];
  1011. /* Make sure requested tables are present, and compute derived tables.
  1012. * We may build same derived table more than once, but it's not expensive.
  1013. */
  1014. if (cinfo->Ss == 0) {
  1015. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  1016. i = compptr->dc_tbl_no;
  1017. jpeg_make_d_derived_tbl(cinfo, TRUE, i,
  1018. & entropy->derived_tbls[i]);
  1019. }
  1020. } else {
  1021. i = compptr->ac_tbl_no;
  1022. jpeg_make_d_derived_tbl(cinfo, FALSE, i,
  1023. & entropy->derived_tbls[i]);
  1024. /* remember the single active table */
  1025. entropy->ac_derived_tbl = entropy->derived_tbls[i];
  1026. }
  1027. /* Initialize DC predictions to 0 */
  1028. entropy->saved.last_dc_val[ci] = 0;
  1029. }
  1030. /* Initialize private state variables */
  1031. entropy->saved.EOBRUN = 0;
  1032. } else {
  1033. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  1034. * This ought to be an error condition, but we make it a warning because
  1035. * there are some baseline files out there with all zeroes in these bytes.
  1036. */
  1037. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  1038. cinfo->Ah != 0 || cinfo->Al != 0)
  1039. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  1040. /* Select MCU decoding routine */
  1041. entropy->pub.decode_mcu = decode_mcu;
  1042. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1043. compptr = cinfo->cur_comp_info[ci];
  1044. dctbl = compptr->dc_tbl_no;
  1045. actbl = compptr->ac_tbl_no;
  1046. /* Compute derived values for Huffman tables */
  1047. /* We may do this more than once for a table, but it's not expensive */
  1048. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  1049. & entropy->dc_derived_tbls[dctbl]);
  1050. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  1051. & entropy->ac_derived_tbls[actbl]);
  1052. /* Initialize DC predictions to 0 */
  1053. entropy->saved.last_dc_val[ci] = 0;
  1054. }
  1055. /* Precalculate decoding info for each block in an MCU of this scan */
  1056. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  1057. ci = cinfo->MCU_membership[blkn];
  1058. compptr = cinfo->cur_comp_info[ci];
  1059. /* Precalculate which table to use for each block */
  1060. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  1061. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  1062. /* Decide whether we really care about the coefficient values */
  1063. if (compptr->component_needed) {
  1064. ci = compptr->DCT_v_scaled_size;
  1065. if (ci <= 0 || ci > 8) ci = 8;
  1066. i = compptr->DCT_h_scaled_size;
  1067. if (i <= 0 || i > 8) i = 8;
  1068. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];
  1069. } else {
  1070. entropy->coef_limit[blkn] = 0;
  1071. }
  1072. }
  1073. }
  1074. /* Initialize bitread state variables */
  1075. entropy->bitstate.bits_left = 0;
  1076. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  1077. entropy->pub.insufficient_data = FALSE;
  1078. /* Initialize restart counter */
  1079. entropy->restarts_to_go = cinfo->restart_interval;
  1080. }
  1081. /*
  1082. * Module initialization routine for Huffman entropy decoding.
  1083. */
  1084. GLOBAL(void)
  1085. jinit_huff_decoder (j_decompress_ptr cinfo)
  1086. {
  1087. huff_entropy_ptr entropy;
  1088. int i;
  1089. entropy = (huff_entropy_ptr)
  1090. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1091. SIZEOF(huff_entropy_decoder));
  1092. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  1093. entropy->pub.start_pass = start_pass_huff_decoder;
  1094. if (cinfo->progressive_mode) {
  1095. /* Create progression status table */
  1096. int *coef_bit_ptr, ci;
  1097. cinfo->coef_bits = (int (*)[DCTSIZE2])
  1098. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1099. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  1100. coef_bit_ptr = & cinfo->coef_bits[0][0];
  1101. for (ci = 0; ci < cinfo->num_components; ci++)
  1102. for (i = 0; i < DCTSIZE2; i++)
  1103. *coef_bit_ptr++ = -1;
  1104. /* Mark derived tables unallocated */
  1105. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1106. entropy->derived_tbls[i] = NULL;
  1107. }
  1108. } else {
  1109. /* Mark tables unallocated */
  1110. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1111. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  1112. }
  1113. }
  1114. }