jchuff.c 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574
  1. /*
  2. * jchuff.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 encoding 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 output suspension.
  13. * If the data destination module demands suspension, we want to be able to
  14. * back up to the start of the current MCU. To do this, we copy state
  15. * variables into local working storage, and update them back to the
  16. * permanent JPEG objects only upon successful completion of an MCU.
  17. *
  18. * We do not support output suspension for the progressive JPEG mode, since
  19. * the library currently does not allow multiple-scan files to be written
  20. * with output suspension.
  21. */
  22. #define JPEG_INTERNALS
  23. #include "jinclude.h"
  24. #include "jpeglib.h"
  25. /* The legal range of a DCT coefficient is
  26. * -1024 .. +1023 for 8-bit data;
  27. * -16384 .. +16383 for 12-bit data.
  28. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  29. */
  30. #if BITS_IN_JSAMPLE == 8
  31. #define MAX_COEF_BITS 10
  32. #else
  33. #define MAX_COEF_BITS 14
  34. #endif
  35. /* Derived data constructed for each Huffman table */
  36. typedef struct {
  37. unsigned int ehufco[256]; /* code for each symbol */
  38. char ehufsi[256]; /* length of code for each symbol */
  39. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  40. } c_derived_tbl;
  41. /* Expanded entropy encoder object for Huffman encoding.
  42. *
  43. * The savable_state subrecord contains fields that change within an MCU,
  44. * but must not be updated permanently until we complete the MCU.
  45. */
  46. typedef struct {
  47. INT32 put_buffer; /* current bit-accumulation buffer */
  48. int put_bits; /* # of bits now in it */
  49. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  50. } savable_state;
  51. /* This macro is to work around compilers with missing or broken
  52. * structure assignment. You'll need to fix this code if you have
  53. * such a compiler and you change MAX_COMPS_IN_SCAN.
  54. */
  55. #ifndef NO_STRUCT_ASSIGN
  56. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  57. #else
  58. #if MAX_COMPS_IN_SCAN == 4
  59. #define ASSIGN_STATE(dest,src) \
  60. ((dest).put_buffer = (src).put_buffer, \
  61. (dest).put_bits = (src).put_bits, \
  62. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  63. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  64. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  65. (dest).last_dc_val[3] = (src).last_dc_val[3])
  66. #endif
  67. #endif
  68. typedef struct {
  69. struct jpeg_entropy_encoder pub; /* public fields */
  70. savable_state saved; /* Bit buffer & DC state at start of MCU */
  71. /* These fields are NOT loaded into local working state. */
  72. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  73. int next_restart_num; /* next restart number to write (0-7) */
  74. /* Pointers to derived tables (these workspaces have image lifespan) */
  75. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  76. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  77. /* Statistics tables for optimization */
  78. long * dc_count_ptrs[NUM_HUFF_TBLS];
  79. long * ac_count_ptrs[NUM_HUFF_TBLS];
  80. /* Following fields used only in progressive mode */
  81. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  82. boolean gather_statistics;
  83. /* next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  84. */
  85. JOCTET * next_output_byte; /* => next byte to write in buffer */
  86. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  87. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  88. /* Coding status for AC components */
  89. int ac_tbl_no; /* the table number of the single component */
  90. unsigned int EOBRUN; /* run length of EOBs */
  91. unsigned int BE; /* # of buffered correction bits before MCU */
  92. char * bit_buffer; /* buffer for correction bits (1 per char) */
  93. /* packing correction bits tightly would save some space but cost time... */
  94. } huff_entropy_encoder;
  95. typedef huff_entropy_encoder * huff_entropy_ptr;
  96. /* Working state while writing an MCU (sequential mode).
  97. * This struct contains all the fields that are needed by subroutines.
  98. */
  99. typedef struct {
  100. JOCTET * next_output_byte; /* => next byte to write in buffer */
  101. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  102. savable_state cur; /* Current bit buffer & DC state */
  103. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  104. } working_state;
  105. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  106. * buffer can hold. Larger sizes may slightly improve compression, but
  107. * 1000 is already well into the realm of overkill.
  108. * The minimum safe size is 64 bits.
  109. */
  110. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  111. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  112. * We assume that int right shift is unsigned if INT32 right shift is,
  113. * which should be safe.
  114. */
  115. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  116. #define ISHIFT_TEMPS int ishift_temp;
  117. #define IRIGHT_SHIFT(x,shft) \
  118. ((ishift_temp = (x)) < 0 ? \
  119. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  120. (ishift_temp >> (shft)))
  121. #else
  122. #define ISHIFT_TEMPS
  123. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  124. #endif
  125. /*
  126. * Compute the derived values for a Huffman table.
  127. * This routine also performs some validation checks on the table.
  128. */
  129. LOCAL(void)
  130. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  131. c_derived_tbl ** pdtbl)
  132. {
  133. JHUFF_TBL *htbl;
  134. c_derived_tbl *dtbl;
  135. int p, i, l, lastp, si, maxsymbol;
  136. char huffsize[257];
  137. unsigned int huffcode[257];
  138. unsigned int code;
  139. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  140. * paralleling the order of the symbols themselves in htbl->huffval[].
  141. */
  142. /* Find the input Huffman table */
  143. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  144. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  145. htbl =
  146. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  147. if (htbl == NULL)
  148. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  149. /* Allocate a workspace if we haven't already done so. */
  150. if (*pdtbl == NULL)
  151. *pdtbl = (c_derived_tbl *)
  152. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  153. SIZEOF(c_derived_tbl));
  154. dtbl = *pdtbl;
  155. /* Figure C.1: make table of Huffman code length for each symbol */
  156. p = 0;
  157. for (l = 1; l <= 16; l++) {
  158. i = (int) htbl->bits[l];
  159. if (i < 0 || p + i > 256) /* protect against table overrun */
  160. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  161. while (i--)
  162. huffsize[p++] = (char) l;
  163. }
  164. huffsize[p] = 0;
  165. lastp = p;
  166. /* Figure C.2: generate the codes themselves */
  167. /* We also validate that the counts represent a legal Huffman code tree. */
  168. code = 0;
  169. si = huffsize[0];
  170. p = 0;
  171. while (huffsize[p]) {
  172. while (((int) huffsize[p]) == si) {
  173. huffcode[p++] = code;
  174. code++;
  175. }
  176. /* code is now 1 more than the last code used for codelength si; but
  177. * it must still fit in si bits, since no code is allowed to be all ones.
  178. */
  179. if (((INT32) code) >= (((INT32) 1) << si))
  180. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  181. code <<= 1;
  182. si++;
  183. }
  184. /* Figure C.3: generate encoding tables */
  185. /* These are code and size indexed by symbol value */
  186. /* Set all codeless symbols to have code length 0;
  187. * this lets us detect duplicate VAL entries here, and later
  188. * allows emit_bits to detect any attempt to emit such symbols.
  189. */
  190. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  191. /* This is also a convenient place to check for out-of-range
  192. * and duplicated VAL entries. We allow 0..255 for AC symbols
  193. * but only 0..15 for DC. (We could constrain them further
  194. * based on data depth and mode, but this seems enough.)
  195. */
  196. maxsymbol = isDC ? 15 : 255;
  197. for (p = 0; p < lastp; p++) {
  198. i = htbl->huffval[p];
  199. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  200. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  201. dtbl->ehufco[i] = huffcode[p];
  202. dtbl->ehufsi[i] = huffsize[p];
  203. }
  204. }
  205. /* Outputting bytes to the file.
  206. * NB: these must be called only when actually outputting,
  207. * that is, entropy->gather_statistics == FALSE.
  208. */
  209. /* Emit a byte, taking 'action' if must suspend. */
  210. #define emit_byte_s(state,val,action) \
  211. { *(state)->next_output_byte++ = (JOCTET) (val); \
  212. if (--(state)->free_in_buffer == 0) \
  213. if (! dump_buffer_s(state)) \
  214. { action; } }
  215. /* Emit a byte */
  216. #define emit_byte_e(entropy,val) \
  217. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  218. if (--(entropy)->free_in_buffer == 0) \
  219. dump_buffer_e(entropy); }
  220. LOCAL(boolean)
  221. dump_buffer_s (working_state * state)
  222. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  223. {
  224. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  225. if (! (*dest->empty_output_buffer) (state->cinfo))
  226. return FALSE;
  227. /* After a successful buffer dump, must reset buffer pointers */
  228. state->next_output_byte = dest->next_output_byte;
  229. state->free_in_buffer = dest->free_in_buffer;
  230. return TRUE;
  231. }
  232. LOCAL(void)
  233. dump_buffer_e (huff_entropy_ptr entropy)
  234. /* Empty the output buffer; we do not support suspension in this case. */
  235. {
  236. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  237. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  238. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  239. /* After a successful buffer dump, must reset buffer pointers */
  240. entropy->next_output_byte = dest->next_output_byte;
  241. entropy->free_in_buffer = dest->free_in_buffer;
  242. }
  243. /* Outputting bits to the file */
  244. /* Only the right 24 bits of put_buffer are used; the valid bits are
  245. * left-justified in this part. At most 16 bits can be passed to emit_bits
  246. * in one call, and we never retain more than 7 bits in put_buffer
  247. * between calls, so 24 bits are sufficient.
  248. */
  249. INLINE
  250. LOCAL(boolean)
  251. emit_bits_s (working_state * state, unsigned int code, int size)
  252. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  253. {
  254. /* This routine is heavily used, so it's worth coding tightly. */
  255. register INT32 put_buffer;
  256. register int put_bits;
  257. /* if size is 0, caller used an invalid Huffman table entry */
  258. if (size == 0)
  259. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  260. /* mask off any extra bits in code */
  261. put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);
  262. /* new number of bits in buffer */
  263. put_bits = size + state->cur.put_bits;
  264. put_buffer <<= 24 - put_bits; /* align incoming bits */
  265. /* and merge with old buffer contents */
  266. put_buffer |= state->cur.put_buffer;
  267. while (put_bits >= 8) {
  268. int c = (int) ((put_buffer >> 16) & 0xFF);
  269. emit_byte_s(state, c, return FALSE);
  270. if (c == 0xFF) { /* need to stuff a zero byte? */
  271. emit_byte_s(state, 0, return FALSE);
  272. }
  273. put_buffer <<= 8;
  274. put_bits -= 8;
  275. }
  276. state->cur.put_buffer = put_buffer; /* update state variables */
  277. state->cur.put_bits = put_bits;
  278. return TRUE;
  279. }
  280. INLINE
  281. LOCAL(void)
  282. emit_bits_e (huff_entropy_ptr entropy, unsigned int code, int size)
  283. /* Emit some bits, unless we are in gather mode */
  284. {
  285. /* This routine is heavily used, so it's worth coding tightly. */
  286. register INT32 put_buffer;
  287. register int put_bits;
  288. /* if size is 0, caller used an invalid Huffman table entry */
  289. if (size == 0)
  290. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  291. if (entropy->gather_statistics)
  292. return; /* do nothing if we're only getting stats */
  293. /* mask off any extra bits in code */
  294. put_buffer = ((INT32) code) & ((((INT32) 1) << size) - 1);
  295. /* new number of bits in buffer */
  296. put_bits = size + entropy->saved.put_bits;
  297. put_buffer <<= 24 - put_bits; /* align incoming bits */
  298. /* and merge with old buffer contents */
  299. put_buffer |= entropy->saved.put_buffer;
  300. while (put_bits >= 8) {
  301. int c = (int) ((put_buffer >> 16) & 0xFF);
  302. emit_byte_e(entropy, c);
  303. if (c == 0xFF) { /* need to stuff a zero byte? */
  304. emit_byte_e(entropy, 0);
  305. }
  306. put_buffer <<= 8;
  307. put_bits -= 8;
  308. }
  309. entropy->saved.put_buffer = put_buffer; /* update variables */
  310. entropy->saved.put_bits = put_bits;
  311. }
  312. LOCAL(boolean)
  313. flush_bits_s (working_state * state)
  314. {
  315. if (! emit_bits_s(state, 0x7F, 7)) /* fill any partial byte with ones */
  316. return FALSE;
  317. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  318. state->cur.put_bits = 0;
  319. return TRUE;
  320. }
  321. LOCAL(void)
  322. flush_bits_e (huff_entropy_ptr entropy)
  323. {
  324. emit_bits_e(entropy, 0x7F, 7); /* fill any partial byte with ones */
  325. entropy->saved.put_buffer = 0; /* and reset bit-buffer to empty */
  326. entropy->saved.put_bits = 0;
  327. }
  328. /*
  329. * Emit (or just count) a Huffman symbol.
  330. */
  331. INLINE
  332. LOCAL(void)
  333. emit_dc_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
  334. {
  335. if (entropy->gather_statistics)
  336. entropy->dc_count_ptrs[tbl_no][symbol]++;
  337. else {
  338. c_derived_tbl * tbl = entropy->dc_derived_tbls[tbl_no];
  339. emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  340. }
  341. }
  342. INLINE
  343. LOCAL(void)
  344. emit_ac_symbol (huff_entropy_ptr entropy, int tbl_no, int symbol)
  345. {
  346. if (entropy->gather_statistics)
  347. entropy->ac_count_ptrs[tbl_no][symbol]++;
  348. else {
  349. c_derived_tbl * tbl = entropy->ac_derived_tbls[tbl_no];
  350. emit_bits_e(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  351. }
  352. }
  353. /*
  354. * Emit bits from a correction bit buffer.
  355. */
  356. LOCAL(void)
  357. emit_buffered_bits (huff_entropy_ptr entropy, char * bufstart,
  358. unsigned int nbits)
  359. {
  360. if (entropy->gather_statistics)
  361. return; /* no real work */
  362. while (nbits > 0) {
  363. emit_bits_e(entropy, (unsigned int) (*bufstart), 1);
  364. bufstart++;
  365. nbits--;
  366. }
  367. }
  368. /*
  369. * Emit any pending EOBRUN symbol.
  370. */
  371. LOCAL(void)
  372. emit_eobrun (huff_entropy_ptr entropy)
  373. {
  374. register int temp, nbits;
  375. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  376. temp = entropy->EOBRUN;
  377. nbits = 0;
  378. while ((temp >>= 1))
  379. nbits++;
  380. /* safety check: shouldn't happen given limited correction-bit buffer */
  381. if (nbits > 14)
  382. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  383. emit_ac_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  384. if (nbits)
  385. emit_bits_e(entropy, entropy->EOBRUN, nbits);
  386. entropy->EOBRUN = 0;
  387. /* Emit any buffered correction bits */
  388. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  389. entropy->BE = 0;
  390. }
  391. }
  392. /*
  393. * Emit a restart marker & resynchronize predictions.
  394. */
  395. LOCAL(boolean)
  396. emit_restart_s (working_state * state, int restart_num)
  397. {
  398. int ci;
  399. if (! flush_bits_s(state))
  400. return FALSE;
  401. emit_byte_s(state, 0xFF, return FALSE);
  402. emit_byte_s(state, JPEG_RST0 + restart_num, return FALSE);
  403. /* Re-initialize DC predictions to 0 */
  404. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  405. state->cur.last_dc_val[ci] = 0;
  406. /* The restart counter is not updated until we successfully write the MCU. */
  407. return TRUE;
  408. }
  409. LOCAL(void)
  410. emit_restart_e (huff_entropy_ptr entropy, int restart_num)
  411. {
  412. int ci;
  413. emit_eobrun(entropy);
  414. if (! entropy->gather_statistics) {
  415. flush_bits_e(entropy);
  416. emit_byte_e(entropy, 0xFF);
  417. emit_byte_e(entropy, JPEG_RST0 + restart_num);
  418. }
  419. if (entropy->cinfo->Ss == 0) {
  420. /* Re-initialize DC predictions to 0 */
  421. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  422. entropy->saved.last_dc_val[ci] = 0;
  423. } else {
  424. /* Re-initialize all AC-related fields to 0 */
  425. entropy->EOBRUN = 0;
  426. entropy->BE = 0;
  427. }
  428. }
  429. /*
  430. * MCU encoding for DC initial scan (either spectral selection,
  431. * or first pass of successive approximation).
  432. */
  433. METHODDEF(boolean)
  434. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  435. {
  436. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  437. register int temp, temp2;
  438. register int nbits;
  439. int blkn, ci, tbl;
  440. ISHIFT_TEMPS
  441. entropy->next_output_byte = cinfo->dest->next_output_byte;
  442. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  443. /* Emit restart marker if needed */
  444. if (cinfo->restart_interval)
  445. if (entropy->restarts_to_go == 0)
  446. emit_restart_e(entropy, entropy->next_restart_num);
  447. /* Encode the MCU data blocks */
  448. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  449. ci = cinfo->MCU_membership[blkn];
  450. tbl = cinfo->cur_comp_info[ci]->dc_tbl_no;
  451. /* Compute the DC value after the required point transform by Al.
  452. * This is simply an arithmetic right shift.
  453. */
  454. temp = IRIGHT_SHIFT((int) (MCU_data[blkn][0][0]), cinfo->Al);
  455. /* DC differences are figured on the point-transformed values. */
  456. temp2 = temp - entropy->saved.last_dc_val[ci];
  457. entropy->saved.last_dc_val[ci] = temp;
  458. /* Encode the DC coefficient difference per section G.1.2.1 */
  459. temp = temp2;
  460. if (temp < 0) {
  461. temp = -temp; /* temp is abs value of input */
  462. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  463. /* This code assumes we are on a two's complement machine */
  464. temp2--;
  465. }
  466. /* Find the number of bits needed for the magnitude of the coefficient */
  467. nbits = 0;
  468. while (temp) {
  469. nbits++;
  470. temp >>= 1;
  471. }
  472. /* Check for out-of-range coefficient values.
  473. * Since we're encoding a difference, the range limit is twice as much.
  474. */
  475. if (nbits > MAX_COEF_BITS+1)
  476. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  477. /* Count/emit the Huffman-coded symbol for the number of bits */
  478. emit_dc_symbol(entropy, tbl, nbits);
  479. /* Emit that number of bits of the value, if positive, */
  480. /* or the complement of its magnitude, if negative. */
  481. if (nbits) /* emit_bits rejects calls with size 0 */
  482. emit_bits_e(entropy, (unsigned int) temp2, nbits);
  483. }
  484. cinfo->dest->next_output_byte = entropy->next_output_byte;
  485. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  486. /* Update restart-interval state too */
  487. if (cinfo->restart_interval) {
  488. if (entropy->restarts_to_go == 0) {
  489. entropy->restarts_to_go = cinfo->restart_interval;
  490. entropy->next_restart_num++;
  491. entropy->next_restart_num &= 7;
  492. }
  493. entropy->restarts_to_go--;
  494. }
  495. return TRUE;
  496. }
  497. /*
  498. * MCU encoding for AC initial scan (either spectral selection,
  499. * or first pass of successive approximation).
  500. */
  501. METHODDEF(boolean)
  502. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  503. {
  504. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  505. const int * natural_order;
  506. JBLOCKROW block;
  507. register int temp, temp2;
  508. register int nbits;
  509. register int r, k;
  510. int Se, Al;
  511. entropy->next_output_byte = cinfo->dest->next_output_byte;
  512. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  513. /* Emit restart marker if needed */
  514. if (cinfo->restart_interval)
  515. if (entropy->restarts_to_go == 0)
  516. emit_restart_e(entropy, entropy->next_restart_num);
  517. Se = cinfo->Se;
  518. Al = cinfo->Al;
  519. natural_order = cinfo->natural_order;
  520. /* Encode the MCU data block */
  521. block = MCU_data[0];
  522. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  523. r = 0; /* r = run length of zeros */
  524. for (k = cinfo->Ss; k <= Se; k++) {
  525. if ((temp = (*block)[natural_order[k]]) == 0) {
  526. r++;
  527. continue;
  528. }
  529. /* We must apply the point transform by Al. For AC coefficients this
  530. * is an integer division with rounding towards 0. To do this portably
  531. * in C, we shift after obtaining the absolute value; so the code is
  532. * interwoven with finding the abs value (temp) and output bits (temp2).
  533. */
  534. if (temp < 0) {
  535. temp = -temp; /* temp is abs value of input */
  536. temp >>= Al; /* apply the point transform */
  537. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  538. temp2 = ~temp;
  539. } else {
  540. temp >>= Al; /* apply the point transform */
  541. temp2 = temp;
  542. }
  543. /* Watch out for case that nonzero coef is zero after point transform */
  544. if (temp == 0) {
  545. r++;
  546. continue;
  547. }
  548. /* Emit any pending EOBRUN */
  549. if (entropy->EOBRUN > 0)
  550. emit_eobrun(entropy);
  551. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  552. while (r > 15) {
  553. emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  554. r -= 16;
  555. }
  556. /* Find the number of bits needed for the magnitude of the coefficient */
  557. nbits = 1; /* there must be at least one 1 bit */
  558. while ((temp >>= 1))
  559. nbits++;
  560. /* Check for out-of-range coefficient values */
  561. if (nbits > MAX_COEF_BITS)
  562. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  563. /* Count/emit Huffman symbol for run length / number of bits */
  564. emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  565. /* Emit that number of bits of the value, if positive, */
  566. /* or the complement of its magnitude, if negative. */
  567. emit_bits_e(entropy, (unsigned int) temp2, nbits);
  568. r = 0; /* reset zero run length */
  569. }
  570. if (r > 0) { /* If there are trailing zeroes, */
  571. entropy->EOBRUN++; /* count an EOB */
  572. if (entropy->EOBRUN == 0x7FFF)
  573. emit_eobrun(entropy); /* force it out to avoid overflow */
  574. }
  575. cinfo->dest->next_output_byte = entropy->next_output_byte;
  576. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  577. /* Update restart-interval state too */
  578. if (cinfo->restart_interval) {
  579. if (entropy->restarts_to_go == 0) {
  580. entropy->restarts_to_go = cinfo->restart_interval;
  581. entropy->next_restart_num++;
  582. entropy->next_restart_num &= 7;
  583. }
  584. entropy->restarts_to_go--;
  585. }
  586. return TRUE;
  587. }
  588. /*
  589. * MCU encoding for DC successive approximation refinement scan.
  590. * Note: we assume such scans can be multi-component,
  591. * although the spec is not very clear on the point.
  592. */
  593. METHODDEF(boolean)
  594. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  595. {
  596. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  597. int Al, blkn;
  598. entropy->next_output_byte = cinfo->dest->next_output_byte;
  599. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  600. /* Emit restart marker if needed */
  601. if (cinfo->restart_interval)
  602. if (entropy->restarts_to_go == 0)
  603. emit_restart_e(entropy, entropy->next_restart_num);
  604. Al = cinfo->Al;
  605. /* Encode the MCU data blocks */
  606. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  607. /* We simply emit the Al'th bit of the DC coefficient value. */
  608. emit_bits_e(entropy, (unsigned int) (MCU_data[blkn][0][0] >> Al), 1);
  609. }
  610. cinfo->dest->next_output_byte = entropy->next_output_byte;
  611. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  612. /* Update restart-interval state too */
  613. if (cinfo->restart_interval) {
  614. if (entropy->restarts_to_go == 0) {
  615. entropy->restarts_to_go = cinfo->restart_interval;
  616. entropy->next_restart_num++;
  617. entropy->next_restart_num &= 7;
  618. }
  619. entropy->restarts_to_go--;
  620. }
  621. return TRUE;
  622. }
  623. /*
  624. * MCU encoding for AC successive approximation refinement scan.
  625. */
  626. METHODDEF(boolean)
  627. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  628. {
  629. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  630. const int * natural_order;
  631. JBLOCKROW block;
  632. register int temp;
  633. register int r, k;
  634. int Se, Al;
  635. int EOB;
  636. char *BR_buffer;
  637. unsigned int BR;
  638. int absvalues[DCTSIZE2];
  639. entropy->next_output_byte = cinfo->dest->next_output_byte;
  640. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  641. /* Emit restart marker if needed */
  642. if (cinfo->restart_interval)
  643. if (entropy->restarts_to_go == 0)
  644. emit_restart_e(entropy, entropy->next_restart_num);
  645. Se = cinfo->Se;
  646. Al = cinfo->Al;
  647. natural_order = cinfo->natural_order;
  648. /* Encode the MCU data block */
  649. block = MCU_data[0];
  650. /* It is convenient to make a pre-pass to determine the transformed
  651. * coefficients' absolute values and the EOB position.
  652. */
  653. EOB = 0;
  654. for (k = cinfo->Ss; k <= Se; k++) {
  655. temp = (*block)[natural_order[k]];
  656. /* We must apply the point transform by Al. For AC coefficients this
  657. * is an integer division with rounding towards 0. To do this portably
  658. * in C, we shift after obtaining the absolute value.
  659. */
  660. if (temp < 0)
  661. temp = -temp; /* temp is abs value of input */
  662. temp >>= Al; /* apply the point transform */
  663. absvalues[k] = temp; /* save abs value for main pass */
  664. if (temp == 1)
  665. EOB = k; /* EOB = index of last newly-nonzero coef */
  666. }
  667. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  668. r = 0; /* r = run length of zeros */
  669. BR = 0; /* BR = count of buffered bits added now */
  670. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  671. for (k = cinfo->Ss; k <= Se; k++) {
  672. if ((temp = absvalues[k]) == 0) {
  673. r++;
  674. continue;
  675. }
  676. /* Emit any required ZRLs, but not if they can be folded into EOB */
  677. while (r > 15 && k <= EOB) {
  678. /* emit any pending EOBRUN and the BE correction bits */
  679. emit_eobrun(entropy);
  680. /* Emit ZRL */
  681. emit_ac_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  682. r -= 16;
  683. /* Emit buffered correction bits that must be associated with ZRL */
  684. emit_buffered_bits(entropy, BR_buffer, BR);
  685. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  686. BR = 0;
  687. }
  688. /* If the coef was previously nonzero, it only needs a correction bit.
  689. * NOTE: a straight translation of the spec's figure G.7 would suggest
  690. * that we also need to test r > 15. But if r > 15, we can only get here
  691. * if k > EOB, which implies that this coefficient is not 1.
  692. */
  693. if (temp > 1) {
  694. /* The correction bit is the next bit of the absolute value. */
  695. BR_buffer[BR++] = (char) (temp & 1);
  696. continue;
  697. }
  698. /* Emit any pending EOBRUN and the BE correction bits */
  699. emit_eobrun(entropy);
  700. /* Count/emit Huffman symbol for run length / number of bits */
  701. emit_ac_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  702. /* Emit output bit for newly-nonzero coef */
  703. temp = ((*block)[natural_order[k]] < 0) ? 0 : 1;
  704. emit_bits_e(entropy, (unsigned int) temp, 1);
  705. /* Emit buffered correction bits that must be associated with this code */
  706. emit_buffered_bits(entropy, BR_buffer, BR);
  707. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  708. BR = 0;
  709. r = 0; /* reset zero run length */
  710. }
  711. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  712. entropy->EOBRUN++; /* count an EOB */
  713. entropy->BE += BR; /* concat my correction bits to older ones */
  714. /* We force out the EOB if we risk either:
  715. * 1. overflow of the EOB counter;
  716. * 2. overflow of the correction bit buffer during the next MCU.
  717. */
  718. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  719. emit_eobrun(entropy);
  720. }
  721. cinfo->dest->next_output_byte = entropy->next_output_byte;
  722. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  723. /* Update restart-interval state too */
  724. if (cinfo->restart_interval) {
  725. if (entropy->restarts_to_go == 0) {
  726. entropy->restarts_to_go = cinfo->restart_interval;
  727. entropy->next_restart_num++;
  728. entropy->next_restart_num &= 7;
  729. }
  730. entropy->restarts_to_go--;
  731. }
  732. return TRUE;
  733. }
  734. /* Encode a single block's worth of coefficients */
  735. LOCAL(boolean)
  736. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  737. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  738. {
  739. register int temp, temp2;
  740. register int nbits;
  741. register int r, k;
  742. int Se = state->cinfo->lim_Se;
  743. const int * natural_order = state->cinfo->natural_order;
  744. /* Encode the DC coefficient difference per section F.1.2.1 */
  745. temp = temp2 = block[0] - last_dc_val;
  746. if (temp < 0) {
  747. temp = -temp; /* temp is abs value of input */
  748. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  749. /* This code assumes we are on a two's complement machine */
  750. temp2--;
  751. }
  752. /* Find the number of bits needed for the magnitude of the coefficient */
  753. nbits = 0;
  754. while (temp) {
  755. nbits++;
  756. temp >>= 1;
  757. }
  758. /* Check for out-of-range coefficient values.
  759. * Since we're encoding a difference, the range limit is twice as much.
  760. */
  761. if (nbits > MAX_COEF_BITS+1)
  762. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  763. /* Emit the Huffman-coded symbol for the number of bits */
  764. if (! emit_bits_s(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  765. return FALSE;
  766. /* Emit that number of bits of the value, if positive, */
  767. /* or the complement of its magnitude, if negative. */
  768. if (nbits) /* emit_bits rejects calls with size 0 */
  769. if (! emit_bits_s(state, (unsigned int) temp2, nbits))
  770. return FALSE;
  771. /* Encode the AC coefficients per section F.1.2.2 */
  772. r = 0; /* r = run length of zeros */
  773. for (k = 1; k <= Se; k++) {
  774. if ((temp2 = block[natural_order[k]]) == 0) {
  775. r++;
  776. } else {
  777. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  778. while (r > 15) {
  779. if (! emit_bits_s(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  780. return FALSE;
  781. r -= 16;
  782. }
  783. temp = temp2;
  784. if (temp < 0) {
  785. temp = -temp; /* temp is abs value of input */
  786. /* This code assumes we are on a two's complement machine */
  787. temp2--;
  788. }
  789. /* Find the number of bits needed for the magnitude of the coefficient */
  790. nbits = 1; /* there must be at least one 1 bit */
  791. while ((temp >>= 1))
  792. nbits++;
  793. /* Check for out-of-range coefficient values */
  794. if (nbits > MAX_COEF_BITS)
  795. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  796. /* Emit Huffman symbol for run length / number of bits */
  797. temp = (r << 4) + nbits;
  798. if (! emit_bits_s(state, actbl->ehufco[temp], actbl->ehufsi[temp]))
  799. return FALSE;
  800. /* Emit that number of bits of the value, if positive, */
  801. /* or the complement of its magnitude, if negative. */
  802. if (! emit_bits_s(state, (unsigned int) temp2, nbits))
  803. return FALSE;
  804. r = 0;
  805. }
  806. }
  807. /* If the last coef(s) were zero, emit an end-of-block code */
  808. if (r > 0)
  809. if (! emit_bits_s(state, actbl->ehufco[0], actbl->ehufsi[0]))
  810. return FALSE;
  811. return TRUE;
  812. }
  813. /*
  814. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  815. */
  816. METHODDEF(boolean)
  817. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  818. {
  819. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  820. working_state state;
  821. int blkn, ci;
  822. jpeg_component_info * compptr;
  823. /* Load up working state */
  824. state.next_output_byte = cinfo->dest->next_output_byte;
  825. state.free_in_buffer = cinfo->dest->free_in_buffer;
  826. ASSIGN_STATE(state.cur, entropy->saved);
  827. state.cinfo = cinfo;
  828. /* Emit restart marker if needed */
  829. if (cinfo->restart_interval) {
  830. if (entropy->restarts_to_go == 0)
  831. if (! emit_restart_s(&state, entropy->next_restart_num))
  832. return FALSE;
  833. }
  834. /* Encode the MCU data blocks */
  835. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  836. ci = cinfo->MCU_membership[blkn];
  837. compptr = cinfo->cur_comp_info[ci];
  838. if (! encode_one_block(&state,
  839. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  840. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  841. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  842. return FALSE;
  843. /* Update last_dc_val */
  844. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  845. }
  846. /* Completed MCU, so update state */
  847. cinfo->dest->next_output_byte = state.next_output_byte;
  848. cinfo->dest->free_in_buffer = state.free_in_buffer;
  849. ASSIGN_STATE(entropy->saved, state.cur);
  850. /* Update restart-interval state too */
  851. if (cinfo->restart_interval) {
  852. if (entropy->restarts_to_go == 0) {
  853. entropy->restarts_to_go = cinfo->restart_interval;
  854. entropy->next_restart_num++;
  855. entropy->next_restart_num &= 7;
  856. }
  857. entropy->restarts_to_go--;
  858. }
  859. return TRUE;
  860. }
  861. /*
  862. * Finish up at the end of a Huffman-compressed scan.
  863. */
  864. METHODDEF(void)
  865. finish_pass_huff (j_compress_ptr cinfo)
  866. {
  867. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  868. working_state state;
  869. if (cinfo->progressive_mode) {
  870. entropy->next_output_byte = cinfo->dest->next_output_byte;
  871. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  872. /* Flush out any buffered data */
  873. emit_eobrun(entropy);
  874. flush_bits_e(entropy);
  875. cinfo->dest->next_output_byte = entropy->next_output_byte;
  876. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  877. } else {
  878. /* Load up working state ... flush_bits needs it */
  879. state.next_output_byte = cinfo->dest->next_output_byte;
  880. state.free_in_buffer = cinfo->dest->free_in_buffer;
  881. ASSIGN_STATE(state.cur, entropy->saved);
  882. state.cinfo = cinfo;
  883. /* Flush out the last data */
  884. if (! flush_bits_s(&state))
  885. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  886. /* Update state */
  887. cinfo->dest->next_output_byte = state.next_output_byte;
  888. cinfo->dest->free_in_buffer = state.free_in_buffer;
  889. ASSIGN_STATE(entropy->saved, state.cur);
  890. }
  891. }
  892. /*
  893. * Huffman coding optimization.
  894. *
  895. * We first scan the supplied data and count the number of uses of each symbol
  896. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  897. * Then we build a Huffman coding tree for the observed counts.
  898. * Symbols which are not needed at all for the particular image are not
  899. * assigned any code, which saves space in the DHT marker as well as in
  900. * the compressed data.
  901. */
  902. /* Process a single block's worth of coefficients */
  903. LOCAL(void)
  904. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  905. long dc_counts[], long ac_counts[])
  906. {
  907. register int temp;
  908. register int nbits;
  909. register int r, k;
  910. int Se = cinfo->lim_Se;
  911. const int * natural_order = cinfo->natural_order;
  912. /* Encode the DC coefficient difference per section F.1.2.1 */
  913. temp = block[0] - last_dc_val;
  914. if (temp < 0)
  915. temp = -temp;
  916. /* Find the number of bits needed for the magnitude of the coefficient */
  917. nbits = 0;
  918. while (temp) {
  919. nbits++;
  920. temp >>= 1;
  921. }
  922. /* Check for out-of-range coefficient values.
  923. * Since we're encoding a difference, the range limit is twice as much.
  924. */
  925. if (nbits > MAX_COEF_BITS+1)
  926. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  927. /* Count the Huffman symbol for the number of bits */
  928. dc_counts[nbits]++;
  929. /* Encode the AC coefficients per section F.1.2.2 */
  930. r = 0; /* r = run length of zeros */
  931. for (k = 1; k <= Se; k++) {
  932. if ((temp = block[natural_order[k]]) == 0) {
  933. r++;
  934. } else {
  935. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  936. while (r > 15) {
  937. ac_counts[0xF0]++;
  938. r -= 16;
  939. }
  940. /* Find the number of bits needed for the magnitude of the coefficient */
  941. if (temp < 0)
  942. temp = -temp;
  943. /* Find the number of bits needed for the magnitude of the coefficient */
  944. nbits = 1; /* there must be at least one 1 bit */
  945. while ((temp >>= 1))
  946. nbits++;
  947. /* Check for out-of-range coefficient values */
  948. if (nbits > MAX_COEF_BITS)
  949. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  950. /* Count Huffman symbol for run length / number of bits */
  951. ac_counts[(r << 4) + nbits]++;
  952. r = 0;
  953. }
  954. }
  955. /* If the last coef(s) were zero, emit an end-of-block code */
  956. if (r > 0)
  957. ac_counts[0]++;
  958. }
  959. /*
  960. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  961. * No data is actually output, so no suspension return is possible.
  962. */
  963. METHODDEF(boolean)
  964. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  965. {
  966. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  967. int blkn, ci;
  968. jpeg_component_info * compptr;
  969. /* Take care of restart intervals if needed */
  970. if (cinfo->restart_interval) {
  971. if (entropy->restarts_to_go == 0) {
  972. /* Re-initialize DC predictions to 0 */
  973. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  974. entropy->saved.last_dc_val[ci] = 0;
  975. /* Update restart state */
  976. entropy->restarts_to_go = cinfo->restart_interval;
  977. }
  978. entropy->restarts_to_go--;
  979. }
  980. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  981. ci = cinfo->MCU_membership[blkn];
  982. compptr = cinfo->cur_comp_info[ci];
  983. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  984. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  985. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  986. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  987. }
  988. return TRUE;
  989. }
  990. /*
  991. * Generate the best Huffman code table for the given counts, fill htbl.
  992. *
  993. * The JPEG standard requires that no symbol be assigned a codeword of all
  994. * one bits (so that padding bits added at the end of a compressed segment
  995. * can't look like a valid code). Because of the canonical ordering of
  996. * codewords, this just means that there must be an unused slot in the
  997. * longest codeword length category. Section K.2 of the JPEG spec suggests
  998. * reserving such a slot by pretending that symbol 256 is a valid symbol
  999. * with count 1. In theory that's not optimal; giving it count zero but
  1000. * including it in the symbol set anyway should give a better Huffman code.
  1001. * But the theoretically better code actually seems to come out worse in
  1002. * practice, because it produces more all-ones bytes (which incur stuffed
  1003. * zero bytes in the final file). In any case the difference is tiny.
  1004. *
  1005. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  1006. * If some symbols have a very small but nonzero probability, the Huffman tree
  1007. * must be adjusted to meet the code length restriction. We currently use
  1008. * the adjustment method suggested in JPEG section K.2. This method is *not*
  1009. * optimal; it may not choose the best possible limited-length code. But
  1010. * typically only very-low-frequency symbols will be given less-than-optimal
  1011. * lengths, so the code is almost optimal. Experimental comparisons against
  1012. * an optimal limited-length-code algorithm indicate that the difference is
  1013. * microscopic --- usually less than a hundredth of a percent of total size.
  1014. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  1015. */
  1016. LOCAL(void)
  1017. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  1018. {
  1019. #define MAX_CLEN 32 /* assumed maximum initial code length */
  1020. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  1021. int codesize[257]; /* codesize[k] = code length of symbol k */
  1022. int others[257]; /* next symbol in current branch of tree */
  1023. int c1, c2;
  1024. int p, i, j;
  1025. long v;
  1026. /* This algorithm is explained in section K.2 of the JPEG standard */
  1027. MEMZERO(bits, SIZEOF(bits));
  1028. MEMZERO(codesize, SIZEOF(codesize));
  1029. for (i = 0; i < 257; i++)
  1030. others[i] = -1; /* init links to empty */
  1031. freq[256] = 1; /* make sure 256 has a nonzero count */
  1032. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  1033. * that no real symbol is given code-value of all ones, because 256
  1034. * will be placed last in the largest codeword category.
  1035. */
  1036. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  1037. for (;;) {
  1038. /* Find the smallest nonzero frequency, set c1 = its symbol */
  1039. /* In case of ties, take the larger symbol number */
  1040. c1 = -1;
  1041. v = 1000000000L;
  1042. for (i = 0; i <= 256; i++) {
  1043. if (freq[i] && freq[i] <= v) {
  1044. v = freq[i];
  1045. c1 = i;
  1046. }
  1047. }
  1048. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  1049. /* In case of ties, take the larger symbol number */
  1050. c2 = -1;
  1051. v = 1000000000L;
  1052. for (i = 0; i <= 256; i++) {
  1053. if (freq[i] && freq[i] <= v && i != c1) {
  1054. v = freq[i];
  1055. c2 = i;
  1056. }
  1057. }
  1058. /* Done if we've merged everything into one frequency */
  1059. if (c2 < 0)
  1060. break;
  1061. /* Else merge the two counts/trees */
  1062. freq[c1] += freq[c2];
  1063. freq[c2] = 0;
  1064. /* Increment the codesize of everything in c1's tree branch */
  1065. codesize[c1]++;
  1066. while (others[c1] >= 0) {
  1067. c1 = others[c1];
  1068. codesize[c1]++;
  1069. }
  1070. others[c1] = c2; /* chain c2 onto c1's tree branch */
  1071. /* Increment the codesize of everything in c2's tree branch */
  1072. codesize[c2]++;
  1073. while (others[c2] >= 0) {
  1074. c2 = others[c2];
  1075. codesize[c2]++;
  1076. }
  1077. }
  1078. /* Now count the number of symbols of each code length */
  1079. for (i = 0; i <= 256; i++) {
  1080. if (codesize[i]) {
  1081. /* The JPEG standard seems to think that this can't happen, */
  1082. /* but I'm paranoid... */
  1083. if (codesize[i] > MAX_CLEN)
  1084. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  1085. bits[codesize[i]]++;
  1086. }
  1087. }
  1088. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  1089. * Huffman procedure assigned any such lengths, we must adjust the coding.
  1090. * Here is what the JPEG spec says about how this next bit works:
  1091. * Since symbols are paired for the longest Huffman code, the symbols are
  1092. * removed from this length category two at a time. The prefix for the pair
  1093. * (which is one bit shorter) is allocated to one of the pair; then,
  1094. * skipping the BITS entry for that prefix length, a code word from the next
  1095. * shortest nonzero BITS entry is converted into a prefix for two code words
  1096. * one bit longer.
  1097. */
  1098. for (i = MAX_CLEN; i > 16; i--) {
  1099. while (bits[i] > 0) {
  1100. j = i - 2; /* find length of new prefix to be used */
  1101. while (bits[j] == 0)
  1102. j--;
  1103. bits[i] -= 2; /* remove two symbols */
  1104. bits[i-1]++; /* one goes in this length */
  1105. bits[j+1] += 2; /* two new symbols in this length */
  1106. bits[j]--; /* symbol of this length is now a prefix */
  1107. }
  1108. }
  1109. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  1110. while (bits[i] == 0) /* find largest codelength still in use */
  1111. i--;
  1112. bits[i]--;
  1113. /* Return final symbol counts (only for lengths 0..16) */
  1114. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  1115. /* Return a list of the symbols sorted by code length */
  1116. /* It's not real clear to me why we don't need to consider the codelength
  1117. * changes made above, but the JPEG spec seems to think this works.
  1118. */
  1119. p = 0;
  1120. for (i = 1; i <= MAX_CLEN; i++) {
  1121. for (j = 0; j <= 255; j++) {
  1122. if (codesize[j] == i) {
  1123. htbl->huffval[p] = (UINT8) j;
  1124. p++;
  1125. }
  1126. }
  1127. }
  1128. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  1129. htbl->sent_table = FALSE;
  1130. }
  1131. /*
  1132. * Finish up a statistics-gathering pass and create the new Huffman tables.
  1133. */
  1134. METHODDEF(void)
  1135. finish_pass_gather (j_compress_ptr cinfo)
  1136. {
  1137. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1138. int ci, tbl;
  1139. jpeg_component_info * compptr;
  1140. JHUFF_TBL **htblptr;
  1141. boolean did_dc[NUM_HUFF_TBLS];
  1142. boolean did_ac[NUM_HUFF_TBLS];
  1143. /* It's important not to apply jpeg_gen_optimal_table more than once
  1144. * per table, because it clobbers the input frequency counts!
  1145. */
  1146. if (cinfo->progressive_mode)
  1147. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  1148. emit_eobrun(entropy);
  1149. MEMZERO(did_dc, SIZEOF(did_dc));
  1150. MEMZERO(did_ac, SIZEOF(did_ac));
  1151. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1152. compptr = cinfo->cur_comp_info[ci];
  1153. /* DC needs no table for refinement scan */
  1154. if (cinfo->Ss == 0 && cinfo->Ah == 0) {
  1155. tbl = compptr->dc_tbl_no;
  1156. if (! did_dc[tbl]) {
  1157. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  1158. if (*htblptr == NULL)
  1159. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  1160. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[tbl]);
  1161. did_dc[tbl] = TRUE;
  1162. }
  1163. }
  1164. /* AC needs no table when not present */
  1165. if (cinfo->Se) {
  1166. tbl = compptr->ac_tbl_no;
  1167. if (! did_ac[tbl]) {
  1168. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  1169. if (*htblptr == NULL)
  1170. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  1171. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[tbl]);
  1172. did_ac[tbl] = TRUE;
  1173. }
  1174. }
  1175. }
  1176. }
  1177. /*
  1178. * Initialize for a Huffman-compressed scan.
  1179. * If gather_statistics is TRUE, we do not output anything during the scan,
  1180. * just count the Huffman symbols used and generate Huffman code tables.
  1181. */
  1182. METHODDEF(void)
  1183. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  1184. {
  1185. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  1186. int ci, tbl;
  1187. jpeg_component_info * compptr;
  1188. if (gather_statistics)
  1189. entropy->pub.finish_pass = finish_pass_gather;
  1190. else
  1191. entropy->pub.finish_pass = finish_pass_huff;
  1192. if (cinfo->progressive_mode) {
  1193. entropy->cinfo = cinfo;
  1194. entropy->gather_statistics = gather_statistics;
  1195. /* We assume jcmaster.c already validated the scan parameters. */
  1196. /* Select execution routine */
  1197. if (cinfo->Ah == 0) {
  1198. if (cinfo->Ss == 0)
  1199. entropy->pub.encode_mcu = encode_mcu_DC_first;
  1200. else
  1201. entropy->pub.encode_mcu = encode_mcu_AC_first;
  1202. } else {
  1203. if (cinfo->Ss == 0)
  1204. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  1205. else {
  1206. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  1207. /* AC refinement needs a correction bit buffer */
  1208. if (entropy->bit_buffer == NULL)
  1209. entropy->bit_buffer = (char *)
  1210. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1211. MAX_CORR_BITS * SIZEOF(char));
  1212. }
  1213. }
  1214. /* Initialize AC stuff */
  1215. entropy->ac_tbl_no = cinfo->cur_comp_info[0]->ac_tbl_no;
  1216. entropy->EOBRUN = 0;
  1217. entropy->BE = 0;
  1218. } else {
  1219. if (gather_statistics)
  1220. entropy->pub.encode_mcu = encode_mcu_gather;
  1221. else
  1222. entropy->pub.encode_mcu = encode_mcu_huff;
  1223. }
  1224. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  1225. compptr = cinfo->cur_comp_info[ci];
  1226. /* DC needs no table for refinement scan */
  1227. if (cinfo->Ss == 0 && cinfo->Ah == 0) {
  1228. tbl = compptr->dc_tbl_no;
  1229. if (gather_statistics) {
  1230. /* Check for invalid table index */
  1231. /* (make_c_derived_tbl does this in the other path) */
  1232. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  1233. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  1234. /* Allocate and zero the statistics tables */
  1235. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  1236. if (entropy->dc_count_ptrs[tbl] == NULL)
  1237. entropy->dc_count_ptrs[tbl] = (long *)
  1238. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1239. 257 * SIZEOF(long));
  1240. MEMZERO(entropy->dc_count_ptrs[tbl], 257 * SIZEOF(long));
  1241. } else {
  1242. /* Compute derived values for Huffman tables */
  1243. /* We may do this more than once for a table, but it's not expensive */
  1244. jpeg_make_c_derived_tbl(cinfo, TRUE, tbl,
  1245. & entropy->dc_derived_tbls[tbl]);
  1246. }
  1247. /* Initialize DC predictions to 0 */
  1248. entropy->saved.last_dc_val[ci] = 0;
  1249. }
  1250. /* AC needs no table when not present */
  1251. if (cinfo->Se) {
  1252. tbl = compptr->ac_tbl_no;
  1253. if (gather_statistics) {
  1254. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  1255. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  1256. if (entropy->ac_count_ptrs[tbl] == NULL)
  1257. entropy->ac_count_ptrs[tbl] = (long *)
  1258. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1259. 257 * SIZEOF(long));
  1260. MEMZERO(entropy->ac_count_ptrs[tbl], 257 * SIZEOF(long));
  1261. } else {
  1262. jpeg_make_c_derived_tbl(cinfo, FALSE, tbl,
  1263. & entropy->ac_derived_tbls[tbl]);
  1264. }
  1265. }
  1266. }
  1267. /* Initialize bit buffer to empty */
  1268. entropy->saved.put_buffer = 0;
  1269. entropy->saved.put_bits = 0;
  1270. /* Initialize restart stuff */
  1271. entropy->restarts_to_go = cinfo->restart_interval;
  1272. entropy->next_restart_num = 0;
  1273. }
  1274. /*
  1275. * Module initialization routine for Huffman entropy encoding.
  1276. */
  1277. GLOBAL(void)
  1278. jinit_huff_encoder (j_compress_ptr cinfo)
  1279. {
  1280. huff_entropy_ptr entropy;
  1281. int i;
  1282. entropy = (huff_entropy_ptr)
  1283. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  1284. SIZEOF(huff_entropy_encoder));
  1285. cinfo->entropy = &entropy->pub;
  1286. entropy->pub.start_pass = start_pass_huff;
  1287. /* Mark tables unallocated */
  1288. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  1289. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  1290. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  1291. }
  1292. if (cinfo->progressive_mode)
  1293. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  1294. }