Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1576 lines
47 KiB

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