jchuff.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. /*
  2. * jchuff.c
  3. *
  4. * Copyright (C) 1991-1995, Thomas G. Lane.
  5. * This file is part of the Independent JPEG Group's software.
  6. * For conditions of distribution and use, see the accompanying README file.
  7. *
  8. * This file contains Huffman entropy encoding routines.
  9. *
  10. * Much of the complexity here has to do with supporting output suspension.
  11. * If the data destination module demands suspension, we want to be able to
  12. * back up to the start of the current MCU. To do this, we copy state
  13. * variables into local working storage, and update them back to the
  14. * permanent JPEG objects only upon successful completion of an MCU.
  15. */
  16. // leave this as first line for PCH reasons...
  17. //
  18. #include "../server/exe_headers.h"
  19. #define JPEG_INTERNALS
  20. #include "jinclude.h"
  21. #include "jpeglib.h"
  22. #include "jchuff.h" /* Declarations shared with jcphuff.c */
  23. /* Expanded entropy encoder object for Huffman encoding.
  24. *
  25. * The savable_state subrecord contains fields that change within an MCU,
  26. * but must not be updated permanently until we complete the MCU.
  27. */
  28. typedef struct {
  29. INT32 put_buffer; /* current bit-accumulation buffer */
  30. int put_bits; /* # of bits now in it */
  31. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  32. } savable_state;
  33. /* This macro is to work around compilers with missing or broken
  34. * structure assignment. You'll need to fix this code if you have
  35. * such a compiler and you change MAX_COMPS_IN_SCAN.
  36. */
  37. #ifndef NO_STRUCT_ASSIGN
  38. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  39. #else
  40. #if MAX_COMPS_IN_SCAN == 4
  41. #define ASSIGN_STATE(dest,src) \
  42. ((dest).put_buffer = (src).put_buffer, \
  43. (dest).put_bits = (src).put_bits, \
  44. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  45. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  46. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  47. (dest).last_dc_val[3] = (src).last_dc_val[3])
  48. #endif
  49. #endif
  50. typedef struct {
  51. struct jpeg_entropy_encoder pub; /* public fields */
  52. savable_state saved; /* Bit buffer & DC state at start of MCU */
  53. /* These fields are NOT loaded into local working state. */
  54. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  55. int next_restart_num; /* next restart number to write (0-7) */
  56. /* Pointers to derived tables (these workspaces have image lifespan) */
  57. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  58. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  59. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  60. long * dc_count_ptrs[NUM_HUFF_TBLS];
  61. long * ac_count_ptrs[NUM_HUFF_TBLS];
  62. #endif
  63. } huff_entropy_encoder;
  64. typedef huff_entropy_encoder * huff_entropy_ptr;
  65. /* Working state while writing an MCU.
  66. * This struct contains all the fields that are needed by subroutines.
  67. */
  68. typedef struct {
  69. JOCTET * next_output_byte; /* => next byte to write in buffer */
  70. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  71. savable_state cur; /* Current bit buffer & DC state */
  72. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  73. } working_state;
  74. /* Forward declarations */
  75. METHODDEF boolean encode_mcu_huff JPP((j_compress_ptr cinfo,
  76. JBLOCKROW *MCU_data));
  77. METHODDEF void finish_pass_huff JPP((j_compress_ptr cinfo));
  78. #ifdef ENTROPY_OPT_SUPPORTED
  79. METHODDEF boolean encode_mcu_gather JPP((j_compress_ptr cinfo,
  80. JBLOCKROW *MCU_data));
  81. METHODDEF void finish_pass_gather JPP((j_compress_ptr cinfo));
  82. #endif
  83. /*
  84. * Initialize for a Huffman-compressed scan.
  85. * If gather_statistics is TRUE, we do not output anything during the scan,
  86. * just count the Huffman symbols used and generate Huffman code tables.
  87. */
  88. METHODDEF void
  89. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  90. {
  91. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  92. int ci, dctbl, actbl;
  93. jpeg_component_info * compptr;
  94. if (gather_statistics) {
  95. #ifdef ENTROPY_OPT_SUPPORTED
  96. entropy->pub.encode_mcu = encode_mcu_gather;
  97. entropy->pub.finish_pass = finish_pass_gather;
  98. #else
  99. ERREXIT(cinfo, JERR_NOT_COMPILED);
  100. #endif
  101. } else {
  102. entropy->pub.encode_mcu = encode_mcu_huff;
  103. entropy->pub.finish_pass = finish_pass_huff;
  104. }
  105. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  106. compptr = cinfo->cur_comp_info[ci];
  107. dctbl = compptr->dc_tbl_no;
  108. actbl = compptr->ac_tbl_no;
  109. /* Make sure requested tables are present */
  110. /* (In gather mode, tables need not be allocated yet) */
  111. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS ||
  112. (cinfo->dc_huff_tbl_ptrs[dctbl] == NULL && !gather_statistics))
  113. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  114. if (actbl < 0 || actbl >= NUM_HUFF_TBLS ||
  115. (cinfo->ac_huff_tbl_ptrs[actbl] == NULL && !gather_statistics))
  116. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  117. if (gather_statistics) {
  118. #ifdef ENTROPY_OPT_SUPPORTED
  119. /* Allocate and zero the statistics tables */
  120. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  121. if (entropy->dc_count_ptrs[dctbl] == NULL)
  122. entropy->dc_count_ptrs[dctbl] = (long *)
  123. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  124. 257 * SIZEOF(long));
  125. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  126. if (entropy->ac_count_ptrs[actbl] == NULL)
  127. entropy->ac_count_ptrs[actbl] = (long *)
  128. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  129. 257 * SIZEOF(long));
  130. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  131. #endif
  132. } else {
  133. /* Compute derived values for Huffman tables */
  134. /* We may do this more than once for a table, but it's not expensive */
  135. jpeg_make_c_derived_tbl(cinfo, cinfo->dc_huff_tbl_ptrs[dctbl],
  136. & entropy->dc_derived_tbls[dctbl]);
  137. jpeg_make_c_derived_tbl(cinfo, cinfo->ac_huff_tbl_ptrs[actbl],
  138. & entropy->ac_derived_tbls[actbl]);
  139. }
  140. /* Initialize DC predictions to 0 */
  141. entropy->saved.last_dc_val[ci] = 0;
  142. }
  143. /* Initialize bit buffer to empty */
  144. entropy->saved.put_buffer = 0;
  145. entropy->saved.put_bits = 0;
  146. /* Initialize restart stuff */
  147. entropy->restarts_to_go = cinfo->restart_interval;
  148. entropy->next_restart_num = 0;
  149. }
  150. /*
  151. * Compute the derived values for a Huffman table.
  152. * Note this is also used by jcphuff.c.
  153. */
  154. GLOBAL void
  155. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, JHUFF_TBL * htbl,
  156. c_derived_tbl ** pdtbl)
  157. {
  158. c_derived_tbl *dtbl;
  159. int p, i, l, lastp, si;
  160. char huffsize[257];
  161. unsigned int huffcode[257];
  162. unsigned int code;
  163. /* Allocate a workspace if we haven't already done so. */
  164. if (*pdtbl == NULL)
  165. *pdtbl = (c_derived_tbl *)
  166. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167. SIZEOF(c_derived_tbl));
  168. dtbl = *pdtbl;
  169. /* Figure C.1: make table of Huffman code length for each symbol */
  170. /* Note that this is in code-length order. */
  171. p = 0;
  172. for (l = 1; l <= 16; l++) {
  173. for (i = 1; i <= (int) htbl->bits[l]; i++)
  174. huffsize[p++] = (char) l;
  175. }
  176. huffsize[p] = 0;
  177. lastp = p;
  178. /* Figure C.2: generate the codes themselves */
  179. /* Note that this is in code-length order. */
  180. code = 0;
  181. si = huffsize[0];
  182. p = 0;
  183. while (huffsize[p]) {
  184. while (((int) huffsize[p]) == si) {
  185. huffcode[p++] = code;
  186. code++;
  187. }
  188. code <<= 1;
  189. si++;
  190. }
  191. /* Figure C.3: generate encoding tables */
  192. /* These are code and size indexed by symbol value */
  193. /* Set any codeless symbols to have code length 0;
  194. * this allows emit_bits to detect any attempt to emit such symbols.
  195. */
  196. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  197. for (p = 0; p < lastp; p++) {
  198. dtbl->ehufco[htbl->huffval[p]] = huffcode[p];
  199. dtbl->ehufsi[htbl->huffval[p]] = huffsize[p];
  200. }
  201. }
  202. /* Outputting bytes to the file */
  203. /* Emit a byte, taking 'action' if must suspend. */
  204. #define emit_byte(state,val,action) \
  205. { *(state)->next_output_byte++ = (JOCTET) (val); \
  206. if (--(state)->free_in_buffer == 0) \
  207. if (! dump_buffer(state)) \
  208. { action; } }
  209. LOCAL boolean
  210. dump_buffer (working_state * state)
  211. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  212. {
  213. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  214. if (! (*dest->empty_output_buffer) (state->cinfo))
  215. return FALSE;
  216. /* After a successful buffer dump, must reset buffer pointers */
  217. state->next_output_byte = dest->next_output_byte;
  218. state->free_in_buffer = dest->free_in_buffer;
  219. return TRUE;
  220. }
  221. /* Outputting bits to the file */
  222. /* Only the right 24 bits of put_buffer are used; the valid bits are
  223. * left-justified in this part. At most 16 bits can be passed to emit_bits
  224. * in one call, and we never retain more than 7 bits in put_buffer
  225. * between calls, so 24 bits are sufficient.
  226. */
  227. INLINE
  228. LOCAL boolean
  229. emit_bits (working_state * state, unsigned int code, int size)
  230. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  231. {
  232. /* This routine is heavily used, so it's worth coding tightly. */
  233. register INT32 put_buffer = (INT32) code;
  234. register int put_bits = state->cur.put_bits;
  235. /* if size is 0, caller used an invalid Huffman table entry */
  236. if (size == 0)
  237. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  238. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  239. put_bits += size; /* new number of bits in buffer */
  240. put_buffer <<= 24 - put_bits; /* align incoming bits */
  241. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  242. while (put_bits >= 8) {
  243. int c = (int) ((put_buffer >> 16) & 0xFF);
  244. emit_byte(state, c, return FALSE);
  245. if (c == 0xFF) { /* need to stuff a zero byte? */
  246. emit_byte(state, 0, return FALSE);
  247. }
  248. put_buffer <<= 8;
  249. put_bits -= 8;
  250. }
  251. state->cur.put_buffer = put_buffer; /* update state variables */
  252. state->cur.put_bits = put_bits;
  253. return TRUE;
  254. }
  255. LOCAL boolean
  256. flush_bits (working_state * state)
  257. {
  258. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  259. return FALSE;
  260. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  261. state->cur.put_bits = 0;
  262. return TRUE;
  263. }
  264. /* Encode a single block's worth of coefficients */
  265. LOCAL boolean
  266. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  267. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  268. {
  269. register int temp, temp2;
  270. register int nbits;
  271. register int k, r, i;
  272. /* Encode the DC coefficient difference per section F.1.2.1 */
  273. temp = temp2 = block[0] - last_dc_val;
  274. if (temp < 0) {
  275. temp = -temp; /* temp is abs value of input */
  276. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  277. /* This code assumes we are on a two's complement machine */
  278. temp2--;
  279. }
  280. /* Find the number of bits needed for the magnitude of the coefficient */
  281. nbits = 0;
  282. while (temp) {
  283. nbits++;
  284. temp >>= 1;
  285. }
  286. /* Emit the Huffman-coded symbol for the number of bits */
  287. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  288. return FALSE;
  289. /* Emit that number of bits of the value, if positive, */
  290. /* or the complement of its magnitude, if negative. */
  291. if (nbits) /* emit_bits rejects calls with size 0 */
  292. if (! emit_bits(state, (unsigned int) temp2, nbits))
  293. return FALSE;
  294. /* Encode the AC coefficients per section F.1.2.2 */
  295. r = 0; /* r = run length of zeros */
  296. for (k = 1; k < DCTSIZE2; k++) {
  297. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  298. r++;
  299. } else {
  300. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  301. while (r > 15) {
  302. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  303. return FALSE;
  304. r -= 16;
  305. }
  306. temp2 = temp;
  307. if (temp < 0) {
  308. temp = -temp; /* temp is abs value of input */
  309. /* This code assumes we are on a two's complement machine */
  310. temp2--;
  311. }
  312. /* Find the number of bits needed for the magnitude of the coefficient */
  313. nbits = 1; /* there must be at least one 1 bit */
  314. while ((temp >>= 1))
  315. nbits++;
  316. /* Emit Huffman symbol for run length / number of bits */
  317. i = (r << 4) + nbits;
  318. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  319. return FALSE;
  320. /* Emit that number of bits of the value, if positive, */
  321. /* or the complement of its magnitude, if negative. */
  322. if (! emit_bits(state, (unsigned int) temp2, nbits))
  323. return FALSE;
  324. r = 0;
  325. }
  326. }
  327. /* If the last coef(s) were zero, emit an end-of-block code */
  328. if (r > 0)
  329. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  330. return FALSE;
  331. return TRUE;
  332. }
  333. /*
  334. * Emit a restart marker & resynchronize predictions.
  335. */
  336. LOCAL boolean
  337. emit_restart (working_state * state, int restart_num)
  338. {
  339. int ci;
  340. if (! flush_bits(state))
  341. return FALSE;
  342. emit_byte(state, 0xFF, return FALSE);
  343. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  344. /* Re-initialize DC predictions to 0 */
  345. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  346. state->cur.last_dc_val[ci] = 0;
  347. /* The restart counter is not updated until we successfully write the MCU. */
  348. return TRUE;
  349. }
  350. /*
  351. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  352. */
  353. METHODDEF boolean
  354. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  355. {
  356. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  357. working_state state;
  358. int blkn, ci;
  359. jpeg_component_info * compptr;
  360. /* Load up working state */
  361. state.next_output_byte = cinfo->dest->next_output_byte;
  362. state.free_in_buffer = cinfo->dest->free_in_buffer;
  363. ASSIGN_STATE(state.cur, entropy->saved);
  364. state.cinfo = cinfo;
  365. /* Emit restart marker if needed */
  366. if (cinfo->restart_interval) {
  367. if (entropy->restarts_to_go == 0)
  368. if (! emit_restart(&state, entropy->next_restart_num))
  369. return FALSE;
  370. }
  371. /* Encode the MCU data blocks */
  372. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  373. ci = cinfo->MCU_membership[blkn];
  374. compptr = cinfo->cur_comp_info[ci];
  375. if (! encode_one_block(&state,
  376. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  377. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  378. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  379. return FALSE;
  380. /* Update last_dc_val */
  381. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  382. }
  383. /* Completed MCU, so update state */
  384. cinfo->dest->next_output_byte = state.next_output_byte;
  385. cinfo->dest->free_in_buffer = state.free_in_buffer;
  386. ASSIGN_STATE(entropy->saved, state.cur);
  387. /* Update restart-interval state too */
  388. if (cinfo->restart_interval) {
  389. if (entropy->restarts_to_go == 0) {
  390. entropy->restarts_to_go = cinfo->restart_interval;
  391. entropy->next_restart_num++;
  392. entropy->next_restart_num &= 7;
  393. }
  394. entropy->restarts_to_go--;
  395. }
  396. return TRUE;
  397. }
  398. /*
  399. * Finish up at the end of a Huffman-compressed scan.
  400. */
  401. METHODDEF void
  402. finish_pass_huff (j_compress_ptr cinfo)
  403. {
  404. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  405. working_state state;
  406. /* Load up working state ... flush_bits needs it */
  407. state.next_output_byte = cinfo->dest->next_output_byte;
  408. state.free_in_buffer = cinfo->dest->free_in_buffer;
  409. ASSIGN_STATE(state.cur, entropy->saved);
  410. state.cinfo = cinfo;
  411. /* Flush out the last data */
  412. if (! flush_bits(&state))
  413. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  414. /* Update state */
  415. cinfo->dest->next_output_byte = state.next_output_byte;
  416. cinfo->dest->free_in_buffer = state.free_in_buffer;
  417. ASSIGN_STATE(entropy->saved, state.cur);
  418. }
  419. /*
  420. * Huffman coding optimization.
  421. *
  422. * This actually is optimization, in the sense that we find the best possible
  423. * Huffman table(s) for the given data. We first scan the supplied data and
  424. * count the number of uses of each symbol that is to be Huffman-coded.
  425. * (This process must agree with the code above.) Then we build an
  426. * optimal Huffman coding tree for the observed counts.
  427. *
  428. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  429. * If some symbols have a very small but nonzero probability, the Huffman tree
  430. * must be adjusted to meet the code length restriction. We currently use
  431. * the adjustment method suggested in the JPEG spec. This method is *not*
  432. * optimal; it may not choose the best possible limited-length code. But
  433. * since the symbols involved are infrequently used, it's not clear that
  434. * going to extra trouble is worthwhile.
  435. */
  436. #ifdef ENTROPY_OPT_SUPPORTED
  437. /* Process a single block's worth of coefficients */
  438. LOCAL void
  439. htest_one_block (JCOEFPTR block, int last_dc_val,
  440. long dc_counts[], long ac_counts[])
  441. {
  442. register int temp;
  443. register int nbits;
  444. register int k, r;
  445. /* Encode the DC coefficient difference per section F.1.2.1 */
  446. temp = block[0] - last_dc_val;
  447. if (temp < 0)
  448. temp = -temp;
  449. /* Find the number of bits needed for the magnitude of the coefficient */
  450. nbits = 0;
  451. while (temp) {
  452. nbits++;
  453. temp >>= 1;
  454. }
  455. /* Count the Huffman symbol for the number of bits */
  456. dc_counts[nbits]++;
  457. /* Encode the AC coefficients per section F.1.2.2 */
  458. r = 0; /* r = run length of zeros */
  459. for (k = 1; k < DCTSIZE2; k++) {
  460. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  461. r++;
  462. } else {
  463. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  464. while (r > 15) {
  465. ac_counts[0xF0]++;
  466. r -= 16;
  467. }
  468. /* Find the number of bits needed for the magnitude of the coefficient */
  469. if (temp < 0)
  470. temp = -temp;
  471. /* Find the number of bits needed for the magnitude of the coefficient */
  472. nbits = 1; /* there must be at least one 1 bit */
  473. while ((temp >>= 1))
  474. nbits++;
  475. /* Count Huffman symbol for run length / number of bits */
  476. ac_counts[(r << 4) + nbits]++;
  477. r = 0;
  478. }
  479. }
  480. /* If the last coef(s) were zero, emit an end-of-block code */
  481. if (r > 0)
  482. ac_counts[0]++;
  483. }
  484. /*
  485. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  486. * No data is actually output, so no suspension return is possible.
  487. */
  488. METHODDEF boolean
  489. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  490. {
  491. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  492. int blkn, ci;
  493. jpeg_component_info * compptr;
  494. /* Take care of restart intervals if needed */
  495. if (cinfo->restart_interval) {
  496. if (entropy->restarts_to_go == 0) {
  497. /* Re-initialize DC predictions to 0 */
  498. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  499. entropy->saved.last_dc_val[ci] = 0;
  500. /* Update restart state */
  501. entropy->restarts_to_go = cinfo->restart_interval;
  502. }
  503. entropy->restarts_to_go--;
  504. }
  505. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  506. ci = cinfo->MCU_membership[blkn];
  507. compptr = cinfo->cur_comp_info[ci];
  508. htest_one_block(MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  509. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  510. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  511. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  512. }
  513. return TRUE;
  514. }
  515. /*
  516. * Generate the optimal coding for the given counts, fill htbl.
  517. * Note this is also used by jcphuff.c.
  518. */
  519. GLOBAL void
  520. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  521. {
  522. #define MAX_CLEN 32 /* assumed maximum initial code length */
  523. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  524. int codesize[257]; /* codesize[k] = code length of symbol k */
  525. int others[257]; /* next symbol in current branch of tree */
  526. int c1, c2;
  527. int p, i, j;
  528. long v;
  529. /* This algorithm is explained in section K.2 of the JPEG standard */
  530. MEMZERO(bits, SIZEOF(bits));
  531. MEMZERO(codesize, SIZEOF(codesize));
  532. for (i = 0; i < 257; i++)
  533. others[i] = -1; /* init links to empty */
  534. freq[256] = 1; /* make sure there is a nonzero count */
  535. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  536. * that no real symbol is given code-value of all ones, because 256
  537. * will be placed in the largest codeword category.
  538. */
  539. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  540. for (;;) {
  541. /* Find the smallest nonzero frequency, set c1 = its symbol */
  542. /* In case of ties, take the larger symbol number */
  543. c1 = -1;
  544. v = 1000000000L;
  545. for (i = 0; i <= 256; i++) {
  546. if (freq[i] && freq[i] <= v) {
  547. v = freq[i];
  548. c1 = i;
  549. }
  550. }
  551. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  552. /* In case of ties, take the larger symbol number */
  553. c2 = -1;
  554. v = 1000000000L;
  555. for (i = 0; i <= 256; i++) {
  556. if (freq[i] && freq[i] <= v && i != c1) {
  557. v = freq[i];
  558. c2 = i;
  559. }
  560. }
  561. /* Done if we've merged everything into one frequency */
  562. if (c2 < 0)
  563. break;
  564. /* Else merge the two counts/trees */
  565. freq[c1] += freq[c2];
  566. freq[c2] = 0;
  567. /* Increment the codesize of everything in c1's tree branch */
  568. codesize[c1]++;
  569. while (others[c1] >= 0) {
  570. c1 = others[c1];
  571. codesize[c1]++;
  572. }
  573. others[c1] = c2; /* chain c2 onto c1's tree branch */
  574. /* Increment the codesize of everything in c2's tree branch */
  575. codesize[c2]++;
  576. while (others[c2] >= 0) {
  577. c2 = others[c2];
  578. codesize[c2]++;
  579. }
  580. }
  581. /* Now count the number of symbols of each code length */
  582. for (i = 0; i <= 256; i++) {
  583. if (codesize[i]) {
  584. /* The JPEG standard seems to think that this can't happen, */
  585. /* but I'm paranoid... */
  586. if (codesize[i] > MAX_CLEN)
  587. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  588. bits[codesize[i]]++;
  589. }
  590. }
  591. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  592. * Huffman procedure assigned any such lengths, we must adjust the coding.
  593. * Here is what the JPEG spec says about how this next bit works:
  594. * Since symbols are paired for the longest Huffman code, the symbols are
  595. * removed from this length category two at a time. The prefix for the pair
  596. * (which is one bit shorter) is allocated to one of the pair; then,
  597. * skipping the BITS entry for that prefix length, a code word from the next
  598. * shortest nonzero BITS entry is converted into a prefix for two code words
  599. * one bit longer.
  600. */
  601. for (i = MAX_CLEN; i > 16; i--) {
  602. while (bits[i] > 0) {
  603. j = i - 2; /* find length of new prefix to be used */
  604. while (bits[j] == 0)
  605. j--;
  606. bits[i] -= 2; /* remove two symbols */
  607. bits[i-1]++; /* one goes in this length */
  608. bits[j+1] += 2; /* two new symbols in this length */
  609. bits[j]--; /* symbol of this length is now a prefix */
  610. }
  611. }
  612. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  613. while (bits[i] == 0) /* find largest codelength still in use */
  614. i--;
  615. bits[i]--;
  616. /* Return final symbol counts (only for lengths 0..16) */
  617. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  618. /* Return a list of the symbols sorted by code length */
  619. /* It's not real clear to me why we don't need to consider the codelength
  620. * changes made above, but the JPEG spec seems to think this works.
  621. */
  622. p = 0;
  623. for (i = 1; i <= MAX_CLEN; i++) {
  624. for (j = 0; j <= 255; j++) {
  625. if (codesize[j] == i) {
  626. htbl->huffval[p] = (UINT8) j;
  627. p++;
  628. }
  629. }
  630. }
  631. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  632. htbl->sent_table = FALSE;
  633. }
  634. /*
  635. * Finish up a statistics-gathering pass and create the new Huffman tables.
  636. */
  637. METHODDEF void
  638. finish_pass_gather (j_compress_ptr cinfo)
  639. {
  640. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  641. int ci, dctbl, actbl;
  642. jpeg_component_info * compptr;
  643. JHUFF_TBL **htblptr;
  644. boolean did_dc[NUM_HUFF_TBLS];
  645. boolean did_ac[NUM_HUFF_TBLS];
  646. /* It's important not to apply jpeg_gen_optimal_table more than once
  647. * per table, because it clobbers the input frequency counts!
  648. */
  649. MEMZERO(did_dc, SIZEOF(did_dc));
  650. MEMZERO(did_ac, SIZEOF(did_ac));
  651. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  652. compptr = cinfo->cur_comp_info[ci];
  653. dctbl = compptr->dc_tbl_no;
  654. actbl = compptr->ac_tbl_no;
  655. if (! did_dc[dctbl]) {
  656. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  657. if (*htblptr == NULL)
  658. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  659. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  660. did_dc[dctbl] = TRUE;
  661. }
  662. if (! did_ac[actbl]) {
  663. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  664. if (*htblptr == NULL)
  665. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  666. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  667. did_ac[actbl] = TRUE;
  668. }
  669. }
  670. }
  671. #endif /* ENTROPY_OPT_SUPPORTED */
  672. /*
  673. * Module initialization routine for Huffman entropy encoding.
  674. */
  675. GLOBAL void
  676. jinit_huff_encoder (j_compress_ptr cinfo)
  677. {
  678. huff_entropy_ptr entropy;
  679. int i;
  680. entropy = (huff_entropy_ptr)
  681. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  682. SIZEOF(huff_entropy_encoder));
  683. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  684. entropy->pub.start_pass = start_pass_huff;
  685. /* Mark tables unallocated */
  686. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  687. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  688. #ifdef ENTROPY_OPT_SUPPORTED
  689. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  690. #endif
  691. }
  692. }