jdhuff.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555
  1. /*
  2. * jdhuff.c
  3. *
  4. * Copyright (C) 1991-1997, Thomas G. Lane.
  5. * Modified 2006-2013 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. 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. register bit_buf_type get_buffer, register 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. register const JOCTET * next_input_byte = state->next_input_byte;
  402. register 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. register 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. register bit_buf_type get_buffer, register int bits_left,
  505. d_derived_tbl * htbl, int min_bits)
  506. {
  507. register int l = min_bits;
  508. register 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. * Finish up at the end of a Huffman-compressed scan.
  533. */
  534. METHODDEF(void)
  535. finish_pass_huff (j_decompress_ptr cinfo)
  536. {
  537. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  538. /* Throw away any unused bits remaining in bit buffer; */
  539. /* include any full bytes in next_marker's count of discarded bytes */
  540. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  541. entropy->bitstate.bits_left = 0;
  542. }
  543. /*
  544. * Check for a restart marker & resynchronize decoder.
  545. * Returns FALSE if must suspend.
  546. */
  547. LOCAL(boolean)
  548. process_restart (j_decompress_ptr cinfo)
  549. {
  550. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  551. int ci;
  552. finish_pass_huff(cinfo);
  553. /* Advance past the RSTn marker */
  554. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  555. return FALSE;
  556. /* Re-initialize DC predictions to 0 */
  557. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  558. entropy->saved.last_dc_val[ci] = 0;
  559. /* Re-init EOB run count, too */
  560. entropy->saved.EOBRUN = 0;
  561. /* Reset restart counter */
  562. entropy->restarts_to_go = cinfo->restart_interval;
  563. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  564. * against a marker. In that case we will end up treating the next data
  565. * segment as empty, and we can avoid producing bogus output pixels by
  566. * leaving the flag set.
  567. */
  568. if (cinfo->unread_marker == 0)
  569. entropy->insufficient_data = FALSE;
  570. return TRUE;
  571. }
  572. /*
  573. * Huffman MCU decoding.
  574. * Each of these routines decodes and returns one MCU's worth of
  575. * Huffman-compressed coefficients.
  576. * The coefficients are reordered from zigzag order into natural array order,
  577. * but are not dequantized.
  578. *
  579. * The i'th block of the MCU is stored into the block pointed to by
  580. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  581. * (Wholesale zeroing is usually a little faster than retail...)
  582. *
  583. * We return FALSE if data source requested suspension. In that case no
  584. * changes have been made to permanent state. (Exception: some output
  585. * coefficients may already have been assigned. This is harmless for
  586. * spectral selection, since we'll just re-assign them on the next call.
  587. * Successive approximation AC refinement has to be more careful, however.)
  588. */
  589. /*
  590. * MCU decoding for DC initial scan (either spectral selection,
  591. * or first pass of successive approximation).
  592. */
  593. METHODDEF(boolean)
  594. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  595. {
  596. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  597. int Al = cinfo->Al;
  598. register int s, r;
  599. int blkn, ci;
  600. JBLOCKROW block;
  601. BITREAD_STATE_VARS;
  602. savable_state state;
  603. d_derived_tbl * tbl;
  604. jpeg_component_info * compptr;
  605. /* Process restart marker if needed; may have to suspend */
  606. if (cinfo->restart_interval) {
  607. if (entropy->restarts_to_go == 0)
  608. if (! process_restart(cinfo))
  609. return FALSE;
  610. }
  611. /* If we've run out of data, just leave the MCU set to zeroes.
  612. * This way, we return uniform gray for the remainder of the segment.
  613. */
  614. if (! entropy->insufficient_data) {
  615. /* Load up working state */
  616. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  617. ASSIGN_STATE(state, entropy->saved);
  618. /* Outer loop handles each block in the MCU */
  619. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  620. block = MCU_data[blkn];
  621. ci = cinfo->MCU_membership[blkn];
  622. compptr = cinfo->cur_comp_info[ci];
  623. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  624. /* Decode a single block's worth of coefficients */
  625. /* Section F.2.2.1: decode the DC coefficient difference */
  626. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  627. if (s) {
  628. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  629. r = GET_BITS(s);
  630. s = HUFF_EXTEND(r, s);
  631. }
  632. /* Convert DC difference to actual value, update last_dc_val */
  633. s += state.last_dc_val[ci];
  634. state.last_dc_val[ci] = s;
  635. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  636. (*block)[0] = (JCOEF) (s << Al);
  637. }
  638. /* Completed MCU, so update state */
  639. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  640. ASSIGN_STATE(entropy->saved, state);
  641. }
  642. /* Account for restart interval (no-op if not using restarts) */
  643. entropy->restarts_to_go--;
  644. return TRUE;
  645. }
  646. /*
  647. * MCU decoding for AC initial scan (either spectral selection,
  648. * or first pass of successive approximation).
  649. */
  650. METHODDEF(boolean)
  651. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  652. {
  653. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  654. register int s, k, r;
  655. unsigned int EOBRUN;
  656. int Se, Al;
  657. const int * natural_order;
  658. JBLOCKROW block;
  659. BITREAD_STATE_VARS;
  660. d_derived_tbl * tbl;
  661. /* Process restart marker if needed; may have to suspend */
  662. if (cinfo->restart_interval) {
  663. if (entropy->restarts_to_go == 0)
  664. if (! process_restart(cinfo))
  665. return FALSE;
  666. }
  667. /* If we've run out of data, just leave the MCU set to zeroes.
  668. * This way, we return uniform gray for the remainder of the segment.
  669. */
  670. if (! entropy->insufficient_data) {
  671. Se = cinfo->Se;
  672. Al = cinfo->Al;
  673. natural_order = cinfo->natural_order;
  674. /* Load up working state.
  675. * We can avoid loading/saving bitread state if in an EOB run.
  676. */
  677. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  678. /* There is always only one block per MCU */
  679. if (EOBRUN) /* if it's a band of zeroes... */
  680. EOBRUN--; /* ...process it now (we do nothing) */
  681. else {
  682. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  683. block = MCU_data[0];
  684. tbl = entropy->ac_derived_tbl;
  685. for (k = cinfo->Ss; k <= Se; k++) {
  686. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  687. r = s >> 4;
  688. s &= 15;
  689. if (s) {
  690. k += r;
  691. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  692. r = GET_BITS(s);
  693. s = HUFF_EXTEND(r, s);
  694. /* Scale and output coefficient in natural (dezigzagged) order */
  695. (*block)[natural_order[k]] = (JCOEF) (s << Al);
  696. } else {
  697. if (r != 15) { /* EOBr, run length is 2^r + appended bits */
  698. if (r) { /* EOBr, r > 0 */
  699. EOBRUN = 1 << r;
  700. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  701. r = GET_BITS(r);
  702. EOBRUN += r;
  703. EOBRUN--; /* this band is processed at this moment */
  704. }
  705. break; /* force end-of-band */
  706. }
  707. k += 15; /* ZRL: skip 15 zeroes in band */
  708. }
  709. }
  710. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  711. }
  712. /* Completed MCU, so update state */
  713. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  714. }
  715. /* Account for restart interval (no-op if not using restarts) */
  716. entropy->restarts_to_go--;
  717. return TRUE;
  718. }
  719. /*
  720. * MCU decoding for DC successive approximation refinement scan.
  721. * Note: we assume such scans can be multi-component,
  722. * although the spec is not very clear on the point.
  723. */
  724. METHODDEF(boolean)
  725. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  726. {
  727. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  728. int p1, blkn;
  729. BITREAD_STATE_VARS;
  730. /* Process restart marker if needed; may have to suspend */
  731. if (cinfo->restart_interval) {
  732. if (entropy->restarts_to_go == 0)
  733. if (! process_restart(cinfo))
  734. return FALSE;
  735. }
  736. /* Not worth the cycles to check insufficient_data here,
  737. * since we will not change the data anyway if we read zeroes.
  738. */
  739. /* Load up working state */
  740. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  741. p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  742. /* Outer loop handles each block in the MCU */
  743. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  744. /* Encoded data is simply the next bit of the two's-complement DC value */
  745. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  746. if (GET_BITS(1))
  747. MCU_data[blkn][0][0] |= p1;
  748. /* Note: since we use |=, repeating the assignment later is safe */
  749. }
  750. /* Completed MCU, so update state */
  751. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  752. /* Account for restart interval (no-op if not using restarts) */
  753. entropy->restarts_to_go--;
  754. return TRUE;
  755. }
  756. /*
  757. * MCU decoding for AC successive approximation refinement scan.
  758. */
  759. METHODDEF(boolean)
  760. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  761. {
  762. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  763. register int s, k, r;
  764. unsigned int EOBRUN;
  765. int Se, p1, m1;
  766. const int * natural_order;
  767. JBLOCKROW block;
  768. JCOEFPTR thiscoef;
  769. BITREAD_STATE_VARS;
  770. d_derived_tbl * tbl;
  771. int num_newnz;
  772. int newnz_pos[DCTSIZE2];
  773. /* Process restart marker if needed; may have to suspend */
  774. if (cinfo->restart_interval) {
  775. if (entropy->restarts_to_go == 0)
  776. if (! process_restart(cinfo))
  777. return FALSE;
  778. }
  779. /* If we've run out of data, don't modify the MCU.
  780. */
  781. if (! entropy->insufficient_data) {
  782. Se = cinfo->Se;
  783. p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  784. m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  785. natural_order = cinfo->natural_order;
  786. /* Load up working state */
  787. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  788. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  789. /* There is always only one block per MCU */
  790. block = MCU_data[0];
  791. tbl = entropy->ac_derived_tbl;
  792. /* If we are forced to suspend, we must undo the assignments to any newly
  793. * nonzero coefficients in the block, because otherwise we'd get confused
  794. * next time about which coefficients were already nonzero.
  795. * But we need not undo addition of bits to already-nonzero coefficients;
  796. * instead, we can test the current bit to see if we already did it.
  797. */
  798. num_newnz = 0;
  799. /* initialize coefficient loop counter to start of band */
  800. k = cinfo->Ss;
  801. if (EOBRUN == 0) {
  802. do {
  803. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  804. r = s >> 4;
  805. s &= 15;
  806. if (s) {
  807. if (s != 1) /* size of new coef should always be 1 */
  808. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  809. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  810. if (GET_BITS(1))
  811. s = p1; /* newly nonzero coef is positive */
  812. else
  813. s = m1; /* newly nonzero coef is negative */
  814. } else {
  815. if (r != 15) {
  816. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  817. if (r) {
  818. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  819. r = GET_BITS(r);
  820. EOBRUN += r;
  821. }
  822. break; /* rest of block is handled by EOB logic */
  823. }
  824. /* note s = 0 for processing ZRL */
  825. }
  826. /* Advance over already-nonzero coefs and r still-zero coefs,
  827. * appending correction bits to the nonzeroes. A correction bit is 1
  828. * if the absolute value of the coefficient must be increased.
  829. */
  830. do {
  831. thiscoef = *block + natural_order[k];
  832. if (*thiscoef) {
  833. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  834. if (GET_BITS(1)) {
  835. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  836. if (*thiscoef >= 0)
  837. *thiscoef += p1;
  838. else
  839. *thiscoef += m1;
  840. }
  841. }
  842. } else {
  843. if (--r < 0)
  844. break; /* reached target zero coefficient */
  845. }
  846. k++;
  847. } while (k <= Se);
  848. if (s) {
  849. int pos = natural_order[k];
  850. /* Output newly nonzero coefficient */
  851. (*block)[pos] = (JCOEF) s;
  852. /* Remember its position in case we have to suspend */
  853. newnz_pos[num_newnz++] = pos;
  854. }
  855. k++;
  856. } while (k <= Se);
  857. }
  858. if (EOBRUN) {
  859. /* Scan any remaining coefficient positions after the end-of-band
  860. * (the last newly nonzero coefficient, if any). Append a correction
  861. * bit to each already-nonzero coefficient. A correction bit is 1
  862. * if the absolute value of the coefficient must be increased.
  863. */
  864. do {
  865. thiscoef = *block + natural_order[k];
  866. if (*thiscoef) {
  867. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  868. if (GET_BITS(1)) {
  869. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  870. if (*thiscoef >= 0)
  871. *thiscoef += p1;
  872. else
  873. *thiscoef += m1;
  874. }
  875. }
  876. }
  877. k++;
  878. } while (k <= Se);
  879. /* Count one block completed in EOB run */
  880. EOBRUN--;
  881. }
  882. /* Completed MCU, so update state */
  883. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  884. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  885. }
  886. /* Account for restart interval (no-op if not using restarts) */
  887. entropy->restarts_to_go--;
  888. return TRUE;
  889. undoit:
  890. /* Re-zero any output coefficients that we made newly nonzero */
  891. while (num_newnz)
  892. (*block)[newnz_pos[--num_newnz]] = 0;
  893. return FALSE;
  894. }
  895. /*
  896. * Decode one MCU's worth of Huffman-compressed coefficients,
  897. * partial blocks.
  898. */
  899. METHODDEF(boolean)
  900. decode_mcu_sub (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  901. {
  902. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  903. const int * natural_order;
  904. int Se, blkn;
  905. BITREAD_STATE_VARS;
  906. savable_state state;
  907. /* Process restart marker if needed; may have to suspend */
  908. if (cinfo->restart_interval) {
  909. if (entropy->restarts_to_go == 0)
  910. if (! process_restart(cinfo))
  911. return FALSE;
  912. }
  913. /* If we've run out of data, just leave the MCU set to zeroes.
  914. * This way, we return uniform gray for the remainder of the segment.
  915. */
  916. if (! entropy->insufficient_data) {
  917. natural_order = cinfo->natural_order;
  918. Se = cinfo->lim_Se;
  919. /* Load up working state */
  920. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  921. ASSIGN_STATE(state, entropy->saved);
  922. /* Outer loop handles each block in the MCU */
  923. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  924. JBLOCKROW block = MCU_data[blkn];
  925. d_derived_tbl * htbl;
  926. register int s, k, r;
  927. int coef_limit, ci;
  928. /* Decode a single block's worth of coefficients */
  929. /* Section F.2.2.1: decode the DC coefficient difference */
  930. htbl = entropy->dc_cur_tbls[blkn];
  931. HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
  932. htbl = entropy->ac_cur_tbls[blkn];
  933. k = 1;
  934. coef_limit = entropy->coef_limit[blkn];
  935. if (coef_limit) {
  936. /* Convert DC difference to actual value, update last_dc_val */
  937. if (s) {
  938. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  939. r = GET_BITS(s);
  940. s = HUFF_EXTEND(r, s);
  941. }
  942. ci = cinfo->MCU_membership[blkn];
  943. s += state.last_dc_val[ci];
  944. state.last_dc_val[ci] = s;
  945. /* Output the DC coefficient */
  946. (*block)[0] = (JCOEF) s;
  947. /* Section F.2.2.2: decode the AC coefficients */
  948. /* Since zeroes are skipped, output area must be cleared beforehand */
  949. for (; k < coef_limit; k++) {
  950. HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
  951. r = s >> 4;
  952. s &= 15;
  953. if (s) {
  954. k += r;
  955. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  956. r = GET_BITS(s);
  957. s = HUFF_EXTEND(r, s);
  958. /* Output coefficient in natural (dezigzagged) order.
  959. * Note: the extra entries in natural_order[] will save us
  960. * if k > Se, which could happen if the data is corrupted.
  961. */
  962. (*block)[natural_order[k]] = (JCOEF) s;
  963. } else {
  964. if (r != 15)
  965. goto EndOfBlock;
  966. k += 15;
  967. }
  968. }
  969. } else {
  970. if (s) {
  971. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  972. DROP_BITS(s);
  973. }
  974. }
  975. /* Section F.2.2.2: decode the AC coefficients */
  976. /* In this path we just discard the values */
  977. for (; k <= Se; k++) {
  978. HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
  979. r = s >> 4;
  980. s &= 15;
  981. if (s) {
  982. k += r;
  983. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  984. DROP_BITS(s);
  985. } else {
  986. if (r != 15)
  987. break;
  988. k += 15;
  989. }
  990. }
  991. EndOfBlock: ;
  992. }
  993. /* Completed MCU, so update state */
  994. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  995. ASSIGN_STATE(entropy->saved, state);
  996. }
  997. /* Account for restart interval (no-op if not using restarts) */
  998. entropy->restarts_to_go--;
  999. return TRUE;
  1000. }
  1001. /*
  1002. * Decode one MCU's worth of Huffman-compressed coefficients,
  1003. * full-size blocks.
  1004. */
  1005. METHODDEF(boolean)
  1006. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  1007. {
  1008. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1009. int blkn;
  1010. BITREAD_STATE_VARS;
  1011. savable_state state;
  1012. /* Process restart marker if needed; may have to suspend */
  1013. if (cinfo->restart_interval) {
  1014. if (entropy->restarts_to_go == 0)
  1015. if (! process_restart(cinfo))
  1016. return FALSE;
  1017. }
  1018. /* If we've run out of data, just leave the MCU set to zeroes.
  1019. * This way, we return uniform gray for the remainder of the segment.
  1020. */
  1021. if (! entropy->insufficient_data) {
  1022. /* Load up working state */
  1023. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  1024. ASSIGN_STATE(state, entropy->saved);
  1025. /* Outer loop handles each block in the MCU */
  1026. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  1027. JBLOCKROW block = MCU_data[blkn];
  1028. d_derived_tbl * htbl;
  1029. register int s, k, r;
  1030. int coef_limit, ci;
  1031. /* Decode a single block's worth of coefficients */
  1032. /* Section F.2.2.1: decode the DC coefficient difference */
  1033. htbl = entropy->dc_cur_tbls[blkn];
  1034. HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
  1035. htbl = entropy->ac_cur_tbls[blkn];
  1036. k = 1;
  1037. coef_limit = entropy->coef_limit[blkn];
  1038. if (coef_limit) {
  1039. /* Convert DC difference to actual value, update last_dc_val */
  1040. if (s) {
  1041. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1042. r = GET_BITS(s);
  1043. s = HUFF_EXTEND(r, s);
  1044. }
  1045. ci = cinfo->MCU_membership[blkn];
  1046. s += state.last_dc_val[ci];
  1047. state.last_dc_val[ci] = s;
  1048. /* Output the DC coefficient */
  1049. (*block)[0] = (JCOEF) s;
  1050. /* Section F.2.2.2: decode the AC coefficients */
  1051. /* Since zeroes are skipped, output area must be cleared beforehand */
  1052. for (; k < coef_limit; k++) {
  1053. HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
  1054. r = s >> 4;
  1055. s &= 15;
  1056. if (s) {
  1057. k += r;
  1058. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1059. r = GET_BITS(s);
  1060. s = HUFF_EXTEND(r, s);
  1061. /* Output coefficient in natural (dezigzagged) order.
  1062. * Note: the extra entries in jpeg_natural_order[] will save us
  1063. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  1064. */
  1065. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  1066. } else {
  1067. if (r != 15)
  1068. goto EndOfBlock;
  1069. k += 15;
  1070. }
  1071. }
  1072. } else {
  1073. if (s) {
  1074. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1075. DROP_BITS(s);
  1076. }
  1077. }
  1078. /* Section F.2.2.2: decode the AC coefficients */
  1079. /* In this path we just discard the values */
  1080. for (; k < DCTSIZE2; k++) {
  1081. HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
  1082. r = s >> 4;
  1083. s &= 15;
  1084. if (s) {
  1085. k += r;
  1086. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1087. DROP_BITS(s);
  1088. } else {
  1089. if (r != 15)
  1090. break;
  1091. k += 15;
  1092. }
  1093. }
  1094. EndOfBlock: ;
  1095. }
  1096. /* Completed MCU, so update state */
  1097. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  1098. ASSIGN_STATE(entropy->saved, state);
  1099. }
  1100. /* Account for restart interval (no-op if not using restarts) */
  1101. entropy->restarts_to_go--;
  1102. return TRUE;
  1103. }
  1104. /*
  1105. * Initialize for a Huffman-compressed scan.
  1106. */
  1107. METHODDEF(void)
  1108. start_pass_huff_decoder (j_decompress_ptr cinfo)
  1109. {
  1110. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1111. int ci, blkn, tbl, i;
  1112. jpeg_component_info * compptr;
  1113. if (cinfo->progressive_mode) {
  1114. /* Validate progressive scan parameters */
  1115. if (cinfo->Ss == 0) {
  1116. if (cinfo->Se != 0)
  1117. goto bad;
  1118. } else {
  1119. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  1120. if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se)
  1121. goto bad;
  1122. /* AC scans may have only one component */
  1123. if (cinfo->comps_in_scan != 1)
  1124. goto bad;
  1125. }
  1126. if (cinfo->Ah != 0) {
  1127. /* Successive approximation refinement scan: must have Al = Ah-1. */
  1128. if (cinfo->Ah-1 != cinfo->Al)
  1129. goto bad;
  1130. }
  1131. if (cinfo->Al > 13) { /* need not check for < 0 */
  1132. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  1133. * but the spec doesn't say so, and we try to be liberal about what we
  1134. * accept. Note: large Al values could result in out-of-range DC
  1135. * coefficients during early scans, leading to bizarre displays due to
  1136. * overflows in the IDCT math. But we won't crash.
  1137. */
  1138. bad:
  1139. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  1140. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  1141. }
  1142. /* Update progression status, and verify that scan order is legal.
  1143. * Note that inter-scan inconsistencies are treated as warnings
  1144. * not fatal errors ... not clear if this is right way to behave.
  1145. */
  1146. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1147. int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
  1148. int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  1149. if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  1150. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  1151. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  1152. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  1153. if (cinfo->Ah != expected)
  1154. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  1155. coef_bit_ptr[coefi] = cinfo->Al;
  1156. }
  1157. }
  1158. /* Select MCU decoding routine */
  1159. if (cinfo->Ah == 0) {
  1160. if (cinfo->Ss == 0)
  1161. entropy->pub.decode_mcu = decode_mcu_DC_first;
  1162. else
  1163. entropy->pub.decode_mcu = decode_mcu_AC_first;
  1164. } else {
  1165. if (cinfo->Ss == 0)
  1166. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  1167. else
  1168. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  1169. }
  1170. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1171. compptr = cinfo->cur_comp_info[ci];
  1172. /* Make sure requested tables are present, and compute derived tables.
  1173. * We may build same derived table more than once, but it's not expensive.
  1174. */
  1175. if (cinfo->Ss == 0) {
  1176. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  1177. tbl = compptr->dc_tbl_no;
  1178. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  1179. & entropy->derived_tbls[tbl]);
  1180. }
  1181. } else {
  1182. tbl = compptr->ac_tbl_no;
  1183. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  1184. & entropy->derived_tbls[tbl]);
  1185. /* remember the single active table */
  1186. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  1187. }
  1188. /* Initialize DC predictions to 0 */
  1189. entropy->saved.last_dc_val[ci] = 0;
  1190. }
  1191. /* Initialize private state variables */
  1192. entropy->saved.EOBRUN = 0;
  1193. } else {
  1194. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  1195. * This ought to be an error condition, but we make it a warning because
  1196. * there are some baseline files out there with all zeroes in these bytes.
  1197. */
  1198. if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||
  1199. ((cinfo->is_baseline || cinfo->Se < DCTSIZE2) &&
  1200. cinfo->Se != cinfo->lim_Se))
  1201. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  1202. /* Select MCU decoding routine */
  1203. /* We retain the hard-coded case for full-size blocks.
  1204. * This is not necessary, but it appears that this version is slightly
  1205. * more performant in the given implementation.
  1206. * With an improved implementation we would prefer a single optimized
  1207. * function.
  1208. */
  1209. if (cinfo->lim_Se != DCTSIZE2-1)
  1210. entropy->pub.decode_mcu = decode_mcu_sub;
  1211. else
  1212. entropy->pub.decode_mcu = decode_mcu;
  1213. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1214. compptr = cinfo->cur_comp_info[ci];
  1215. /* Compute derived values for Huffman tables */
  1216. /* We may do this more than once for a table, but it's not expensive */
  1217. tbl = compptr->dc_tbl_no;
  1218. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  1219. & entropy->dc_derived_tbls[tbl]);
  1220. if (cinfo->lim_Se) { /* AC needs no table when not present */
  1221. tbl = compptr->ac_tbl_no;
  1222. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  1223. & entropy->ac_derived_tbls[tbl]);
  1224. }
  1225. /* Initialize DC predictions to 0 */
  1226. entropy->saved.last_dc_val[ci] = 0;
  1227. }
  1228. /* Precalculate decoding info for each block in an MCU of this scan */
  1229. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  1230. ci = cinfo->MCU_membership[blkn];
  1231. compptr = cinfo->cur_comp_info[ci];
  1232. /* Precalculate which table to use for each block */
  1233. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  1234. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  1235. /* Decide whether we really care about the coefficient values */
  1236. if (compptr->component_needed) {
  1237. ci = compptr->DCT_v_scaled_size;
  1238. i = compptr->DCT_h_scaled_size;
  1239. switch (cinfo->lim_Se) {
  1240. case (1*1-1):
  1241. entropy->coef_limit[blkn] = 1;
  1242. break;
  1243. case (2*2-1):
  1244. if (ci <= 0 || ci > 2) ci = 2;
  1245. if (i <= 0 || i > 2) i = 2;
  1246. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order2[ci - 1][i - 1];
  1247. break;
  1248. case (3*3-1):
  1249. if (ci <= 0 || ci > 3) ci = 3;
  1250. if (i <= 0 || i > 3) i = 3;
  1251. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order3[ci - 1][i - 1];
  1252. break;
  1253. case (4*4-1):
  1254. if (ci <= 0 || ci > 4) ci = 4;
  1255. if (i <= 0 || i > 4) i = 4;
  1256. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order4[ci - 1][i - 1];
  1257. break;
  1258. case (5*5-1):
  1259. if (ci <= 0 || ci > 5) ci = 5;
  1260. if (i <= 0 || i > 5) i = 5;
  1261. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order5[ci - 1][i - 1];
  1262. break;
  1263. case (6*6-1):
  1264. if (ci <= 0 || ci > 6) ci = 6;
  1265. if (i <= 0 || i > 6) i = 6;
  1266. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order6[ci - 1][i - 1];
  1267. break;
  1268. case (7*7-1):
  1269. if (ci <= 0 || ci > 7) ci = 7;
  1270. if (i <= 0 || i > 7) i = 7;
  1271. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order7[ci - 1][i - 1];
  1272. break;
  1273. default:
  1274. if (ci <= 0 || ci > 8) ci = 8;
  1275. if (i <= 0 || i > 8) i = 8;
  1276. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];
  1277. break;
  1278. }
  1279. } else {
  1280. entropy->coef_limit[blkn] = 0;
  1281. }
  1282. }
  1283. }
  1284. /* Initialize bitread state variables */
  1285. entropy->bitstate.bits_left = 0;
  1286. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  1287. entropy->insufficient_data = FALSE;
  1288. /* Initialize restart counter */
  1289. entropy->restarts_to_go = cinfo->restart_interval;
  1290. }
  1291. /*
  1292. * Module initialization routine for Huffman entropy decoding.
  1293. */
  1294. GLOBAL(void)
  1295. jinit_huff_decoder (j_decompress_ptr cinfo)
  1296. {
  1297. huff_entropy_ptr entropy;
  1298. int i;
  1299. entropy = (huff_entropy_ptr)
  1300. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1301. SIZEOF(huff_entropy_decoder));
  1302. cinfo->entropy = &entropy->pub;
  1303. entropy->pub.start_pass = start_pass_huff_decoder;
  1304. entropy->pub.finish_pass = finish_pass_huff;
  1305. if (cinfo->progressive_mode) {
  1306. /* Create progression status table */
  1307. int *coef_bit_ptr, ci;
  1308. cinfo->coef_bits = (int (*)[DCTSIZE2])
  1309. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1310. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  1311. coef_bit_ptr = & cinfo->coef_bits[0][0];
  1312. for (ci = 0; ci < cinfo->num_components; ci++)
  1313. for (i = 0; i < DCTSIZE2; i++)
  1314. *coef_bit_ptr++ = -1;
  1315. /* Mark derived tables unallocated */
  1316. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1317. entropy->derived_tbls[i] = NULL;
  1318. }
  1319. } else {
  1320. /* Mark tables unallocated */
  1321. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1322. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  1323. }
  1324. }
  1325. }