4 * Copyright (C) 1991-1998, 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.
8 * This file contains Huffman entropy encoding routines for sequential JPEG.
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.
17 #define JPEG_INTERNALS
20 #include "jlossy.h" /* Private declarations for lossy codec */
21 #include "jchuff.h" /* Declarations shared with jc*huff.c */
24 /* Expanded entropy encoder object for Huffman encoding.
26 * The savable_state subrecord contains fields that change within an MCU,
27 * but must not be updated permanently until we complete the MCU.
31 INT32 put_buffer; /* current bit-accumulation buffer */
32 int put_bits; /* # of bits now in it */
33 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
36 /* This macro is to work around compilers with missing or broken
37 * structure assignment. You'll need to fix this code if you have
38 * such a compiler and you change MAX_COMPS_IN_SCAN.
41 #ifndef NO_STRUCT_ASSIGN
42 #define ASSIGN_STATE(dest,src) ((dest) = (src))
44 #if MAX_COMPS_IN_SCAN == 4
45 #define ASSIGN_STATE(dest,src) \
46 ((dest).put_buffer = (src).put_buffer, \
47 (dest).put_bits = (src).put_bits, \
48 (dest).last_dc_val[0] = (src).last_dc_val[0], \
49 (dest).last_dc_val[1] = (src).last_dc_val[1], \
50 (dest).last_dc_val[2] = (src).last_dc_val[2], \
51 (dest).last_dc_val[3] = (src).last_dc_val[3])
57 savable_state saved; /* Bit buffer & DC state at start of MCU */
59 /* These fields are NOT loaded into local working state. */
60 unsigned int restarts_to_go; /* MCUs left in this restart interval */
61 int next_restart_num; /* next restart number to write (0-7) */
63 /* Pointers to derived tables (these workspaces have image lifespan) */
64 c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
65 c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
67 #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
68 long * dc_count_ptrs[NUM_HUFF_TBLS];
69 long * ac_count_ptrs[NUM_HUFF_TBLS];
71 } shuff_entropy_encoder;
73 typedef shuff_entropy_encoder * shuff_entropy_ptr;
75 /* Working state while writing an MCU.
76 * This struct contains all the fields that are needed by subroutines.
80 JOCTET * next_output_byte; /* => next byte to write in buffer */
81 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
82 savable_state cur; /* Current bit buffer & DC state */
83 j_compress_ptr cinfo; /* dump_buffer needs access to this */
87 /* Forward declarations */
88 METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
89 JBLOCKROW *MCU_data));
90 METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
91 #ifdef ENTROPY_OPT_SUPPORTED
92 METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
93 JBLOCKROW *MCU_data));
94 METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
99 * Initialize for a Huffman-compressed scan.
100 * If gather_statistics is TRUE, we do not output anything during the scan,
101 * just count the Huffman symbols used and generate Huffman code tables.
105 start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
107 j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
108 shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
109 int ci, dctbl, actbl;
110 jpeg_component_info * compptr;
112 if (gather_statistics) {
113 #ifdef ENTROPY_OPT_SUPPORTED
114 lossyc->entropy_encode_mcu = encode_mcu_gather;
115 lossyc->pub.entropy_finish_pass = finish_pass_gather;
117 ERREXIT(cinfo, JERR_NOT_COMPILED);
120 lossyc->entropy_encode_mcu = encode_mcu_huff;
121 lossyc->pub.entropy_finish_pass = finish_pass_huff;
124 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
125 compptr = cinfo->cur_comp_info[ci];
126 dctbl = compptr->dc_tbl_no;
127 actbl = compptr->ac_tbl_no;
128 if (gather_statistics) {
129 #ifdef ENTROPY_OPT_SUPPORTED
130 /* Check for invalid table indexes */
131 /* (make_c_derived_tbl does this in the other path) */
132 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
133 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
134 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
135 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
136 /* Allocate and zero the statistics tables */
137 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
138 if (entropy->dc_count_ptrs[dctbl] == NULL)
139 entropy->dc_count_ptrs[dctbl] = (long *)
140 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
142 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
143 if (entropy->ac_count_ptrs[actbl] == NULL)
144 entropy->ac_count_ptrs[actbl] = (long *)
145 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
147 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
150 /* Compute derived values for Huffman tables */
151 /* We may do this more than once for a table, but it's not expensive */
152 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
153 & entropy->dc_derived_tbls[dctbl]);
154 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
155 & entropy->ac_derived_tbls[actbl]);
157 /* Initialize DC predictions to 0 */
158 entropy->saved.last_dc_val[ci] = 0;
161 /* Initialize bit buffer to empty */
162 entropy->saved.put_buffer = 0;
163 entropy->saved.put_bits = 0;
165 /* Initialize restart stuff */
166 entropy->restarts_to_go = cinfo->restart_interval;
167 entropy->next_restart_num = 0;
171 /* Outputting bytes to the file */
173 /* Emit a byte, taking 'action' if must suspend. */
174 #define emit_byte(state,val,action) \
175 { *(state)->next_output_byte++ = (JOCTET) (val); \
176 if (--(state)->free_in_buffer == 0) \
177 if (! dump_buffer(state)) \
182 dump_buffer (working_state * state)
183 /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
185 struct jpeg_destination_mgr * dest = state->cinfo->dest;
187 if (! (*dest->empty_output_buffer) (state->cinfo))
189 /* After a successful buffer dump, must reset buffer pointers */
190 state->next_output_byte = dest->next_output_byte;
191 state->free_in_buffer = dest->free_in_buffer;
196 /* Outputting bits to the file */
198 /* Only the right 24 bits of put_buffer are used; the valid bits are
199 * left-justified in this part. At most 16 bits can be passed to emit_bits
200 * in one call, and we never retain more than 7 bits in put_buffer
201 * between calls, so 24 bits are sufficient.
206 emit_bits (working_state * state, unsigned int code, int size)
207 /* Emit some bits; return TRUE if successful, FALSE if must suspend */
209 /* This routine is heavily used, so it's worth coding tightly. */
210 register INT32 put_buffer = (INT32) code;
211 register int put_bits = state->cur.put_bits;
213 /* if size is 0, caller used an invalid Huffman table entry */
215 ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
217 put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
219 put_bits += size; /* new number of bits in buffer */
221 put_buffer <<= 24 - put_bits; /* align incoming bits */
223 put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
225 while (put_bits >= 8) {
226 int c = (int) ((put_buffer >> 16) & 0xFF);
228 emit_byte(state, c, return FALSE);
229 if (c == 0xFF) { /* need to stuff a zero byte? */
230 emit_byte(state, 0, return FALSE);
236 state->cur.put_buffer = put_buffer; /* update state variables */
237 state->cur.put_bits = put_bits;
244 flush_bits (working_state * state)
246 if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
248 state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
249 state->cur.put_bits = 0;
254 /* Encode a single block's worth of coefficients */
257 encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
258 c_derived_tbl *dctbl, c_derived_tbl *actbl)
260 register int temp, temp2;
262 register int k, r, i;
264 /* Encode the DC coefficient difference per section F.1.2.1 */
266 temp = temp2 = block[0] - last_dc_val;
269 temp = -temp; /* temp is abs value of input */
270 /* For a negative input, want temp2 = bitwise complement of abs(input) */
271 /* This code assumes we are on a two's complement machine */
275 /* Find the number of bits needed for the magnitude of the coefficient */
281 /* Check for out-of-range coefficient values.
282 * Since we're encoding a difference, the range limit is twice as much.
284 if (nbits > MAX_COEF_BITS+1)
285 ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
287 /* Emit the Huffman-coded symbol for the number of bits */
288 if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
291 /* Emit that number of bits of the value, if positive, */
292 /* or the complement of its magnitude, if negative. */
293 if (nbits) /* emit_bits rejects calls with size 0 */
294 if (! emit_bits(state, (unsigned int) temp2, nbits))
297 /* Encode the AC coefficients per section F.1.2.2 */
299 r = 0; /* r = run length of zeros */
301 for (k = 1; k < DCTSIZE2; k++) {
302 if ((temp = block[jpeg_natural_order[k]]) == 0) {
305 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
307 if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
314 temp = -temp; /* temp is abs value of input */
315 /* This code assumes we are on a two's complement machine */
319 /* Find the number of bits needed for the magnitude of the coefficient */
320 nbits = 1; /* there must be at least one 1 bit */
323 /* Check for out-of-range coefficient values */
324 if (nbits > MAX_COEF_BITS)
325 ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
327 /* Emit Huffman symbol for run length / number of bits */
328 i = (r << 4) + nbits;
329 if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
332 /* Emit that number of bits of the value, if positive, */
333 /* or the complement of its magnitude, if negative. */
334 if (! emit_bits(state, (unsigned int) temp2, nbits))
341 /* If the last coef(s) were zero, emit an end-of-block code */
343 if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
351 * Emit a restart marker & resynchronize predictions.
355 emit_restart (working_state * state, int restart_num)
359 if (! flush_bits(state))
362 emit_byte(state, 0xFF, return FALSE);
363 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
365 /* Re-initialize DC predictions to 0 */
366 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
367 state->cur.last_dc_val[ci] = 0;
369 /* The restart counter is not updated until we successfully write the MCU. */
376 * Encode and output one MCU's worth of Huffman-compressed coefficients.
380 encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
382 j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
383 shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
386 jpeg_component_info * compptr;
388 /* Load up working state */
389 state.next_output_byte = cinfo->dest->next_output_byte;
390 state.free_in_buffer = cinfo->dest->free_in_buffer;
391 ASSIGN_STATE(state.cur, entropy->saved);
394 /* Emit restart marker if needed */
395 if (cinfo->restart_interval) {
396 if (entropy->restarts_to_go == 0)
397 if (! emit_restart(&state, entropy->next_restart_num))
401 /* Encode the MCU data blocks */
402 for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
403 ci = cinfo->MCU_membership[blkn];
404 compptr = cinfo->cur_comp_info[ci];
405 if (! encode_one_block(&state,
406 MCU_data[blkn][0], state.cur.last_dc_val[ci],
407 entropy->dc_derived_tbls[compptr->dc_tbl_no],
408 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
410 /* Update last_dc_val */
411 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
414 /* Completed MCU, so 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);
419 /* Update restart-interval state too */
420 if (cinfo->restart_interval) {
421 if (entropy->restarts_to_go == 0) {
422 entropy->restarts_to_go = cinfo->restart_interval;
423 entropy->next_restart_num++;
424 entropy->next_restart_num &= 7;
426 entropy->restarts_to_go--;
434 * Finish up at the end of a Huffman-compressed scan.
438 finish_pass_huff (j_compress_ptr cinfo)
440 j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
441 shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
444 /* Load up working state ... flush_bits needs it */
445 state.next_output_byte = cinfo->dest->next_output_byte;
446 state.free_in_buffer = cinfo->dest->free_in_buffer;
447 ASSIGN_STATE(state.cur, entropy->saved);
450 /* Flush out the last data */
451 if (! flush_bits(&state))
452 ERREXIT(cinfo, JERR_CANT_SUSPEND);
455 cinfo->dest->next_output_byte = state.next_output_byte;
456 cinfo->dest->free_in_buffer = state.free_in_buffer;
457 ASSIGN_STATE(entropy->saved, state.cur);
462 * Huffman coding optimization.
464 * We first scan the supplied data and count the number of uses of each symbol
465 * that is to be Huffman-coded. (This process MUST agree with the code above.)
466 * Then we build a Huffman coding tree for the observed counts.
467 * Symbols which are not needed at all for the particular image are not
468 * assigned any code, which saves space in the DHT marker as well as in
469 * the compressed data.
472 #ifdef ENTROPY_OPT_SUPPORTED
475 /* Process a single block's worth of coefficients */
478 htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
479 long dc_counts[], long ac_counts[])
485 /* Encode the DC coefficient difference per section F.1.2.1 */
487 temp = block[0] - last_dc_val;
491 /* Find the number of bits needed for the magnitude of the coefficient */
497 /* Check for out-of-range coefficient values.
498 * Since we're encoding a difference, the range limit is twice as much.
500 if (nbits > MAX_COEF_BITS+1)
501 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
503 /* Count the Huffman symbol for the number of bits */
506 /* Encode the AC coefficients per section F.1.2.2 */
508 r = 0; /* r = run length of zeros */
510 for (k = 1; k < DCTSIZE2; k++) {
511 if ((temp = block[jpeg_natural_order[k]]) == 0) {
514 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
520 /* Find the number of bits needed for the magnitude of the coefficient */
524 /* Find the number of bits needed for the magnitude of the coefficient */
525 nbits = 1; /* there must be at least one 1 bit */
528 /* Check for out-of-range coefficient values */
529 if (nbits > MAX_COEF_BITS)
530 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
532 /* Count Huffman symbol for run length / number of bits */
533 ac_counts[(r << 4) + nbits]++;
539 /* If the last coef(s) were zero, emit an end-of-block code */
546 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
547 * No data is actually output, so no suspension return is possible.
551 encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
553 j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
554 shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
556 jpeg_component_info * compptr;
558 /* Take care of restart intervals if needed */
559 if (cinfo->restart_interval) {
560 if (entropy->restarts_to_go == 0) {
561 /* Re-initialize DC predictions to 0 */
562 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
563 entropy->saved.last_dc_val[ci] = 0;
564 /* Update restart state */
565 entropy->restarts_to_go = cinfo->restart_interval;
567 entropy->restarts_to_go--;
570 for (blkn = 0; blkn < cinfo->data_units_in_MCU; blkn++) {
571 ci = cinfo->MCU_membership[blkn];
572 compptr = cinfo->cur_comp_info[ci];
573 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
574 entropy->dc_count_ptrs[compptr->dc_tbl_no],
575 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
576 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
584 * Finish up a statistics-gathering pass and create the new Huffman tables.
588 finish_pass_gather (j_compress_ptr cinfo)
590 j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
591 shuff_entropy_ptr entropy = (shuff_entropy_ptr) lossyc->entropy_private;
592 int ci, dctbl, actbl;
593 jpeg_component_info * compptr;
595 boolean did_dc[NUM_HUFF_TBLS];
596 boolean did_ac[NUM_HUFF_TBLS];
598 /* It's important not to apply jpeg_gen_optimal_table more than once
599 * per table, because it clobbers the input frequency counts!
601 MEMZERO(did_dc, SIZEOF(did_dc));
602 MEMZERO(did_ac, SIZEOF(did_ac));
604 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
605 compptr = cinfo->cur_comp_info[ci];
606 dctbl = compptr->dc_tbl_no;
607 actbl = compptr->ac_tbl_no;
608 if (! did_dc[dctbl]) {
609 htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
610 if (*htblptr == NULL)
611 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
612 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
613 did_dc[dctbl] = TRUE;
615 if (! did_ac[actbl]) {
616 htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
617 if (*htblptr == NULL)
618 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
619 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
620 did_ac[actbl] = TRUE;
626 #endif /* ENTROPY_OPT_SUPPORTED */
630 need_optimization_pass (j_compress_ptr cinfo)
638 * Module initialization routine for Huffman entropy encoding.
642 jinit_shuff_encoder (j_compress_ptr cinfo)
644 j_lossy_c_ptr lossyc = (j_lossy_c_ptr) cinfo->codec;
645 shuff_entropy_ptr entropy;
648 entropy = (shuff_entropy_ptr)
649 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
650 SIZEOF(shuff_entropy_encoder));
651 lossyc->entropy_private = (struct jpeg_entropy_encoder *) entropy;
652 lossyc->pub.entropy_start_pass = start_pass_huff;
653 lossyc->pub.need_optimization_pass = need_optimization_pass;
655 /* Mark tables unallocated */
656 for (i = 0; i < NUM_HUFF_TBLS; i++) {
657 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
658 #ifdef ENTROPY_OPT_SUPPORTED
659 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;