jchuff.c 33 KB

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