jchuff.c 34 KB

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