jcphuff.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  1. /*
  2. * jcphuff.c
  3. *
  4. * This file was part of the Independent JPEG Group's software:
  5. * Copyright (C) 1995-1997, Thomas G. Lane.
  6. * libjpeg-turbo Modifications:
  7. * Copyright (C) 2015, D. R. Commander.
  8. * For conditions of distribution and use, see the accompanying README.ijg
  9. * file.
  10. *
  11. * This file contains Huffman entropy encoding routines for progressive JPEG.
  12. *
  13. * We do not support output suspension in this module, since the library
  14. * currently does not allow multiple-scan files to be written with output
  15. * suspension.
  16. */
  17. #define JPEG_INTERNALS
  18. #include "jinclude.h"
  19. #include "jpeglib.h"
  20. #include "jchuff.h" /* Declarations shared with jchuff.c */
  21. #ifdef C_PROGRESSIVE_SUPPORTED
  22. /* Expanded entropy encoder object for progressive Huffman encoding. */
  23. typedef struct {
  24. struct jpeg_entropy_encoder pub; /* public fields */
  25. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  26. boolean gather_statistics;
  27. /* Bit-level coding status.
  28. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  29. */
  30. JOCTET *next_output_byte; /* => next byte to write in buffer */
  31. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  32. size_t put_buffer; /* current bit-accumulation buffer */
  33. int put_bits; /* # of bits now in it */
  34. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  35. /* Coding status for DC components */
  36. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  37. /* Coding status for AC components */
  38. int ac_tbl_no; /* the table number of the single component */
  39. unsigned int EOBRUN; /* run length of EOBs */
  40. unsigned int BE; /* # of buffered correction bits before MCU */
  41. char *bit_buffer; /* buffer for correction bits (1 per char) */
  42. /* packing correction bits tightly would save some space but cost time... */
  43. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  44. int next_restart_num; /* next restart number to write (0-7) */
  45. /* Pointers to derived tables (these workspaces have image lifespan).
  46. * Since any one scan codes only DC or only AC, we only need one set
  47. * of tables, not one for DC and one for AC.
  48. */
  49. c_derived_tbl *derived_tbls[NUM_HUFF_TBLS];
  50. /* Statistics tables for optimization; again, one set is enough */
  51. long *count_ptrs[NUM_HUFF_TBLS];
  52. } phuff_entropy_encoder;
  53. typedef phuff_entropy_encoder *phuff_entropy_ptr;
  54. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  55. * buffer can hold. Larger sizes may slightly improve compression, but
  56. * 1000 is already well into the realm of overkill.
  57. * The minimum safe size is 64 bits.
  58. */
  59. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  60. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than JLONG.
  61. * We assume that int right shift is unsigned if JLONG right shift is,
  62. * which should be safe.
  63. */
  64. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  65. #define ISHIFT_TEMPS int ishift_temp;
  66. #define IRIGHT_SHIFT(x,shft) \
  67. ((ishift_temp = (x)) < 0 ? \
  68. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  69. (ishift_temp >> (shft)))
  70. #else
  71. #define ISHIFT_TEMPS
  72. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  73. #endif
  74. /* Forward declarations */
  75. METHODDEF(boolean) encode_mcu_DC_first (j_compress_ptr cinfo,
  76. JBLOCKROW *MCU_data);
  77. METHODDEF(boolean) encode_mcu_AC_first (j_compress_ptr cinfo,
  78. JBLOCKROW *MCU_data);
  79. METHODDEF(boolean) encode_mcu_DC_refine (j_compress_ptr cinfo,
  80. JBLOCKROW *MCU_data);
  81. METHODDEF(boolean) encode_mcu_AC_refine (j_compress_ptr cinfo,
  82. JBLOCKROW *MCU_data);
  83. METHODDEF(void) finish_pass_phuff (j_compress_ptr cinfo);
  84. METHODDEF(void) finish_pass_gather_phuff (j_compress_ptr cinfo);
  85. /*
  86. * Initialize for a Huffman-compressed scan using progressive JPEG.
  87. */
  88. METHODDEF(void)
  89. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  90. {
  91. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  92. boolean is_DC_band;
  93. int ci, tbl;
  94. jpeg_component_info *compptr;
  95. entropy->cinfo = cinfo;
  96. entropy->gather_statistics = gather_statistics;
  97. is_DC_band = (cinfo->Ss == 0);
  98. /* We assume jcmaster.c already validated the scan parameters. */
  99. /* Select execution routines */
  100. if (cinfo->Ah == 0) {
  101. if (is_DC_band)
  102. entropy->pub.encode_mcu = encode_mcu_DC_first;
  103. else
  104. entropy->pub.encode_mcu = encode_mcu_AC_first;
  105. } else {
  106. if (is_DC_band)
  107. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  108. else {
  109. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  110. /* AC refinement needs a correction bit buffer */
  111. if (entropy->bit_buffer == NULL)
  112. entropy->bit_buffer = (char *)
  113. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  114. MAX_CORR_BITS * sizeof(char));
  115. }
  116. }
  117. if (gather_statistics)
  118. entropy->pub.finish_pass = finish_pass_gather_phuff;
  119. else
  120. entropy->pub.finish_pass = finish_pass_phuff;
  121. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  122. * for AC coefficients.
  123. */
  124. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  125. compptr = cinfo->cur_comp_info[ci];
  126. /* Initialize DC predictions to 0 */
  127. entropy->last_dc_val[ci] = 0;
  128. /* Get table index */
  129. if (is_DC_band) {
  130. if (cinfo->Ah != 0) /* DC refinement needs no table */
  131. continue;
  132. tbl = compptr->dc_tbl_no;
  133. } else {
  134. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  135. }
  136. if (gather_statistics) {
  137. /* Check for invalid table index */
  138. /* (make_c_derived_tbl does this in the other path) */
  139. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  140. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  141. /* Allocate and zero the statistics tables */
  142. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  143. if (entropy->count_ptrs[tbl] == NULL)
  144. entropy->count_ptrs[tbl] = (long *)
  145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  146. 257 * sizeof(long));
  147. MEMZERO(entropy->count_ptrs[tbl], 257 * sizeof(long));
  148. } else {
  149. /* Compute derived values for Huffman table */
  150. /* We may do this more than once for a table, but it's not expensive */
  151. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  152. & entropy->derived_tbls[tbl]);
  153. }
  154. }
  155. /* Initialize AC stuff */
  156. entropy->EOBRUN = 0;
  157. entropy->BE = 0;
  158. /* Initialize bit buffer to empty */
  159. entropy->put_buffer = 0;
  160. entropy->put_bits = 0;
  161. /* Initialize restart stuff */
  162. entropy->restarts_to_go = cinfo->restart_interval;
  163. entropy->next_restart_num = 0;
  164. }
  165. /* Outputting bytes to the file.
  166. * NB: these must be called only when actually outputting,
  167. * that is, entropy->gather_statistics == FALSE.
  168. */
  169. /* Emit a byte */
  170. #define emit_byte(entropy,val) \
  171. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  172. if (--(entropy)->free_in_buffer == 0) \
  173. dump_buffer(entropy); }
  174. LOCAL(void)
  175. dump_buffer (phuff_entropy_ptr entropy)
  176. /* Empty the output buffer; we do not support suspension in this module. */
  177. {
  178. struct jpeg_destination_mgr *dest = entropy->cinfo->dest;
  179. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  180. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  181. /* After a successful buffer dump, must reset buffer pointers */
  182. entropy->next_output_byte = dest->next_output_byte;
  183. entropy->free_in_buffer = dest->free_in_buffer;
  184. }
  185. /* Outputting bits to the file */
  186. /* Only the right 24 bits of put_buffer are used; the valid bits are
  187. * left-justified in this part. At most 16 bits can be passed to emit_bits
  188. * in one call, and we never retain more than 7 bits in put_buffer
  189. * between calls, so 24 bits are sufficient.
  190. */
  191. LOCAL(void)
  192. emit_bits (phuff_entropy_ptr entropy, unsigned int code, int size)
  193. /* Emit some bits, unless we are in gather mode */
  194. {
  195. /* This routine is heavily used, so it's worth coding tightly. */
  196. register size_t put_buffer = (size_t) code;
  197. register int put_bits = entropy->put_bits;
  198. /* if size is 0, caller used an invalid Huffman table entry */
  199. if (size == 0)
  200. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  201. if (entropy->gather_statistics)
  202. return; /* do nothing if we're only getting stats */
  203. put_buffer &= (((size_t) 1)<<size) - 1; /* mask off any extra bits in code */
  204. put_bits += size; /* new number of bits in buffer */
  205. put_buffer <<= 24 - put_bits; /* align incoming bits */
  206. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  207. while (put_bits >= 8) {
  208. int c = (int) ((put_buffer >> 16) & 0xFF);
  209. emit_byte(entropy, c);
  210. if (c == 0xFF) { /* need to stuff a zero byte? */
  211. emit_byte(entropy, 0);
  212. }
  213. put_buffer <<= 8;
  214. put_bits -= 8;
  215. }
  216. entropy->put_buffer = put_buffer; /* update variables */
  217. entropy->put_bits = put_bits;
  218. }
  219. LOCAL(void)
  220. flush_bits (phuff_entropy_ptr entropy)
  221. {
  222. emit_bits(entropy, 0x7F, 7); /* fill any partial byte with ones */
  223. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  224. entropy->put_bits = 0;
  225. }
  226. /*
  227. * Emit (or just count) a Huffman symbol.
  228. */
  229. LOCAL(void)
  230. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  231. {
  232. if (entropy->gather_statistics)
  233. entropy->count_ptrs[tbl_no][symbol]++;
  234. else {
  235. c_derived_tbl *tbl = entropy->derived_tbls[tbl_no];
  236. emit_bits(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  237. }
  238. }
  239. /*
  240. * Emit bits from a correction bit buffer.
  241. */
  242. LOCAL(void)
  243. emit_buffered_bits (phuff_entropy_ptr entropy, char *bufstart,
  244. unsigned int nbits)
  245. {
  246. if (entropy->gather_statistics)
  247. return; /* no real work */
  248. while (nbits > 0) {
  249. emit_bits(entropy, (unsigned int) (*bufstart), 1);
  250. bufstart++;
  251. nbits--;
  252. }
  253. }
  254. /*
  255. * Emit any pending EOBRUN symbol.
  256. */
  257. LOCAL(void)
  258. emit_eobrun (phuff_entropy_ptr entropy)
  259. {
  260. register int temp, nbits;
  261. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  262. temp = entropy->EOBRUN;
  263. nbits = 0;
  264. while ((temp >>= 1))
  265. nbits++;
  266. /* safety check: shouldn't happen given limited correction-bit buffer */
  267. if (nbits > 14)
  268. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  269. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  270. if (nbits)
  271. emit_bits(entropy, entropy->EOBRUN, nbits);
  272. entropy->EOBRUN = 0;
  273. /* Emit any buffered correction bits */
  274. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  275. entropy->BE = 0;
  276. }
  277. }
  278. /*
  279. * Emit a restart marker & resynchronize predictions.
  280. */
  281. LOCAL(void)
  282. emit_restart (phuff_entropy_ptr entropy, int restart_num)
  283. {
  284. int ci;
  285. emit_eobrun(entropy);
  286. if (! entropy->gather_statistics) {
  287. flush_bits(entropy);
  288. emit_byte(entropy, 0xFF);
  289. emit_byte(entropy, JPEG_RST0 + restart_num);
  290. }
  291. if (entropy->cinfo->Ss == 0) {
  292. /* Re-initialize DC predictions to 0 */
  293. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  294. entropy->last_dc_val[ci] = 0;
  295. } else {
  296. /* Re-initialize all AC-related fields to 0 */
  297. entropy->EOBRUN = 0;
  298. entropy->BE = 0;
  299. }
  300. }
  301. /*
  302. * MCU encoding for DC initial scan (either spectral selection,
  303. * or first pass of successive approximation).
  304. */
  305. METHODDEF(boolean)
  306. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  307. {
  308. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  309. register int temp, temp2;
  310. register int nbits;
  311. int blkn, ci;
  312. int Al = cinfo->Al;
  313. JBLOCKROW block;
  314. jpeg_component_info *compptr;
  315. ISHIFT_TEMPS
  316. entropy->next_output_byte = cinfo->dest->next_output_byte;
  317. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  318. /* Emit restart marker if needed */
  319. if (cinfo->restart_interval)
  320. if (entropy->restarts_to_go == 0)
  321. emit_restart(entropy, entropy->next_restart_num);
  322. /* Encode the MCU data blocks */
  323. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  324. block = MCU_data[blkn];
  325. ci = cinfo->MCU_membership[blkn];
  326. compptr = cinfo->cur_comp_info[ci];
  327. /* Compute the DC value after the required point transform by Al.
  328. * This is simply an arithmetic right shift.
  329. */
  330. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  331. /* DC differences are figured on the point-transformed values. */
  332. temp = temp2 - entropy->last_dc_val[ci];
  333. entropy->last_dc_val[ci] = temp2;
  334. /* Encode the DC coefficient difference per section G.1.2.1 */
  335. temp2 = temp;
  336. if (temp < 0) {
  337. temp = -temp; /* temp is abs value of input */
  338. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  339. /* This code assumes we are on a two's complement machine */
  340. temp2--;
  341. }
  342. /* Find the number of bits needed for the magnitude of the coefficient */
  343. nbits = 0;
  344. while (temp) {
  345. nbits++;
  346. temp >>= 1;
  347. }
  348. /* Check for out-of-range coefficient values.
  349. * Since we're encoding a difference, the range limit is twice as much.
  350. */
  351. if (nbits > MAX_COEF_BITS+1)
  352. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  353. /* Count/emit the Huffman-coded symbol for the number of bits */
  354. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  355. /* Emit that number of bits of the value, if positive, */
  356. /* or the complement of its magnitude, if negative. */
  357. if (nbits) /* emit_bits rejects calls with size 0 */
  358. emit_bits(entropy, (unsigned int) temp2, nbits);
  359. }
  360. cinfo->dest->next_output_byte = entropy->next_output_byte;
  361. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  362. /* Update restart-interval state too */
  363. if (cinfo->restart_interval) {
  364. if (entropy->restarts_to_go == 0) {
  365. entropy->restarts_to_go = cinfo->restart_interval;
  366. entropy->next_restart_num++;
  367. entropy->next_restart_num &= 7;
  368. }
  369. entropy->restarts_to_go--;
  370. }
  371. return TRUE;
  372. }
  373. /*
  374. * MCU encoding for AC initial scan (either spectral selection,
  375. * or first pass of successive approximation).
  376. */
  377. METHODDEF(boolean)
  378. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  379. {
  380. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  381. register int temp, temp2;
  382. register int nbits;
  383. register int r, k;
  384. int Se = cinfo->Se;
  385. int Al = cinfo->Al;
  386. JBLOCKROW block;
  387. entropy->next_output_byte = cinfo->dest->next_output_byte;
  388. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  389. /* Emit restart marker if needed */
  390. if (cinfo->restart_interval)
  391. if (entropy->restarts_to_go == 0)
  392. emit_restart(entropy, entropy->next_restart_num);
  393. /* Encode the MCU data block */
  394. block = MCU_data[0];
  395. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  396. r = 0; /* r = run length of zeros */
  397. for (k = cinfo->Ss; k <= Se; k++) {
  398. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  399. r++;
  400. continue;
  401. }
  402. /* We must apply the point transform by Al. For AC coefficients this
  403. * is an integer division with rounding towards 0. To do this portably
  404. * in C, we shift after obtaining the absolute value; so the code is
  405. * interwoven with finding the abs value (temp) and output bits (temp2).
  406. */
  407. if (temp < 0) {
  408. temp = -temp; /* temp is abs value of input */
  409. temp >>= Al; /* apply the point transform */
  410. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  411. temp2 = ~temp;
  412. } else {
  413. temp >>= Al; /* apply the point transform */
  414. temp2 = temp;
  415. }
  416. /* Watch out for case that nonzero coef is zero after point transform */
  417. if (temp == 0) {
  418. r++;
  419. continue;
  420. }
  421. /* Emit any pending EOBRUN */
  422. if (entropy->EOBRUN > 0)
  423. emit_eobrun(entropy);
  424. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  425. while (r > 15) {
  426. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  427. r -= 16;
  428. }
  429. /* Find the number of bits needed for the magnitude of the coefficient */
  430. nbits = 1; /* there must be at least one 1 bit */
  431. while ((temp >>= 1))
  432. nbits++;
  433. /* Check for out-of-range coefficient values */
  434. if (nbits > MAX_COEF_BITS)
  435. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  436. /* Count/emit Huffman symbol for run length / number of bits */
  437. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  438. /* Emit that number of bits of the value, if positive, */
  439. /* or the complement of its magnitude, if negative. */
  440. emit_bits(entropy, (unsigned int) temp2, nbits);
  441. r = 0; /* reset zero run length */
  442. }
  443. if (r > 0) { /* If there are trailing zeroes, */
  444. entropy->EOBRUN++; /* count an EOB */
  445. if (entropy->EOBRUN == 0x7FFF)
  446. emit_eobrun(entropy); /* force it out to avoid overflow */
  447. }
  448. cinfo->dest->next_output_byte = entropy->next_output_byte;
  449. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  450. /* Update restart-interval state too */
  451. if (cinfo->restart_interval) {
  452. if (entropy->restarts_to_go == 0) {
  453. entropy->restarts_to_go = cinfo->restart_interval;
  454. entropy->next_restart_num++;
  455. entropy->next_restart_num &= 7;
  456. }
  457. entropy->restarts_to_go--;
  458. }
  459. return TRUE;
  460. }
  461. /*
  462. * MCU encoding for DC successive approximation refinement scan.
  463. * Note: we assume such scans can be multi-component, although the spec
  464. * is not very clear on the point.
  465. */
  466. METHODDEF(boolean)
  467. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  468. {
  469. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  470. register int temp;
  471. int blkn;
  472. int Al = cinfo->Al;
  473. JBLOCKROW block;
  474. entropy->next_output_byte = cinfo->dest->next_output_byte;
  475. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  476. /* Emit restart marker if needed */
  477. if (cinfo->restart_interval)
  478. if (entropy->restarts_to_go == 0)
  479. emit_restart(entropy, entropy->next_restart_num);
  480. /* Encode the MCU data blocks */
  481. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  482. block = MCU_data[blkn];
  483. /* We simply emit the Al'th bit of the DC coefficient value. */
  484. temp = (*block)[0];
  485. emit_bits(entropy, (unsigned int) (temp >> Al), 1);
  486. }
  487. cinfo->dest->next_output_byte = entropy->next_output_byte;
  488. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  489. /* Update restart-interval state too */
  490. if (cinfo->restart_interval) {
  491. if (entropy->restarts_to_go == 0) {
  492. entropy->restarts_to_go = cinfo->restart_interval;
  493. entropy->next_restart_num++;
  494. entropy->next_restart_num &= 7;
  495. }
  496. entropy->restarts_to_go--;
  497. }
  498. return TRUE;
  499. }
  500. /*
  501. * MCU encoding for AC successive approximation refinement scan.
  502. */
  503. METHODDEF(boolean)
  504. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  505. {
  506. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  507. register int temp;
  508. register int r, k;
  509. int EOB;
  510. char *BR_buffer;
  511. unsigned int BR;
  512. int Se = cinfo->Se;
  513. int Al = cinfo->Al;
  514. JBLOCKROW block;
  515. int absvalues[DCTSIZE2];
  516. entropy->next_output_byte = cinfo->dest->next_output_byte;
  517. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  518. /* Emit restart marker if needed */
  519. if (cinfo->restart_interval)
  520. if (entropy->restarts_to_go == 0)
  521. emit_restart(entropy, entropy->next_restart_num);
  522. /* Encode the MCU data block */
  523. block = MCU_data[0];
  524. /* It is convenient to make a pre-pass to determine the transformed
  525. * coefficients' absolute values and the EOB position.
  526. */
  527. EOB = 0;
  528. for (k = cinfo->Ss; k <= Se; k++) {
  529. temp = (*block)[jpeg_natural_order[k]];
  530. /* We must apply the point transform by Al. For AC coefficients this
  531. * is an integer division with rounding towards 0. To do this portably
  532. * in C, we shift after obtaining the absolute value.
  533. */
  534. if (temp < 0)
  535. temp = -temp; /* temp is abs value of input */
  536. temp >>= Al; /* apply the point transform */
  537. absvalues[k] = temp; /* save abs value for main pass */
  538. if (temp == 1)
  539. EOB = k; /* EOB = index of last newly-nonzero coef */
  540. }
  541. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  542. r = 0; /* r = run length of zeros */
  543. BR = 0; /* BR = count of buffered bits added now */
  544. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  545. for (k = cinfo->Ss; k <= Se; k++) {
  546. if ((temp = absvalues[k]) == 0) {
  547. r++;
  548. continue;
  549. }
  550. /* Emit any required ZRLs, but not if they can be folded into EOB */
  551. while (r > 15 && k <= EOB) {
  552. /* emit any pending EOBRUN and the BE correction bits */
  553. emit_eobrun(entropy);
  554. /* Emit ZRL */
  555. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  556. r -= 16;
  557. /* Emit buffered correction bits that must be associated with ZRL */
  558. emit_buffered_bits(entropy, BR_buffer, BR);
  559. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  560. BR = 0;
  561. }
  562. /* If the coef was previously nonzero, it only needs a correction bit.
  563. * NOTE: a straight translation of the spec's figure G.7 would suggest
  564. * that we also need to test r > 15. But if r > 15, we can only get here
  565. * if k > EOB, which implies that this coefficient is not 1.
  566. */
  567. if (temp > 1) {
  568. /* The correction bit is the next bit of the absolute value. */
  569. BR_buffer[BR++] = (char) (temp & 1);
  570. continue;
  571. }
  572. /* Emit any pending EOBRUN and the BE correction bits */
  573. emit_eobrun(entropy);
  574. /* Count/emit Huffman symbol for run length / number of bits */
  575. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  576. /* Emit output bit for newly-nonzero coef */
  577. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  578. emit_bits(entropy, (unsigned int) temp, 1);
  579. /* Emit buffered correction bits that must be associated with this code */
  580. emit_buffered_bits(entropy, BR_buffer, BR);
  581. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  582. BR = 0;
  583. r = 0; /* reset zero run length */
  584. }
  585. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  586. entropy->EOBRUN++; /* count an EOB */
  587. entropy->BE += BR; /* concat my correction bits to older ones */
  588. /* We force out the EOB if we risk either:
  589. * 1. overflow of the EOB counter;
  590. * 2. overflow of the correction bit buffer during the next MCU.
  591. */
  592. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  593. emit_eobrun(entropy);
  594. }
  595. cinfo->dest->next_output_byte = entropy->next_output_byte;
  596. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  597. /* Update restart-interval state too */
  598. if (cinfo->restart_interval) {
  599. if (entropy->restarts_to_go == 0) {
  600. entropy->restarts_to_go = cinfo->restart_interval;
  601. entropy->next_restart_num++;
  602. entropy->next_restart_num &= 7;
  603. }
  604. entropy->restarts_to_go--;
  605. }
  606. return TRUE;
  607. }
  608. /*
  609. * Finish up at the end of a Huffman-compressed progressive scan.
  610. */
  611. METHODDEF(void)
  612. finish_pass_phuff (j_compress_ptr cinfo)
  613. {
  614. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  615. entropy->next_output_byte = cinfo->dest->next_output_byte;
  616. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  617. /* Flush out any buffered data */
  618. emit_eobrun(entropy);
  619. flush_bits(entropy);
  620. cinfo->dest->next_output_byte = entropy->next_output_byte;
  621. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  622. }
  623. /*
  624. * Finish up a statistics-gathering pass and create the new Huffman tables.
  625. */
  626. METHODDEF(void)
  627. finish_pass_gather_phuff (j_compress_ptr cinfo)
  628. {
  629. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  630. boolean is_DC_band;
  631. int ci, tbl;
  632. jpeg_component_info *compptr;
  633. JHUFF_TBL **htblptr;
  634. boolean did[NUM_HUFF_TBLS];
  635. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  636. emit_eobrun(entropy);
  637. is_DC_band = (cinfo->Ss == 0);
  638. /* It's important not to apply jpeg_gen_optimal_table more than once
  639. * per table, because it clobbers the input frequency counts!
  640. */
  641. MEMZERO(did, sizeof(did));
  642. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  643. compptr = cinfo->cur_comp_info[ci];
  644. if (is_DC_band) {
  645. if (cinfo->Ah != 0) /* DC refinement needs no table */
  646. continue;
  647. tbl = compptr->dc_tbl_no;
  648. } else {
  649. tbl = compptr->ac_tbl_no;
  650. }
  651. if (! did[tbl]) {
  652. if (is_DC_band)
  653. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  654. else
  655. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  656. if (*htblptr == NULL)
  657. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  658. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  659. did[tbl] = TRUE;
  660. }
  661. }
  662. }
  663. /*
  664. * Module initialization routine for progressive Huffman entropy encoding.
  665. */
  666. GLOBAL(void)
  667. jinit_phuff_encoder (j_compress_ptr cinfo)
  668. {
  669. phuff_entropy_ptr entropy;
  670. int i;
  671. entropy = (phuff_entropy_ptr)
  672. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  673. sizeof(phuff_entropy_encoder));
  674. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  675. entropy->pub.start_pass = start_pass_phuff;
  676. /* Mark tables unallocated */
  677. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  678. entropy->derived_tbls[i] = NULL;
  679. entropy->count_ptrs[i] = NULL;
  680. }
  681. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  682. }
  683. #endif /* C_PROGRESSIVE_SUPPORTED */