jdhuff.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559
  1. /*
  2. * jdhuff.c
  3. *
  4. * Copyright (C) 1991-1997, Thomas G. Lane.
  5. * Modified 2006-2019 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. htbl = jpeg_std_huff_table((j_common_ptr) cinfo, isDC, tblno);
  291. /* Allocate a workspace if we haven't already done so. */
  292. if (*pdtbl == NULL)
  293. *pdtbl = (d_derived_tbl *) (*cinfo->mem->alloc_small)
  294. ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(d_derived_tbl));
  295. dtbl = *pdtbl;
  296. dtbl->pub = htbl; /* fill in back link */
  297. /* Figure C.1: make table of Huffman code length for each symbol */
  298. p = 0;
  299. for (l = 1; l <= 16; l++) {
  300. i = (int) htbl->bits[l];
  301. if (i < 0 || p + i > 256) /* protect against table overrun */
  302. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  303. while (i--)
  304. huffsize[p++] = (char) l;
  305. }
  306. huffsize[p] = 0;
  307. numsymbols = p;
  308. /* Figure C.2: generate the codes themselves */
  309. /* We also validate that the counts represent a legal Huffman code tree. */
  310. code = 0;
  311. si = huffsize[0];
  312. p = 0;
  313. while (huffsize[p]) {
  314. while (((int) huffsize[p]) == si) {
  315. huffcode[p++] = code;
  316. code++;
  317. }
  318. /* code is now 1 more than the last code used for codelength si; but
  319. * it must still fit in si bits, since no code is allowed to be all ones.
  320. */
  321. if (((INT32) code) >= (((INT32) 1) << si))
  322. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  323. code <<= 1;
  324. si++;
  325. }
  326. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  327. p = 0;
  328. for (l = 1; l <= 16; l++) {
  329. if (htbl->bits[l]) {
  330. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  331. * minus the minimum code of length l
  332. */
  333. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  334. p += htbl->bits[l];
  335. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  336. } else {
  337. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  338. }
  339. }
  340. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  341. /* Compute lookahead tables to speed up decoding.
  342. * First we set all the table entries to 0, indicating "too long";
  343. * then we iterate through the Huffman codes that are short enough and
  344. * fill in all the entries that correspond to bit sequences starting
  345. * with that code.
  346. */
  347. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  348. p = 0;
  349. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  350. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  351. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  352. /* Generate left-justified code followed by all possible bit sequences */
  353. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  354. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  355. dtbl->look_nbits[lookbits] = l;
  356. dtbl->look_sym[lookbits] = htbl->huffval[p];
  357. lookbits++;
  358. }
  359. }
  360. }
  361. /* Validate symbols as being reasonable.
  362. * For AC tables, we make no check, but accept all byte values 0..255.
  363. * For DC tables, we require the symbols to be in range 0..15.
  364. * (Tighter bounds could be applied depending on the data depth and mode,
  365. * but this is sufficient to ensure safe decoding.)
  366. */
  367. if (isDC) {
  368. for (i = 0; i < numsymbols; i++) {
  369. int sym = htbl->huffval[i];
  370. if (sym < 0 || sym > 15)
  371. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  372. }
  373. }
  374. }
  375. /*
  376. * Out-of-line code for bit fetching.
  377. * Note: current values of get_buffer and bits_left are passed as parameters,
  378. * but are returned in the corresponding fields of the state struct.
  379. *
  380. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  381. * of get_buffer to be used. (On machines with wider words, an even larger
  382. * buffer could be used.) However, on some machines 32-bit shifts are
  383. * quite slow and take time proportional to the number of places shifted.
  384. * (This is true with most PC compilers, for instance.) In this case it may
  385. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  386. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  387. */
  388. #ifdef SLOW_SHIFT_32
  389. #define MIN_GET_BITS 15 /* minimum allowable value */
  390. #else
  391. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  392. #endif
  393. LOCAL(boolean)
  394. jpeg_fill_bit_buffer (bitread_working_state * state,
  395. register bit_buf_type get_buffer, register int bits_left,
  396. int nbits)
  397. /* Load up the bit buffer to a depth of at least nbits */
  398. {
  399. /* Copy heavily used state fields into locals (hopefully registers) */
  400. register const JOCTET * next_input_byte = state->next_input_byte;
  401. register size_t bytes_in_buffer = state->bytes_in_buffer;
  402. j_decompress_ptr cinfo = state->cinfo;
  403. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  404. /* (It is assumed that no request will be for more than that many bits.) */
  405. /* We fail to do so only if we hit a marker or are forced to suspend. */
  406. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  407. while (bits_left < MIN_GET_BITS) {
  408. register int c;
  409. /* Attempt to read a byte */
  410. if (bytes_in_buffer == 0) {
  411. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  412. return FALSE;
  413. next_input_byte = cinfo->src->next_input_byte;
  414. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  415. }
  416. bytes_in_buffer--;
  417. c = GETJOCTET(*next_input_byte++);
  418. /* If it's 0xFF, check and discard stuffed zero byte */
  419. if (c == 0xFF) {
  420. /* Loop here to discard any padding FF's on terminating marker,
  421. * so that we can save a valid unread_marker value. NOTE: we will
  422. * accept multiple FF's followed by a 0 as meaning a single FF data
  423. * byte. This data pattern is not valid according to the standard.
  424. */
  425. do {
  426. if (bytes_in_buffer == 0) {
  427. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  428. return FALSE;
  429. next_input_byte = cinfo->src->next_input_byte;
  430. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  431. }
  432. bytes_in_buffer--;
  433. c = GETJOCTET(*next_input_byte++);
  434. } while (c == 0xFF);
  435. if (c == 0) {
  436. /* Found FF/00, which represents an FF data byte */
  437. c = 0xFF;
  438. } else {
  439. /* Oops, it's actually a marker indicating end of compressed data.
  440. * Save the marker code for later use.
  441. * Fine point: it might appear that we should save the marker into
  442. * bitread working state, not straight into permanent state. But
  443. * once we have hit a marker, we cannot need to suspend within the
  444. * current MCU, because we will read no more bytes from the data
  445. * source. So it is OK to update permanent state right away.
  446. */
  447. cinfo->unread_marker = c;
  448. /* See if we need to insert some fake zero bits. */
  449. goto no_more_bytes;
  450. }
  451. }
  452. /* OK, load c into get_buffer */
  453. get_buffer = (get_buffer << 8) | c;
  454. bits_left += 8;
  455. } /* end while */
  456. } else {
  457. no_more_bytes:
  458. /* We get here if we've read the marker that terminates the compressed
  459. * data segment. There should be enough bits in the buffer register
  460. * to satisfy the request; if so, no problem.
  461. */
  462. if (nbits > bits_left) {
  463. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  464. * the data stream, so that we can produce some kind of image.
  465. * We use a nonvolatile flag to ensure that only one warning message
  466. * appears per data segment.
  467. */
  468. if (! ((huff_entropy_ptr) cinfo->entropy)->insufficient_data) {
  469. WARNMS(cinfo, JWRN_HIT_MARKER);
  470. ((huff_entropy_ptr) cinfo->entropy)->insufficient_data = TRUE;
  471. }
  472. /* Fill the buffer with zero bits */
  473. get_buffer <<= MIN_GET_BITS - bits_left;
  474. bits_left = MIN_GET_BITS;
  475. }
  476. }
  477. /* Unload the local registers */
  478. state->next_input_byte = next_input_byte;
  479. state->bytes_in_buffer = bytes_in_buffer;
  480. state->get_buffer = get_buffer;
  481. state->bits_left = bits_left;
  482. return TRUE;
  483. }
  484. /*
  485. * Figure F.12: extend sign bit.
  486. * On some machines, a shift and sub will be faster than a table lookup.
  487. */
  488. #ifdef AVOID_TABLES
  489. #define BIT_MASK(nbits) ((1<<(nbits))-1)
  490. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) - ((1<<(s))-1) : (x))
  491. #else
  492. #define BIT_MASK(nbits) bmask[nbits]
  493. #define HUFF_EXTEND(x,s) ((x) <= bmask[(s) - 1] ? (x) - bmask[s] : (x))
  494. static const int bmask[16] = /* bmask[n] is mask for n rightmost bits */
  495. { 0, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
  496. 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF };
  497. #endif /* AVOID_TABLES */
  498. /*
  499. * Out-of-line code for Huffman code decoding.
  500. */
  501. LOCAL(int)
  502. jpeg_huff_decode (bitread_working_state * state,
  503. register bit_buf_type get_buffer, register int bits_left,
  504. d_derived_tbl * htbl, int min_bits)
  505. {
  506. register int l = min_bits;
  507. register INT32 code;
  508. /* HUFF_DECODE has determined that the code is at least min_bits */
  509. /* bits long, so fetch that many bits in one swoop. */
  510. CHECK_BIT_BUFFER(*state, l, return -1);
  511. code = GET_BITS(l);
  512. /* Collect the rest of the Huffman code one bit at a time. */
  513. /* This is per Figure F.16 in the JPEG spec. */
  514. while (code > htbl->maxcode[l]) {
  515. code <<= 1;
  516. CHECK_BIT_BUFFER(*state, 1, return -1);
  517. code |= GET_BITS(1);
  518. l++;
  519. }
  520. /* Unload the local registers */
  521. state->get_buffer = get_buffer;
  522. state->bits_left = bits_left;
  523. /* With garbage input we may reach the sentinel value l = 17. */
  524. if (l > 16) {
  525. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  526. return 0; /* fake a zero as the safest result */
  527. }
  528. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  529. }
  530. /*
  531. * Finish up at the end of a Huffman-compressed scan.
  532. */
  533. METHODDEF(void)
  534. finish_pass_huff (j_decompress_ptr cinfo)
  535. {
  536. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  537. /* Throw away any unused bits remaining in bit buffer; */
  538. /* include any full bytes in next_marker's count of discarded bytes */
  539. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  540. entropy->bitstate.bits_left = 0;
  541. }
  542. /*
  543. * Check for a restart marker & resynchronize decoder.
  544. * Returns FALSE if must suspend.
  545. */
  546. LOCAL(boolean)
  547. process_restart (j_decompress_ptr cinfo)
  548. {
  549. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  550. int ci;
  551. finish_pass_huff(cinfo);
  552. /* Advance past the RSTn marker */
  553. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  554. return FALSE;
  555. /* Re-initialize DC predictions to 0 */
  556. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  557. entropy->saved.last_dc_val[ci] = 0;
  558. /* Re-init EOB run count, too */
  559. entropy->saved.EOBRUN = 0;
  560. /* Reset restart counter */
  561. entropy->restarts_to_go = cinfo->restart_interval;
  562. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  563. * against a marker. In that case we will end up treating the next data
  564. * segment as empty, and we can avoid producing bogus output pixels by
  565. * leaving the flag set.
  566. */
  567. if (cinfo->unread_marker == 0)
  568. entropy->insufficient_data = FALSE;
  569. return TRUE;
  570. }
  571. /*
  572. * Huffman MCU decoding.
  573. * Each of these routines decodes and returns one MCU's worth of
  574. * Huffman-compressed coefficients.
  575. * The coefficients are reordered from zigzag order into natural array order,
  576. * but are not dequantized.
  577. *
  578. * The i'th block of the MCU is stored into the block pointed to by
  579. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  580. * (Wholesale zeroing is usually a little faster than retail...)
  581. *
  582. * We return FALSE if data source requested suspension. In that case no
  583. * changes have been made to permanent state. (Exception: some output
  584. * coefficients may already have been assigned. This is harmless for
  585. * spectral selection, since we'll just re-assign them on the next call.
  586. * Successive approximation AC refinement has to be more careful, however.)
  587. */
  588. /*
  589. * MCU decoding for DC initial scan (either spectral selection,
  590. * or first pass of successive approximation).
  591. */
  592. METHODDEF(boolean)
  593. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  594. {
  595. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  596. int Al = cinfo->Al;
  597. register int s, r;
  598. int blkn, ci;
  599. JBLOCKROW block;
  600. BITREAD_STATE_VARS;
  601. savable_state state;
  602. d_derived_tbl * tbl;
  603. jpeg_component_info * compptr;
  604. /* Process restart marker if needed; may have to suspend */
  605. if (cinfo->restart_interval) {
  606. if (entropy->restarts_to_go == 0)
  607. if (! process_restart(cinfo))
  608. return FALSE;
  609. }
  610. /* If we've run out of data, just leave the MCU set to zeroes.
  611. * This way, we return uniform gray for the remainder of the segment.
  612. */
  613. if (! entropy->insufficient_data) {
  614. /* Load up working state */
  615. BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
  616. ASSIGN_STATE(state, entropy->saved);
  617. /* Outer loop handles each block in the MCU */
  618. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  619. block = MCU_data[blkn];
  620. ci = cinfo->MCU_membership[blkn];
  621. compptr = cinfo->cur_comp_info[ci];
  622. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  623. /* Decode a single block's worth of coefficients */
  624. /* Section F.2.2.1: decode the DC coefficient difference */
  625. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  626. if (s) {
  627. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  628. r = GET_BITS(s);
  629. s = HUFF_EXTEND(r, s);
  630. }
  631. /* Convert DC difference to actual value, update last_dc_val */
  632. s += state.last_dc_val[ci];
  633. state.last_dc_val[ci] = s;
  634. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  635. (*block)[0] = (JCOEF) (s << Al);
  636. }
  637. /* Completed MCU, so update state */
  638. BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
  639. ASSIGN_STATE(entropy->saved, state);
  640. }
  641. /* Account for restart interval if using restarts */
  642. if (cinfo->restart_interval)
  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. /* Load up working state.
  672. * We can avoid loading/saving bitread state if in an EOB run.
  673. */
  674. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  675. /* There is always only one block per MCU */
  676. if (EOBRUN) /* if it's a band of zeroes... */
  677. EOBRUN--; /* ...process it now (we do nothing) */
  678. else {
  679. BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
  680. Se = cinfo->Se;
  681. Al = cinfo->Al;
  682. natural_order = cinfo->natural_order;
  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 if using restarts */
  716. if (cinfo->restart_interval)
  717. entropy->restarts_to_go--;
  718. return TRUE;
  719. }
  720. /*
  721. * MCU decoding for DC successive approximation refinement scan.
  722. * Note: we assume such scans can be multi-component,
  723. * although the spec is not very clear on the point.
  724. */
  725. METHODDEF(boolean)
  726. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  727. {
  728. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  729. JCOEF p1;
  730. int blkn;
  731. BITREAD_STATE_VARS;
  732. /* Process restart marker if needed; may have to suspend */
  733. if (cinfo->restart_interval) {
  734. if (entropy->restarts_to_go == 0)
  735. if (! process_restart(cinfo))
  736. return FALSE;
  737. }
  738. /* Not worth the cycles to check insufficient_data here,
  739. * since we will not change the data anyway if we read zeroes.
  740. */
  741. /* Load up working state */
  742. BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
  743. p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  744. /* Outer loop handles each block in the MCU */
  745. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  746. /* Encoded data is simply the next bit of the two's-complement DC value */
  747. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  748. if (GET_BITS(1))
  749. MCU_data[blkn][0][0] |= p1;
  750. /* Note: since we use |=, repeating the assignment later is safe */
  751. }
  752. /* Completed MCU, so update state */
  753. BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
  754. /* Account for restart interval if using restarts */
  755. if (cinfo->restart_interval)
  756. entropy->restarts_to_go--;
  757. return TRUE;
  758. }
  759. /*
  760. * MCU decoding for AC successive approximation refinement scan.
  761. */
  762. METHODDEF(boolean)
  763. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  764. {
  765. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  766. register int s, k, r;
  767. unsigned int EOBRUN;
  768. int Se;
  769. JCOEF p1, m1;
  770. const int * natural_order;
  771. JBLOCKROW block;
  772. JCOEFPTR thiscoef;
  773. BITREAD_STATE_VARS;
  774. d_derived_tbl * tbl;
  775. int num_newnz;
  776. int newnz_pos[DCTSIZE2];
  777. /* Process restart marker if needed; may have to suspend */
  778. if (cinfo->restart_interval) {
  779. if (entropy->restarts_to_go == 0)
  780. if (! process_restart(cinfo))
  781. return FALSE;
  782. }
  783. /* If we've run out of data, don't modify the MCU.
  784. */
  785. if (! entropy->insufficient_data) {
  786. Se = cinfo->Se;
  787. p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  788. m1 = -p1; /* -1 in the bit position being coded */
  789. natural_order = cinfo->natural_order;
  790. /* Load up working state */
  791. BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
  792. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  793. /* There is always only one block per MCU */
  794. block = MCU_data[0];
  795. tbl = entropy->ac_derived_tbl;
  796. /* If we are forced to suspend, we must undo the assignments to any newly
  797. * nonzero coefficients in the block, because otherwise we'd get confused
  798. * next time about which coefficients were already nonzero.
  799. * But we need not undo addition of bits to already-nonzero coefficients;
  800. * instead, we can test the current bit to see if we already did it.
  801. */
  802. num_newnz = 0;
  803. /* initialize coefficient loop counter to start of band */
  804. k = cinfo->Ss;
  805. if (EOBRUN == 0) {
  806. do {
  807. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  808. r = s >> 4;
  809. s &= 15;
  810. if (s) {
  811. if (s != 1) /* size of new coef should always be 1 */
  812. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  813. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  814. if (GET_BITS(1))
  815. s = p1; /* newly nonzero coef is positive */
  816. else
  817. s = m1; /* newly nonzero coef is negative */
  818. } else {
  819. if (r != 15) {
  820. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  821. if (r) {
  822. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  823. r = GET_BITS(r);
  824. EOBRUN += r;
  825. }
  826. break; /* rest of block is handled by EOB logic */
  827. }
  828. /* note s = 0 for processing ZRL */
  829. }
  830. /* Advance over already-nonzero coefs and r still-zero coefs,
  831. * appending correction bits to the nonzeroes. A correction bit is 1
  832. * if the absolute value of the coefficient must be increased.
  833. */
  834. do {
  835. thiscoef = *block + natural_order[k];
  836. if (*thiscoef) {
  837. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  838. if (GET_BITS(1)) {
  839. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  840. if (*thiscoef >= 0)
  841. *thiscoef += p1;
  842. else
  843. *thiscoef += m1;
  844. }
  845. }
  846. } else {
  847. if (--r < 0)
  848. break; /* reached target zero coefficient */
  849. }
  850. k++;
  851. } while (k <= Se);
  852. if (s) {
  853. int pos = natural_order[k];
  854. /* Output newly nonzero coefficient */
  855. (*block)[pos] = (JCOEF) s;
  856. /* Remember its position in case we have to suspend */
  857. newnz_pos[num_newnz++] = pos;
  858. }
  859. k++;
  860. } while (k <= Se);
  861. }
  862. if (EOBRUN) {
  863. /* Scan any remaining coefficient positions after the end-of-band
  864. * (the last newly nonzero coefficient, if any). Append a correction
  865. * bit to each already-nonzero coefficient. A correction bit is 1
  866. * if the absolute value of the coefficient must be increased.
  867. */
  868. do {
  869. thiscoef = *block + natural_order[k];
  870. if (*thiscoef) {
  871. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  872. if (GET_BITS(1)) {
  873. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  874. if (*thiscoef >= 0)
  875. *thiscoef += p1;
  876. else
  877. *thiscoef += m1;
  878. }
  879. }
  880. }
  881. k++;
  882. } while (k <= Se);
  883. /* Count one block completed in EOB run */
  884. EOBRUN--;
  885. }
  886. /* Completed MCU, so update state */
  887. BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
  888. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  889. }
  890. /* Account for restart interval if using restarts */
  891. if (cinfo->restart_interval)
  892. entropy->restarts_to_go--;
  893. return TRUE;
  894. undoit:
  895. /* Re-zero any output coefficients that we made newly nonzero */
  896. while (num_newnz)
  897. (*block)[newnz_pos[--num_newnz]] = 0;
  898. return FALSE;
  899. }
  900. /*
  901. * Decode one MCU's worth of Huffman-compressed coefficients,
  902. * partial blocks.
  903. */
  904. METHODDEF(boolean)
  905. decode_mcu_sub (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  906. {
  907. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  908. const int * natural_order;
  909. int Se, blkn;
  910. BITREAD_STATE_VARS;
  911. savable_state state;
  912. /* Process restart marker if needed; may have to suspend */
  913. if (cinfo->restart_interval) {
  914. if (entropy->restarts_to_go == 0)
  915. if (! process_restart(cinfo))
  916. return FALSE;
  917. }
  918. /* If we've run out of data, just leave the MCU set to zeroes.
  919. * This way, we return uniform gray for the remainder of the segment.
  920. */
  921. if (! entropy->insufficient_data) {
  922. natural_order = cinfo->natural_order;
  923. Se = cinfo->lim_Se;
  924. /* Load up working state */
  925. BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
  926. ASSIGN_STATE(state, entropy->saved);
  927. /* Outer loop handles each block in the MCU */
  928. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  929. JBLOCKROW block = MCU_data[blkn];
  930. d_derived_tbl * htbl;
  931. register int s, k, r;
  932. int coef_limit, ci;
  933. /* Decode a single block's worth of coefficients */
  934. /* Section F.2.2.1: decode the DC coefficient difference */
  935. htbl = entropy->dc_cur_tbls[blkn];
  936. HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
  937. htbl = entropy->ac_cur_tbls[blkn];
  938. k = 1;
  939. coef_limit = entropy->coef_limit[blkn];
  940. if (coef_limit) {
  941. /* Convert DC difference to actual value, update last_dc_val */
  942. if (s) {
  943. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  944. r = GET_BITS(s);
  945. s = HUFF_EXTEND(r, s);
  946. }
  947. ci = cinfo->MCU_membership[blkn];
  948. s += state.last_dc_val[ci];
  949. state.last_dc_val[ci] = s;
  950. /* Output the DC coefficient */
  951. (*block)[0] = (JCOEF) s;
  952. /* Section F.2.2.2: decode the AC coefficients */
  953. /* Since zeroes are skipped, output area must be cleared beforehand */
  954. for (; k < coef_limit; k++) {
  955. HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
  956. r = s >> 4;
  957. s &= 15;
  958. if (s) {
  959. k += r;
  960. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  961. r = GET_BITS(s);
  962. s = HUFF_EXTEND(r, s);
  963. /* Output coefficient in natural (dezigzagged) order.
  964. * Note: the extra entries in natural_order[] will save us
  965. * if k > Se, which could happen if the data is corrupted.
  966. */
  967. (*block)[natural_order[k]] = (JCOEF) s;
  968. } else {
  969. if (r != 15)
  970. goto EndOfBlock;
  971. k += 15;
  972. }
  973. }
  974. } else {
  975. if (s) {
  976. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  977. DROP_BITS(s);
  978. }
  979. }
  980. /* Section F.2.2.2: decode the AC coefficients */
  981. /* In this path we just discard the values */
  982. for (; k <= Se; k++) {
  983. HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
  984. r = s >> 4;
  985. s &= 15;
  986. if (s) {
  987. k += r;
  988. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  989. DROP_BITS(s);
  990. } else {
  991. if (r != 15)
  992. break;
  993. k += 15;
  994. }
  995. }
  996. EndOfBlock: ;
  997. }
  998. /* Completed MCU, so update state */
  999. BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
  1000. ASSIGN_STATE(entropy->saved, state);
  1001. }
  1002. /* Account for restart interval if using restarts */
  1003. if (cinfo->restart_interval)
  1004. entropy->restarts_to_go--;
  1005. return TRUE;
  1006. }
  1007. /*
  1008. * Decode one MCU's worth of Huffman-compressed coefficients,
  1009. * full-size blocks.
  1010. */
  1011. METHODDEF(boolean)
  1012. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  1013. {
  1014. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1015. int blkn;
  1016. BITREAD_STATE_VARS;
  1017. savable_state state;
  1018. /* Process restart marker if needed; may have to suspend */
  1019. if (cinfo->restart_interval) {
  1020. if (entropy->restarts_to_go == 0)
  1021. if (! process_restart(cinfo))
  1022. return FALSE;
  1023. }
  1024. /* If we've run out of data, just leave the MCU set to zeroes.
  1025. * This way, we return uniform gray for the remainder of the segment.
  1026. */
  1027. if (! entropy->insufficient_data) {
  1028. /* Load up working state */
  1029. BITREAD_LOAD_STATE(cinfo, entropy->bitstate);
  1030. ASSIGN_STATE(state, entropy->saved);
  1031. /* Outer loop handles each block in the MCU */
  1032. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  1033. JBLOCKROW block = MCU_data[blkn];
  1034. d_derived_tbl * htbl;
  1035. register int s, k, r;
  1036. int coef_limit, ci;
  1037. /* Decode a single block's worth of coefficients */
  1038. /* Section F.2.2.1: decode the DC coefficient difference */
  1039. htbl = entropy->dc_cur_tbls[blkn];
  1040. HUFF_DECODE(s, br_state, htbl, return FALSE, label1);
  1041. htbl = entropy->ac_cur_tbls[blkn];
  1042. k = 1;
  1043. coef_limit = entropy->coef_limit[blkn];
  1044. if (coef_limit) {
  1045. /* Convert DC difference to actual value, update last_dc_val */
  1046. if (s) {
  1047. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1048. r = GET_BITS(s);
  1049. s = HUFF_EXTEND(r, s);
  1050. }
  1051. ci = cinfo->MCU_membership[blkn];
  1052. s += state.last_dc_val[ci];
  1053. state.last_dc_val[ci] = s;
  1054. /* Output the DC coefficient */
  1055. (*block)[0] = (JCOEF) s;
  1056. /* Section F.2.2.2: decode the AC coefficients */
  1057. /* Since zeroes are skipped, output area must be cleared beforehand */
  1058. for (; k < coef_limit; k++) {
  1059. HUFF_DECODE(s, br_state, htbl, return FALSE, label2);
  1060. r = s >> 4;
  1061. s &= 15;
  1062. if (s) {
  1063. k += r;
  1064. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1065. r = GET_BITS(s);
  1066. s = HUFF_EXTEND(r, s);
  1067. /* Output coefficient in natural (dezigzagged) order.
  1068. * Note: the extra entries in jpeg_natural_order[] will save us
  1069. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  1070. */
  1071. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  1072. } else {
  1073. if (r != 15)
  1074. goto EndOfBlock;
  1075. k += 15;
  1076. }
  1077. }
  1078. } else {
  1079. if (s) {
  1080. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1081. DROP_BITS(s);
  1082. }
  1083. }
  1084. /* Section F.2.2.2: decode the AC coefficients */
  1085. /* In this path we just discard the values */
  1086. for (; k < DCTSIZE2; k++) {
  1087. HUFF_DECODE(s, br_state, htbl, return FALSE, label3);
  1088. r = s >> 4;
  1089. s &= 15;
  1090. if (s) {
  1091. k += r;
  1092. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  1093. DROP_BITS(s);
  1094. } else {
  1095. if (r != 15)
  1096. break;
  1097. k += 15;
  1098. }
  1099. }
  1100. EndOfBlock: ;
  1101. }
  1102. /* Completed MCU, so update state */
  1103. BITREAD_SAVE_STATE(cinfo, entropy->bitstate);
  1104. ASSIGN_STATE(entropy->saved, state);
  1105. }
  1106. /* Account for restart interval if using restarts */
  1107. if (cinfo->restart_interval)
  1108. entropy->restarts_to_go--;
  1109. return TRUE;
  1110. }
  1111. /*
  1112. * Initialize for a Huffman-compressed scan.
  1113. */
  1114. METHODDEF(void)
  1115. start_pass_huff_decoder (j_decompress_ptr cinfo)
  1116. {
  1117. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1118. int ci, blkn, tbl, i;
  1119. jpeg_component_info * compptr;
  1120. if (cinfo->progressive_mode) {
  1121. /* Validate progressive scan parameters */
  1122. if (cinfo->Ss == 0) {
  1123. if (cinfo->Se != 0)
  1124. goto bad;
  1125. } else {
  1126. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  1127. if (cinfo->Se < cinfo->Ss || cinfo->Se > cinfo->lim_Se)
  1128. goto bad;
  1129. /* AC scans may have only one component */
  1130. if (cinfo->comps_in_scan != 1)
  1131. goto bad;
  1132. }
  1133. if (cinfo->Ah != 0) {
  1134. /* Successive approximation refinement scan: must have Al = Ah-1. */
  1135. if (cinfo->Ah-1 != cinfo->Al)
  1136. goto bad;
  1137. }
  1138. if (cinfo->Al > 13) { /* need not check for < 0 */
  1139. /* Arguably the maximum Al value should be less than 13 for 8-bit
  1140. * precision, but the spec doesn't say so, and we try to be liberal
  1141. * about what we accept. Note: large Al values could result in
  1142. * out-of-range DC coefficients during early scans, leading to bizarre
  1143. * displays due to overflows in the IDCT math. But we won't crash.
  1144. */
  1145. bad:
  1146. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  1147. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  1148. }
  1149. /* Update progression status, and verify that scan order is legal.
  1150. * Note that inter-scan inconsistencies are treated as warnings
  1151. * not fatal errors ... not clear if this is right way to behave.
  1152. */
  1153. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1154. int coefi, cindex = cinfo->cur_comp_info[ci]->component_index;
  1155. int *coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  1156. if (cinfo->Ss && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  1157. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  1158. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  1159. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  1160. if (cinfo->Ah != expected)
  1161. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  1162. coef_bit_ptr[coefi] = cinfo->Al;
  1163. }
  1164. }
  1165. /* Select MCU decoding routine */
  1166. if (cinfo->Ah == 0) {
  1167. if (cinfo->Ss == 0)
  1168. entropy->pub.decode_mcu = decode_mcu_DC_first;
  1169. else
  1170. entropy->pub.decode_mcu = decode_mcu_AC_first;
  1171. } else {
  1172. if (cinfo->Ss == 0)
  1173. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  1174. else
  1175. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  1176. }
  1177. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1178. compptr = cinfo->cur_comp_info[ci];
  1179. /* Make sure requested tables are present, and compute derived tables.
  1180. * We may build same derived table more than once, but it's not expensive.
  1181. */
  1182. if (cinfo->Ss == 0) {
  1183. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  1184. tbl = compptr->dc_tbl_no;
  1185. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  1186. & entropy->derived_tbls[tbl]);
  1187. }
  1188. } else {
  1189. tbl = compptr->ac_tbl_no;
  1190. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  1191. & entropy->derived_tbls[tbl]);
  1192. /* remember the single active table */
  1193. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  1194. }
  1195. /* Initialize DC predictions to 0 */
  1196. entropy->saved.last_dc_val[ci] = 0;
  1197. }
  1198. /* Initialize private state variables */
  1199. entropy->saved.EOBRUN = 0;
  1200. } else {
  1201. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  1202. * This ought to be an error condition, but we make it a warning because
  1203. * there are some baseline files out there with all zeroes in these bytes.
  1204. */
  1205. if (cinfo->Ss != 0 || cinfo->Ah != 0 || cinfo->Al != 0 ||
  1206. ((cinfo->is_baseline || cinfo->Se < DCTSIZE2) &&
  1207. cinfo->Se != cinfo->lim_Se))
  1208. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  1209. /* Select MCU decoding routine */
  1210. /* We retain the hard-coded case for full-size blocks.
  1211. * This is not necessary, but it appears that this version is slightly
  1212. * more performant in the given implementation.
  1213. * With an improved implementation we would prefer a single optimized
  1214. * function.
  1215. */
  1216. if (cinfo->lim_Se != DCTSIZE2-1)
  1217. entropy->pub.decode_mcu = decode_mcu_sub;
  1218. else
  1219. entropy->pub.decode_mcu = decode_mcu;
  1220. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1221. compptr = cinfo->cur_comp_info[ci];
  1222. /* Compute derived values for Huffman tables */
  1223. /* We may do this more than once for a table, but it's not expensive */
  1224. tbl = compptr->dc_tbl_no;
  1225. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  1226. & entropy->dc_derived_tbls[tbl]);
  1227. if (cinfo->lim_Se) { /* AC needs no table when not present */
  1228. tbl = compptr->ac_tbl_no;
  1229. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  1230. & entropy->ac_derived_tbls[tbl]);
  1231. }
  1232. /* Initialize DC predictions to 0 */
  1233. entropy->saved.last_dc_val[ci] = 0;
  1234. }
  1235. /* Precalculate decoding info for each block in an MCU of this scan */
  1236. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  1237. ci = cinfo->MCU_membership[blkn];
  1238. compptr = cinfo->cur_comp_info[ci];
  1239. /* Precalculate which table to use for each block */
  1240. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  1241. entropy->ac_cur_tbls[blkn] = /* AC needs no table when not present */
  1242. cinfo->lim_Se ? entropy->ac_derived_tbls[compptr->ac_tbl_no] : NULL;
  1243. /* Decide whether we really care about the coefficient values */
  1244. if (compptr->component_needed) {
  1245. ci = compptr->DCT_v_scaled_size;
  1246. i = compptr->DCT_h_scaled_size;
  1247. switch (cinfo->lim_Se) {
  1248. case (1*1-1):
  1249. entropy->coef_limit[blkn] = 1;
  1250. break;
  1251. case (2*2-1):
  1252. if (ci <= 0 || ci > 2) ci = 2;
  1253. if (i <= 0 || i > 2) i = 2;
  1254. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order2[ci - 1][i - 1];
  1255. break;
  1256. case (3*3-1):
  1257. if (ci <= 0 || ci > 3) ci = 3;
  1258. if (i <= 0 || i > 3) i = 3;
  1259. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order3[ci - 1][i - 1];
  1260. break;
  1261. case (4*4-1):
  1262. if (ci <= 0 || ci > 4) ci = 4;
  1263. if (i <= 0 || i > 4) i = 4;
  1264. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order4[ci - 1][i - 1];
  1265. break;
  1266. case (5*5-1):
  1267. if (ci <= 0 || ci > 5) ci = 5;
  1268. if (i <= 0 || i > 5) i = 5;
  1269. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order5[ci - 1][i - 1];
  1270. break;
  1271. case (6*6-1):
  1272. if (ci <= 0 || ci > 6) ci = 6;
  1273. if (i <= 0 || i > 6) i = 6;
  1274. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order6[ci - 1][i - 1];
  1275. break;
  1276. case (7*7-1):
  1277. if (ci <= 0 || ci > 7) ci = 7;
  1278. if (i <= 0 || i > 7) i = 7;
  1279. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order7[ci - 1][i - 1];
  1280. break;
  1281. default:
  1282. if (ci <= 0 || ci > 8) ci = 8;
  1283. if (i <= 0 || i > 8) i = 8;
  1284. entropy->coef_limit[blkn] = 1 + jpeg_zigzag_order[ci - 1][i - 1];
  1285. }
  1286. } else {
  1287. entropy->coef_limit[blkn] = 0;
  1288. }
  1289. }
  1290. }
  1291. /* Initialize bitread state variables */
  1292. entropy->bitstate.bits_left = 0;
  1293. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  1294. entropy->insufficient_data = FALSE;
  1295. /* Initialize restart counter */
  1296. entropy->restarts_to_go = cinfo->restart_interval;
  1297. }
  1298. /*
  1299. * Module initialization routine for Huffman entropy decoding.
  1300. */
  1301. GLOBAL(void)
  1302. jinit_huff_decoder (j_decompress_ptr cinfo)
  1303. {
  1304. huff_entropy_ptr entropy;
  1305. int i;
  1306. entropy = (huff_entropy_ptr) (*cinfo->mem->alloc_small)
  1307. ((j_common_ptr) cinfo, JPOOL_IMAGE, SIZEOF(huff_entropy_decoder));
  1308. cinfo->entropy = &entropy->pub;
  1309. entropy->pub.start_pass = start_pass_huff_decoder;
  1310. entropy->pub.finish_pass = finish_pass_huff;
  1311. if (cinfo->progressive_mode) {
  1312. /* Create progression status table */
  1313. int *coef_bit_ptr, ci;
  1314. cinfo->coef_bits = (int (*)[DCTSIZE2]) (*cinfo->mem->alloc_small)
  1315. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1316. cinfo->num_components * DCTSIZE2 * SIZEOF(int));
  1317. coef_bit_ptr = & cinfo->coef_bits[0][0];
  1318. for (ci = 0; ci < cinfo->num_components; ci++)
  1319. for (i = 0; i < DCTSIZE2; i++)
  1320. *coef_bit_ptr++ = -1;
  1321. /* Mark derived tables unallocated */
  1322. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1323. entropy->derived_tbls[i] = NULL;
  1324. }
  1325. } else {
  1326. /* Mark derived tables unallocated */
  1327. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1328. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  1329. }
  1330. }
  1331. }