jchuff.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. /*
  2. * jchuff.c
  3. *
  4. * This file was part of the Independent JPEG Group's software:
  5. * Copyright (C) 1991-1997, Thomas G. Lane.
  6. * libjpeg-turbo Modifications:
  7. * Copyright (C) 2009-2011, D. R. Commander.
  8. * For conditions of distribution and use, see the accompanying README file.
  9. *
  10. * This file contains Huffman entropy encoding routines.
  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. #define JPEG_INTERNALS
  19. #include "jinclude.h"
  20. #include "jpeglib.h"
  21. #include "jchuff.h" /* Declarations shared with jcphuff.c */
  22. #include <limits.h>
  23. static unsigned char jpeg_nbits_table[65536];
  24. static int jpeg_nbits_table_init = 0;
  25. #ifndef min
  26. #define min(a,b) ((a)<(b)?(a):(b))
  27. #endif
  28. /* Expanded entropy encoder object for Huffman encoding.
  29. *
  30. * The savable_state subrecord contains fields that change within an MCU,
  31. * but must not be updated permanently until we complete the MCU.
  32. */
  33. typedef struct {
  34. size_t put_buffer; /* current bit-accumulation buffer */
  35. int put_bits; /* # of bits now in it */
  36. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  37. } savable_state;
  38. /* This macro is to work around compilers with missing or broken
  39. * structure assignment. You'll need to fix this code if you have
  40. * such a compiler and you change MAX_COMPS_IN_SCAN.
  41. */
  42. #ifndef NO_STRUCT_ASSIGN
  43. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  44. #else
  45. #if MAX_COMPS_IN_SCAN == 4
  46. #define ASSIGN_STATE(dest,src) \
  47. ((dest).put_buffer = (src).put_buffer, \
  48. (dest).put_bits = (src).put_bits, \
  49. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  50. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  51. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  52. (dest).last_dc_val[3] = (src).last_dc_val[3])
  53. #endif
  54. #endif
  55. typedef struct {
  56. struct jpeg_entropy_encoder pub; /* public fields */
  57. savable_state saved; /* Bit buffer & DC state at start of MCU */
  58. /* These fields are NOT loaded into local working state. */
  59. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  60. int next_restart_num; /* next restart number to write (0-7) */
  61. /* Pointers to derived tables (these workspaces have image lifespan) */
  62. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  63. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  64. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  65. long * dc_count_ptrs[NUM_HUFF_TBLS];
  66. long * ac_count_ptrs[NUM_HUFF_TBLS];
  67. #endif
  68. } huff_entropy_encoder;
  69. typedef huff_entropy_encoder * huff_entropy_ptr;
  70. /* Working state while writing an MCU.
  71. * This struct contains all the fields that are needed by subroutines.
  72. */
  73. typedef struct {
  74. JOCTET * next_output_byte; /* => next byte to write in buffer */
  75. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  76. savable_state cur; /* Current bit buffer & DC state */
  77. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  78. } working_state;
  79. /* Forward declarations */
  80. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  81. JBLOCKROW *MCU_data));
  82. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  83. #ifdef ENTROPY_OPT_SUPPORTED
  84. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  85. JBLOCKROW *MCU_data));
  86. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  87. #endif
  88. /*
  89. * Initialize for a Huffman-compressed scan.
  90. * If gather_statistics is TRUE, we do not output anything during the scan,
  91. * just count the Huffman symbols used and generate Huffman code tables.
  92. */
  93. METHODDEF(void)
  94. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  95. {
  96. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  97. int ci, dctbl, actbl;
  98. jpeg_component_info * compptr;
  99. if (gather_statistics) {
  100. #ifdef ENTROPY_OPT_SUPPORTED
  101. entropy->pub.encode_mcu = encode_mcu_gather;
  102. entropy->pub.finish_pass = finish_pass_gather;
  103. #else
  104. ERREXIT(cinfo, JERR_NOT_COMPILED);
  105. #endif
  106. } else {
  107. entropy->pub.encode_mcu = encode_mcu_huff;
  108. entropy->pub.finish_pass = finish_pass_huff;
  109. }
  110. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  111. compptr = cinfo->cur_comp_info[ci];
  112. dctbl = compptr->dc_tbl_no;
  113. actbl = compptr->ac_tbl_no;
  114. if (gather_statistics) {
  115. #ifdef ENTROPY_OPT_SUPPORTED
  116. /* Check for invalid table indexes */
  117. /* (make_c_derived_tbl does this in the other path) */
  118. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  119. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  120. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  121. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  122. /* Allocate and zero the statistics tables */
  123. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  124. if (entropy->dc_count_ptrs[dctbl] == NULL)
  125. entropy->dc_count_ptrs[dctbl] = (long *)
  126. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  127. 257 * SIZEOF(long));
  128. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  129. if (entropy->ac_count_ptrs[actbl] == NULL)
  130. entropy->ac_count_ptrs[actbl] = (long *)
  131. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  132. 257 * SIZEOF(long));
  133. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  134. #endif
  135. } else {
  136. /* Compute derived values for Huffman tables */
  137. /* We may do this more than once for a table, but it's not expensive */
  138. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  139. & entropy->dc_derived_tbls[dctbl]);
  140. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  141. & entropy->ac_derived_tbls[actbl]);
  142. }
  143. /* Initialize DC predictions to 0 */
  144. entropy->saved.last_dc_val[ci] = 0;
  145. }
  146. /* Initialize bit buffer to empty */
  147. entropy->saved.put_buffer = 0;
  148. entropy->saved.put_bits = 0;
  149. /* Initialize restart stuff */
  150. entropy->restarts_to_go = cinfo->restart_interval;
  151. entropy->next_restart_num = 0;
  152. }
  153. /*
  154. * Compute the derived values for a Huffman table.
  155. * This routine also performs some validation checks on the table.
  156. *
  157. * Note this is also used by jcphuff.c.
  158. */
  159. GLOBAL(void)
  160. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  161. c_derived_tbl ** pdtbl)
  162. {
  163. JHUFF_TBL *htbl;
  164. c_derived_tbl *dtbl;
  165. int p, i, l, lastp, si, maxsymbol;
  166. char huffsize[257];
  167. unsigned int huffcode[257];
  168. unsigned int code;
  169. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170. * paralleling the order of the symbols themselves in htbl->huffval[].
  171. */
  172. /* Find the input Huffman table */
  173. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  174. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  175. htbl =
  176. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  177. if (htbl == NULL)
  178. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  179. /* Allocate a workspace if we haven't already done so. */
  180. if (*pdtbl == NULL)
  181. *pdtbl = (c_derived_tbl *)
  182. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  183. SIZEOF(c_derived_tbl));
  184. dtbl = *pdtbl;
  185. /* Figure C.1: make table of Huffman code length for each symbol */
  186. p = 0;
  187. for (l = 1; l <= 16; l++) {
  188. i = (int) htbl->bits[l];
  189. if (i < 0 || p + i > 256) /* protect against table overrun */
  190. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  191. while (i--)
  192. huffsize[p++] = (char) l;
  193. }
  194. huffsize[p] = 0;
  195. lastp = p;
  196. /* Figure C.2: generate the codes themselves */
  197. /* We also validate that the counts represent a legal Huffman code tree. */
  198. code = 0;
  199. si = huffsize[0];
  200. p = 0;
  201. while (huffsize[p]) {
  202. while (((int) huffsize[p]) == si) {
  203. huffcode[p++] = code;
  204. code++;
  205. }
  206. /* code is now 1 more than the last code used for codelength si; but
  207. * it must still fit in si bits, since no code is allowed to be all ones.
  208. */
  209. if (((INT32) code) >= (((INT32) 1) << si))
  210. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  211. code <<= 1;
  212. si++;
  213. }
  214. /* Figure C.3: generate encoding tables */
  215. /* These are code and size indexed by symbol value */
  216. /* Set all codeless symbols to have code length 0;
  217. * this lets us detect duplicate VAL entries here, and later
  218. * allows emit_bits to detect any attempt to emit such symbols.
  219. */
  220. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  221. /* This is also a convenient place to check for out-of-range
  222. * and duplicated VAL entries. We allow 0..255 for AC symbols
  223. * but only 0..15 for DC. (We could constrain them further
  224. * based on data depth and mode, but this seems enough.)
  225. */
  226. maxsymbol = isDC ? 15 : 255;
  227. for (p = 0; p < lastp; p++) {
  228. i = htbl->huffval[p];
  229. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  230. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  231. dtbl->ehufco[i] = huffcode[p];
  232. dtbl->ehufsi[i] = huffsize[p];
  233. }
  234. if(!jpeg_nbits_table_init) {
  235. for(i = 0; i < 65536; i++) {
  236. int nbits = 0, temp = i;
  237. while (temp) {temp >>= 1; nbits++;}
  238. jpeg_nbits_table[i] = nbits;
  239. }
  240. jpeg_nbits_table_init = 1;
  241. }
  242. }
  243. /* Outputting bytes to the file */
  244. /* Emit a byte, taking 'action' if must suspend. */
  245. #define emit_byte(state,val,action) \
  246. { *(state)->next_output_byte++ = (JOCTET) (val); \
  247. if (--(state)->free_in_buffer == 0) \
  248. if (! dump_buffer(state)) \
  249. { action; } }
  250. LOCAL(boolean)
  251. dump_buffer (working_state * state)
  252. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  253. {
  254. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  255. if (! (*dest->empty_output_buffer) (state->cinfo))
  256. return FALSE;
  257. /* After a successful buffer dump, must reset buffer pointers */
  258. state->next_output_byte = dest->next_output_byte;
  259. state->free_in_buffer = dest->free_in_buffer;
  260. return TRUE;
  261. }
  262. /* Outputting bits to the file */
  263. /* These macros perform the same task as the emit_bits() function in the
  264. * original libjpeg code. In addition to reducing overhead by explicitly
  265. * inlining the code, additional performance is achieved by taking into
  266. * account the size of the bit buffer and waiting until it is almost full
  267. * before emptying it. This mostly benefits 64-bit platforms, since 6
  268. * bytes can be stored in a 64-bit bit buffer before it has to be emptied.
  269. */
  270. #define EMIT_BYTE() { \
  271. JOCTET c; \
  272. put_bits -= 8; \
  273. c = (JOCTET)GETJOCTET(put_buffer >> put_bits); \
  274. *buffer++ = c; \
  275. if (c == 0xFF) /* need to stuff a zero byte? */ \
  276. *buffer++ = 0; \
  277. }
  278. #define PUT_BITS(code, size) { \
  279. put_bits += size; \
  280. put_buffer = (put_buffer << size) | code; \
  281. }
  282. #define CHECKBUF15() { \
  283. if (put_bits > 15) { \
  284. EMIT_BYTE() \
  285. EMIT_BYTE() \
  286. } \
  287. }
  288. #define CHECKBUF31() { \
  289. if (put_bits > 31) { \
  290. EMIT_BYTE() \
  291. EMIT_BYTE() \
  292. EMIT_BYTE() \
  293. EMIT_BYTE() \
  294. } \
  295. }
  296. #define CHECKBUF47() { \
  297. if (put_bits > 47) { \
  298. EMIT_BYTE() \
  299. EMIT_BYTE() \
  300. EMIT_BYTE() \
  301. EMIT_BYTE() \
  302. EMIT_BYTE() \
  303. EMIT_BYTE() \
  304. } \
  305. }
  306. #if __WORDSIZE==64 || defined(_WIN64)
  307. #define EMIT_BITS(code, size) { \
  308. CHECKBUF47() \
  309. PUT_BITS(code, size) \
  310. }
  311. #define EMIT_CODE(code, size) { \
  312. temp2 &= (((INT32) 1)<<nbits) - 1; \
  313. CHECKBUF31() \
  314. PUT_BITS(code, size) \
  315. PUT_BITS(temp2, nbits) \
  316. }
  317. #else
  318. #define EMIT_BITS(code, size) { \
  319. PUT_BITS(code, size) \
  320. CHECKBUF15() \
  321. }
  322. #define EMIT_CODE(code, size) { \
  323. temp2 &= (((INT32) 1)<<nbits) - 1; \
  324. PUT_BITS(code, size) \
  325. CHECKBUF15() \
  326. PUT_BITS(temp2, nbits) \
  327. CHECKBUF15() \
  328. }
  329. #endif
  330. #define BUFSIZE (DCTSIZE2 * 2)
  331. #define LOAD_BUFFER() { \
  332. if (state->free_in_buffer < BUFSIZE) { \
  333. localbuf = 1; \
  334. buffer = _buffer; \
  335. } \
  336. else buffer = state->next_output_byte; \
  337. }
  338. #define STORE_BUFFER() { \
  339. if (localbuf) { \
  340. bytes = buffer - _buffer; \
  341. buffer = _buffer; \
  342. while (bytes > 0) { \
  343. bytestocopy = min(bytes, state->free_in_buffer); \
  344. MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
  345. state->next_output_byte += bytestocopy; \
  346. buffer += bytestocopy; \
  347. state->free_in_buffer -= bytestocopy; \
  348. if (state->free_in_buffer == 0) \
  349. if (! dump_buffer(state)) return FALSE; \
  350. bytes -= bytestocopy; \
  351. } \
  352. } \
  353. else { \
  354. state->free_in_buffer -= (buffer - state->next_output_byte); \
  355. state->next_output_byte = buffer; \
  356. } \
  357. }
  358. LOCAL(boolean)
  359. flush_bits (working_state * state)
  360. {
  361. JOCTET _buffer[BUFSIZE], *buffer;
  362. size_t put_buffer; int put_bits;
  363. size_t bytes, bytestocopy; int localbuf = 0;
  364. put_buffer = state->cur.put_buffer;
  365. put_bits = state->cur.put_bits;
  366. LOAD_BUFFER()
  367. /* fill any partial byte with ones */
  368. PUT_BITS(0x7F, 7)
  369. while (put_bits >= 8) EMIT_BYTE()
  370. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  371. state->cur.put_bits = 0;
  372. STORE_BUFFER()
  373. return TRUE;
  374. }
  375. /* Encode a single block's worth of coefficients */
  376. LOCAL(boolean)
  377. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  378. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  379. {
  380. int temp, temp2, temp3;
  381. int nbits;
  382. int r, code, size;
  383. JOCTET _buffer[BUFSIZE], *buffer;
  384. size_t put_buffer; int put_bits;
  385. int code_0xf0 = actbl->ehufco[0xf0], size_0xf0 = actbl->ehufsi[0xf0];
  386. size_t bytes, bytestocopy; int localbuf = 0;
  387. put_buffer = state->cur.put_buffer;
  388. put_bits = state->cur.put_bits;
  389. LOAD_BUFFER()
  390. /* Encode the DC coefficient difference per section F.1.2.1 */
  391. temp = temp2 = block[0] - last_dc_val;
  392. /* This is a well-known technique for obtaining the absolute value without a
  393. * branch. It is derived from an assembly language technique presented in
  394. * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
  395. * Agner Fog.
  396. */
  397. temp3 = temp >> (CHAR_BIT * sizeof(int) - 1);
  398. temp ^= temp3;
  399. temp -= temp3;
  400. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  401. /* This code assumes we are on a two's complement machine */
  402. temp2 += temp3;
  403. /* Find the number of bits needed for the magnitude of the coefficient */
  404. nbits = jpeg_nbits_table[temp];
  405. /* Emit the Huffman-coded symbol for the number of bits */
  406. code = dctbl->ehufco[nbits];
  407. size = dctbl->ehufsi[nbits];
  408. PUT_BITS(code, size)
  409. CHECKBUF15()
  410. /* Mask off any extra bits in code */
  411. temp2 &= (((INT32) 1)<<nbits) - 1;
  412. /* Emit that number of bits of the value, if positive, */
  413. /* or the complement of its magnitude, if negative. */
  414. PUT_BITS(temp2, nbits)
  415. CHECKBUF15()
  416. /* Encode the AC coefficients per section F.1.2.2 */
  417. r = 0; /* r = run length of zeros */
  418. /* Manually unroll the k loop to eliminate the counter variable. This
  419. * improves performance greatly on systems with a limited number of
  420. * registers (such as x86.)
  421. */
  422. #define kloop(jpeg_natural_order_of_k) { \
  423. if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
  424. r++; \
  425. } else { \
  426. temp2 = temp; \
  427. /* Branch-less absolute value, bitwise complement, etc., same as above */ \
  428. temp3 = temp >> (CHAR_BIT * sizeof(int) - 1); \
  429. temp ^= temp3; \
  430. temp -= temp3; \
  431. temp2 += temp3; \
  432. nbits = jpeg_nbits_table[temp]; \
  433. /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
  434. while (r > 15) { \
  435. EMIT_BITS(code_0xf0, size_0xf0) \
  436. r -= 16; \
  437. } \
  438. /* Emit Huffman symbol for run length / number of bits */ \
  439. temp3 = (r << 4) + nbits; \
  440. code = actbl->ehufco[temp3]; \
  441. size = actbl->ehufsi[temp3]; \
  442. EMIT_CODE(code, size) \
  443. r = 0; \
  444. } \
  445. }
  446. /* One iteration for each value in jpeg_natural_order[] */
  447. kloop(1); kloop(8); kloop(16); kloop(9); kloop(2); kloop(3);
  448. kloop(10); kloop(17); kloop(24); kloop(32); kloop(25); kloop(18);
  449. kloop(11); kloop(4); kloop(5); kloop(12); kloop(19); kloop(26);
  450. kloop(33); kloop(40); kloop(48); kloop(41); kloop(34); kloop(27);
  451. kloop(20); kloop(13); kloop(6); kloop(7); kloop(14); kloop(21);
  452. kloop(28); kloop(35); kloop(42); kloop(49); kloop(56); kloop(57);
  453. kloop(50); kloop(43); kloop(36); kloop(29); kloop(22); kloop(15);
  454. kloop(23); kloop(30); kloop(37); kloop(44); kloop(51); kloop(58);
  455. kloop(59); kloop(52); kloop(45); kloop(38); kloop(31); kloop(39);
  456. kloop(46); kloop(53); kloop(60); kloop(61); kloop(54); kloop(47);
  457. kloop(55); kloop(62); kloop(63);
  458. /* If the last coef(s) were zero, emit an end-of-block code */
  459. if (r > 0) {
  460. code = actbl->ehufco[0];
  461. size = actbl->ehufsi[0];
  462. EMIT_BITS(code, size)
  463. }
  464. state->cur.put_buffer = put_buffer;
  465. state->cur.put_bits = put_bits;
  466. STORE_BUFFER()
  467. return TRUE;
  468. }
  469. /*
  470. * Emit a restart marker & resynchronize predictions.
  471. */
  472. LOCAL(boolean)
  473. emit_restart (working_state * state, int restart_num)
  474. {
  475. int ci;
  476. if (! flush_bits(state))
  477. return FALSE;
  478. emit_byte(state, 0xFF, return FALSE);
  479. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  480. /* Re-initialize DC predictions to 0 */
  481. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  482. state->cur.last_dc_val[ci] = 0;
  483. /* The restart counter is not updated until we successfully write the MCU. */
  484. return TRUE;
  485. }
  486. /*
  487. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  488. */
  489. METHODDEF(boolean)
  490. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  491. {
  492. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  493. working_state state;
  494. int blkn, ci;
  495. jpeg_component_info * compptr;
  496. /* Load up working state */
  497. state.next_output_byte = cinfo->dest->next_output_byte;
  498. state.free_in_buffer = cinfo->dest->free_in_buffer;
  499. ASSIGN_STATE(state.cur, entropy->saved);
  500. state.cinfo = cinfo;
  501. /* Emit restart marker if needed */
  502. if (cinfo->restart_interval) {
  503. if (entropy->restarts_to_go == 0)
  504. if (! emit_restart(&state, entropy->next_restart_num))
  505. return FALSE;
  506. }
  507. /* Encode the MCU data blocks */
  508. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  509. ci = cinfo->MCU_membership[blkn];
  510. compptr = cinfo->cur_comp_info[ci];
  511. if (! encode_one_block(&state,
  512. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  513. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  514. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  515. return FALSE;
  516. /* Update last_dc_val */
  517. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  518. }
  519. /* Completed MCU, so update state */
  520. cinfo->dest->next_output_byte = state.next_output_byte;
  521. cinfo->dest->free_in_buffer = state.free_in_buffer;
  522. ASSIGN_STATE(entropy->saved, state.cur);
  523. /* Update restart-interval state too */
  524. if (cinfo->restart_interval) {
  525. if (entropy->restarts_to_go == 0) {
  526. entropy->restarts_to_go = cinfo->restart_interval;
  527. entropy->next_restart_num++;
  528. entropy->next_restart_num &= 7;
  529. }
  530. entropy->restarts_to_go--;
  531. }
  532. return TRUE;
  533. }
  534. /*
  535. * Finish up at the end of a Huffman-compressed scan.
  536. */
  537. METHODDEF(void)
  538. finish_pass_huff (j_compress_ptr cinfo)
  539. {
  540. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  541. working_state state;
  542. /* Load up working state ... flush_bits needs it */
  543. state.next_output_byte = cinfo->dest->next_output_byte;
  544. state.free_in_buffer = cinfo->dest->free_in_buffer;
  545. ASSIGN_STATE(state.cur, entropy->saved);
  546. state.cinfo = cinfo;
  547. /* Flush out the last data */
  548. if (! flush_bits(&state))
  549. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  550. /* Update state */
  551. cinfo->dest->next_output_byte = state.next_output_byte;
  552. cinfo->dest->free_in_buffer = state.free_in_buffer;
  553. ASSIGN_STATE(entropy->saved, state.cur);
  554. }
  555. /*
  556. * Huffman coding optimization.
  557. *
  558. * We first scan the supplied data and count the number of uses of each symbol
  559. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  560. * Then we build a Huffman coding tree for the observed counts.
  561. * Symbols which are not needed at all for the particular image are not
  562. * assigned any code, which saves space in the DHT marker as well as in
  563. * the compressed data.
  564. */
  565. #ifdef ENTROPY_OPT_SUPPORTED
  566. /* Process a single block's worth of coefficients */
  567. LOCAL(void)
  568. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  569. long dc_counts[], long ac_counts[])
  570. {
  571. register int temp;
  572. register int nbits;
  573. register int k, r;
  574. /* Encode the DC coefficient difference per section F.1.2.1 */
  575. temp = block[0] - last_dc_val;
  576. if (temp < 0)
  577. temp = -temp;
  578. /* Find the number of bits needed for the magnitude of the coefficient */
  579. nbits = 0;
  580. while (temp) {
  581. nbits++;
  582. temp >>= 1;
  583. }
  584. /* Check for out-of-range coefficient values.
  585. * Since we're encoding a difference, the range limit is twice as much.
  586. */
  587. if (nbits > MAX_COEF_BITS+1)
  588. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  589. /* Count the Huffman symbol for the number of bits */
  590. dc_counts[nbits]++;
  591. /* Encode the AC coefficients per section F.1.2.2 */
  592. r = 0; /* r = run length of zeros */
  593. for (k = 1; k < DCTSIZE2; k++) {
  594. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  595. r++;
  596. } else {
  597. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  598. while (r > 15) {
  599. ac_counts[0xF0]++;
  600. r -= 16;
  601. }
  602. /* Find the number of bits needed for the magnitude of the coefficient */
  603. if (temp < 0)
  604. temp = -temp;
  605. /* Find the number of bits needed for the magnitude of the coefficient */
  606. nbits = 1; /* there must be at least one 1 bit */
  607. while ((temp >>= 1))
  608. nbits++;
  609. /* Check for out-of-range coefficient values */
  610. if (nbits > MAX_COEF_BITS)
  611. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  612. /* Count Huffman symbol for run length / number of bits */
  613. ac_counts[(r << 4) + nbits]++;
  614. r = 0;
  615. }
  616. }
  617. /* If the last coef(s) were zero, emit an end-of-block code */
  618. if (r > 0)
  619. ac_counts[0]++;
  620. }
  621. /*
  622. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  623. * No data is actually output, so no suspension return is possible.
  624. */
  625. METHODDEF(boolean)
  626. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  627. {
  628. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  629. int blkn, ci;
  630. jpeg_component_info * compptr;
  631. /* Take care of restart intervals if needed */
  632. if (cinfo->restart_interval) {
  633. if (entropy->restarts_to_go == 0) {
  634. /* Re-initialize DC predictions to 0 */
  635. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  636. entropy->saved.last_dc_val[ci] = 0;
  637. /* Update restart state */
  638. entropy->restarts_to_go = cinfo->restart_interval;
  639. }
  640. entropy->restarts_to_go--;
  641. }
  642. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  643. ci = cinfo->MCU_membership[blkn];
  644. compptr = cinfo->cur_comp_info[ci];
  645. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  646. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  647. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  648. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  649. }
  650. return TRUE;
  651. }
  652. /*
  653. * Generate the best Huffman code table for the given counts, fill htbl.
  654. * Note this is also used by jcphuff.c.
  655. *
  656. * The JPEG standard requires that no symbol be assigned a codeword of all
  657. * one bits (so that padding bits added at the end of a compressed segment
  658. * can't look like a valid code). Because of the canonical ordering of
  659. * codewords, this just means that there must be an unused slot in the
  660. * longest codeword length category. Section K.2 of the JPEG spec suggests
  661. * reserving such a slot by pretending that symbol 256 is a valid symbol
  662. * with count 1. In theory that's not optimal; giving it count zero but
  663. * including it in the symbol set anyway should give a better Huffman code.
  664. * But the theoretically better code actually seems to come out worse in
  665. * practice, because it produces more all-ones bytes (which incur stuffed
  666. * zero bytes in the final file). In any case the difference is tiny.
  667. *
  668. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  669. * If some symbols have a very small but nonzero probability, the Huffman tree
  670. * must be adjusted to meet the code length restriction. We currently use
  671. * the adjustment method suggested in JPEG section K.2. This method is *not*
  672. * optimal; it may not choose the best possible limited-length code. But
  673. * typically only very-low-frequency symbols will be given less-than-optimal
  674. * lengths, so the code is almost optimal. Experimental comparisons against
  675. * an optimal limited-length-code algorithm indicate that the difference is
  676. * microscopic --- usually less than a hundredth of a percent of total size.
  677. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  678. */
  679. GLOBAL(void)
  680. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  681. {
  682. #define MAX_CLEN 32 /* assumed maximum initial code length */
  683. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  684. int codesize[257]; /* codesize[k] = code length of symbol k */
  685. int others[257]; /* next symbol in current branch of tree */
  686. int c1, c2;
  687. int p, i, j;
  688. long v;
  689. /* This algorithm is explained in section K.2 of the JPEG standard */
  690. MEMZERO(bits, SIZEOF(bits));
  691. MEMZERO(codesize, SIZEOF(codesize));
  692. for (i = 0; i < 257; i++)
  693. others[i] = -1; /* init links to empty */
  694. freq[256] = 1; /* make sure 256 has a nonzero count */
  695. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  696. * that no real symbol is given code-value of all ones, because 256
  697. * will be placed last in the largest codeword category.
  698. */
  699. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  700. for (;;) {
  701. /* Find the smallest nonzero frequency, set c1 = its symbol */
  702. /* In case of ties, take the larger symbol number */
  703. c1 = -1;
  704. v = 1000000000L;
  705. for (i = 0; i <= 256; i++) {
  706. if (freq[i] && freq[i] <= v) {
  707. v = freq[i];
  708. c1 = i;
  709. }
  710. }
  711. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  712. /* In case of ties, take the larger symbol number */
  713. c2 = -1;
  714. v = 1000000000L;
  715. for (i = 0; i <= 256; i++) {
  716. if (freq[i] && freq[i] <= v && i != c1) {
  717. v = freq[i];
  718. c2 = i;
  719. }
  720. }
  721. /* Done if we've merged everything into one frequency */
  722. if (c2 < 0)
  723. break;
  724. /* Else merge the two counts/trees */
  725. freq[c1] += freq[c2];
  726. freq[c2] = 0;
  727. /* Increment the codesize of everything in c1's tree branch */
  728. codesize[c1]++;
  729. while (others[c1] >= 0) {
  730. c1 = others[c1];
  731. codesize[c1]++;
  732. }
  733. others[c1] = c2; /* chain c2 onto c1's tree branch */
  734. /* Increment the codesize of everything in c2's tree branch */
  735. codesize[c2]++;
  736. while (others[c2] >= 0) {
  737. c2 = others[c2];
  738. codesize[c2]++;
  739. }
  740. }
  741. /* Now count the number of symbols of each code length */
  742. for (i = 0; i <= 256; i++) {
  743. if (codesize[i]) {
  744. /* The JPEG standard seems to think that this can't happen, */
  745. /* but I'm paranoid... */
  746. if (codesize[i] > MAX_CLEN)
  747. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  748. bits[codesize[i]]++;
  749. }
  750. }
  751. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  752. * Huffman procedure assigned any such lengths, we must adjust the coding.
  753. * Here is what the JPEG spec says about how this next bit works:
  754. * Since symbols are paired for the longest Huffman code, the symbols are
  755. * removed from this length category two at a time. The prefix for the pair
  756. * (which is one bit shorter) is allocated to one of the pair; then,
  757. * skipping the BITS entry for that prefix length, a code word from the next
  758. * shortest nonzero BITS entry is converted into a prefix for two code words
  759. * one bit longer.
  760. */
  761. for (i = MAX_CLEN; i > 16; i--) {
  762. while (bits[i] > 0) {
  763. j = i - 2; /* find length of new prefix to be used */
  764. while (bits[j] == 0)
  765. j--;
  766. bits[i] -= 2; /* remove two symbols */
  767. bits[i-1]++; /* one goes in this length */
  768. bits[j+1] += 2; /* two new symbols in this length */
  769. bits[j]--; /* symbol of this length is now a prefix */
  770. }
  771. }
  772. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  773. while (bits[i] == 0) /* find largest codelength still in use */
  774. i--;
  775. bits[i]--;
  776. /* Return final symbol counts (only for lengths 0..16) */
  777. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  778. /* Return a list of the symbols sorted by code length */
  779. /* It's not real clear to me why we don't need to consider the codelength
  780. * changes made above, but the JPEG spec seems to think this works.
  781. */
  782. p = 0;
  783. for (i = 1; i <= MAX_CLEN; i++) {
  784. for (j = 0; j <= 255; j++) {
  785. if (codesize[j] == i) {
  786. htbl->huffval[p] = (UINT8) j;
  787. p++;
  788. }
  789. }
  790. }
  791. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  792. htbl->sent_table = FALSE;
  793. }
  794. /*
  795. * Finish up a statistics-gathering pass and create the new Huffman tables.
  796. */
  797. METHODDEF(void)
  798. finish_pass_gather (j_compress_ptr cinfo)
  799. {
  800. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  801. int ci, dctbl, actbl;
  802. jpeg_component_info * compptr;
  803. JHUFF_TBL **htblptr;
  804. boolean did_dc[NUM_HUFF_TBLS];
  805. boolean did_ac[NUM_HUFF_TBLS];
  806. /* It's important not to apply jpeg_gen_optimal_table more than once
  807. * per table, because it clobbers the input frequency counts!
  808. */
  809. MEMZERO(did_dc, SIZEOF(did_dc));
  810. MEMZERO(did_ac, SIZEOF(did_ac));
  811. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  812. compptr = cinfo->cur_comp_info[ci];
  813. dctbl = compptr->dc_tbl_no;
  814. actbl = compptr->ac_tbl_no;
  815. if (! did_dc[dctbl]) {
  816. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  817. if (*htblptr == NULL)
  818. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  819. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  820. did_dc[dctbl] = TRUE;
  821. }
  822. if (! did_ac[actbl]) {
  823. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  824. if (*htblptr == NULL)
  825. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  826. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  827. did_ac[actbl] = TRUE;
  828. }
  829. }
  830. }
  831. #endif /* ENTROPY_OPT_SUPPORTED */
  832. /*
  833. * Module initialization routine for Huffman entropy encoding.
  834. */
  835. GLOBAL(void)
  836. jinit_huff_encoder (j_compress_ptr cinfo)
  837. {
  838. huff_entropy_ptr entropy;
  839. int i;
  840. entropy = (huff_entropy_ptr)
  841. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  842. SIZEOF(huff_entropy_encoder));
  843. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  844. entropy->pub.start_pass = start_pass_huff;
  845. /* Mark tables unallocated */
  846. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  847. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  848. #ifdef ENTROPY_OPT_SUPPORTED
  849. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  850. #endif
  851. }
  852. }