4 * Copyright (C) 1991-1997, Thomas G. Lane.
5 * Copyright (C) 2009-2011, D. R. Commander.
6 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
9 * This file contains Huffman entropy encoding routines.
11 * Much of the complexity here has to do with supporting output suspension.
12 * If the data destination module demands suspension, we want to be able to
13 * back up to the start of the current MCU. To do this, we copy state
14 * variables into local working storage, and update them back to the
15 * permanent JPEG objects only upon successful completion of an MCU.
18 #define JPEG_INTERNALS
21 #include "jchuff.h" /* Declarations shared with jcphuff.c */
24 static const unsigned char jpeg_nbits_table
[65536] = {
25 /* Number i needs jpeg_nbits_table[i] bits to be represented. */
26 #include "jpeg_nbits_table.h"
30 #define min(a,b) ((a)<(b)?(a):(b))
34 /* Expanded entropy encoder object for Huffman encoding.
36 * The savable_state subrecord contains fields that change within an MCU,
37 * but must not be updated permanently until we complete the MCU.
41 size_t put_buffer
; /* current bit-accumulation buffer */
42 int put_bits
; /* # of bits now in it */
43 int last_dc_val
[MAX_COMPS_IN_SCAN
]; /* last DC coef for each component */
46 /* This macro is to work around compilers with missing or broken
47 * structure assignment. You'll need to fix this code if you have
48 * such a compiler and you change MAX_COMPS_IN_SCAN.
51 #ifndef NO_STRUCT_ASSIGN
52 #define ASSIGN_STATE(dest,src) ((dest) = (src))
54 #if MAX_COMPS_IN_SCAN == 4
55 #define ASSIGN_STATE(dest,src) \
56 ((dest).put_buffer = (src).put_buffer, \
57 (dest).put_bits = (src).put_bits, \
58 (dest).last_dc_val[0] = (src).last_dc_val[0], \
59 (dest).last_dc_val[1] = (src).last_dc_val[1], \
60 (dest).last_dc_val[2] = (src).last_dc_val[2], \
61 (dest).last_dc_val[3] = (src).last_dc_val[3])
67 struct jpeg_entropy_encoder pub
; /* public fields */
69 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) */
75 /* Pointers to derived tables (these workspaces have image lifespan) */
76 c_derived_tbl
* dc_derived_tbls
[NUM_HUFF_TBLS
];
77 c_derived_tbl
* ac_derived_tbls
[NUM_HUFF_TBLS
];
79 #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
80 long * dc_count_ptrs
[NUM_HUFF_TBLS
];
81 long * ac_count_ptrs
[NUM_HUFF_TBLS
];
83 } huff_entropy_encoder
;
85 typedef huff_entropy_encoder
* huff_entropy_ptr
;
87 /* Working state while writing an MCU.
88 * This struct contains all the fields that are needed by subroutines.
92 JOCTET
* next_output_byte
; /* => next byte to write in buffer */
93 size_t free_in_buffer
; /* # of byte spaces remaining in buffer */
94 savable_state cur
; /* Current bit buffer & DC state */
95 j_compress_ptr cinfo
; /* dump_buffer needs access to this */
99 /* Forward declarations */
100 METHODDEF(boolean
) encode_mcu_huff
JPP((j_compress_ptr cinfo
,
101 JBLOCKROW
*MCU_data
));
102 METHODDEF(void) finish_pass_huff
JPP((j_compress_ptr cinfo
));
103 #ifdef ENTROPY_OPT_SUPPORTED
104 METHODDEF(boolean
) encode_mcu_gather
JPP((j_compress_ptr cinfo
,
105 JBLOCKROW
*MCU_data
));
106 METHODDEF(void) finish_pass_gather
JPP((j_compress_ptr cinfo
));
111 * Initialize for a Huffman-compressed scan.
112 * If gather_statistics is TRUE, we do not output anything during the scan,
113 * just count the Huffman symbols used and generate Huffman code tables.
117 start_pass_huff (j_compress_ptr cinfo
, boolean gather_statistics
)
119 huff_entropy_ptr entropy
= (huff_entropy_ptr
) cinfo
->entropy
;
120 int ci
, dctbl
, actbl
;
121 jpeg_component_info
* compptr
;
123 if (gather_statistics
) {
124 #ifdef ENTROPY_OPT_SUPPORTED
125 entropy
->pub
.encode_mcu
= encode_mcu_gather
;
126 entropy
->pub
.finish_pass
= finish_pass_gather
;
128 ERREXIT(cinfo
, JERR_NOT_COMPILED
);
131 entropy
->pub
.encode_mcu
= encode_mcu_huff
;
132 entropy
->pub
.finish_pass
= finish_pass_huff
;
135 for (ci
= 0; ci
< cinfo
->comps_in_scan
; ci
++) {
136 compptr
= cinfo
->cur_comp_info
[ci
];
137 dctbl
= compptr
->dc_tbl_no
;
138 actbl
= compptr
->ac_tbl_no
;
139 if (gather_statistics
) {
140 #ifdef ENTROPY_OPT_SUPPORTED
141 /* Check for invalid table indexes */
142 /* (make_c_derived_tbl does this in the other path) */
143 if (dctbl
< 0 || dctbl
>= NUM_HUFF_TBLS
)
144 ERREXIT1(cinfo
, JERR_NO_HUFF_TABLE
, dctbl
);
145 if (actbl
< 0 || actbl
>= NUM_HUFF_TBLS
)
146 ERREXIT1(cinfo
, JERR_NO_HUFF_TABLE
, actbl
);
147 /* Allocate and zero the statistics tables */
148 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
149 if (entropy
->dc_count_ptrs
[dctbl
] == NULL
)
150 entropy
->dc_count_ptrs
[dctbl
] = (long *)
151 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
153 MEMZERO(entropy
->dc_count_ptrs
[dctbl
], 257 * SIZEOF(long));
154 if (entropy
->ac_count_ptrs
[actbl
] == NULL
)
155 entropy
->ac_count_ptrs
[actbl
] = (long *)
156 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
158 MEMZERO(entropy
->ac_count_ptrs
[actbl
], 257 * SIZEOF(long));
161 /* Compute derived values for Huffman tables */
162 /* We may do this more than once for a table, but it's not expensive */
163 jpeg_make_c_derived_tbl(cinfo
, TRUE
, dctbl
,
164 & entropy
->dc_derived_tbls
[dctbl
]);
165 jpeg_make_c_derived_tbl(cinfo
, FALSE
, actbl
,
166 & entropy
->ac_derived_tbls
[actbl
]);
168 /* Initialize DC predictions to 0 */
169 entropy
->saved
.last_dc_val
[ci
] = 0;
172 /* Initialize bit buffer to empty */
173 entropy
->saved
.put_buffer
= 0;
174 entropy
->saved
.put_bits
= 0;
176 /* Initialize restart stuff */
177 entropy
->restarts_to_go
= cinfo
->restart_interval
;
178 entropy
->next_restart_num
= 0;
183 * Compute the derived values for a Huffman table.
184 * This routine also performs some validation checks on the table.
186 * Note this is also used by jcphuff.c.
190 jpeg_make_c_derived_tbl (j_compress_ptr cinfo
, boolean isDC
, int tblno
,
191 c_derived_tbl
** pdtbl
)
195 int p
, i
, l
, lastp
, si
, maxsymbol
;
197 unsigned int huffcode
[257];
200 /* Note that huffsize[] and huffcode[] are filled in code-length order,
201 * paralleling the order of the symbols themselves in htbl->huffval[].
204 /* Find the input Huffman table */
205 if (tblno
< 0 || tblno
>= NUM_HUFF_TBLS
)
206 ERREXIT1(cinfo
, JERR_NO_HUFF_TABLE
, tblno
);
208 isDC
? cinfo
->dc_huff_tbl_ptrs
[tblno
] : cinfo
->ac_huff_tbl_ptrs
[tblno
];
210 ERREXIT1(cinfo
, JERR_NO_HUFF_TABLE
, tblno
);
212 /* Allocate a workspace if we haven't already done so. */
214 *pdtbl
= (c_derived_tbl
*)
215 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
216 SIZEOF(c_derived_tbl
));
219 /* Figure C.1: make table of Huffman code length for each symbol */
222 for (l
= 1; l
<= 16; l
++) {
223 i
= (int) htbl
->bits
[l
];
224 if (i
< 0 || p
+ i
> 256) /* protect against table overrun */
225 ERREXIT(cinfo
, JERR_BAD_HUFF_TABLE
);
227 huffsize
[p
++] = (char) l
;
232 /* Figure C.2: generate the codes themselves */
233 /* We also validate that the counts represent a legal Huffman code tree. */
238 while (huffsize
[p
]) {
239 while (((int) huffsize
[p
]) == si
) {
240 huffcode
[p
++] = code
;
243 /* code is now 1 more than the last code used for codelength si; but
244 * it must still fit in si bits, since no code is allowed to be all ones.
246 if (((INT32
) code
) >= (((INT32
) 1) << si
))
247 ERREXIT(cinfo
, JERR_BAD_HUFF_TABLE
);
252 /* Figure C.3: generate encoding tables */
253 /* These are code and size indexed by symbol value */
255 /* Set all codeless symbols to have code length 0;
256 * this lets us detect duplicate VAL entries here, and later
257 * allows emit_bits to detect any attempt to emit such symbols.
259 MEMZERO(dtbl
->ehufsi
, SIZEOF(dtbl
->ehufsi
));
261 /* This is also a convenient place to check for out-of-range
262 * and duplicated VAL entries. We allow 0..255 for AC symbols
263 * but only 0..15 for DC. (We could constrain them further
264 * based on data depth and mode, but this seems enough.)
266 maxsymbol
= isDC
? 15 : 255;
268 for (p
= 0; p
< lastp
; p
++) {
269 i
= htbl
->huffval
[p
];
270 if (i
< 0 || i
> maxsymbol
|| dtbl
->ehufsi
[i
])
271 ERREXIT(cinfo
, JERR_BAD_HUFF_TABLE
);
272 dtbl
->ehufco
[i
] = huffcode
[p
];
273 dtbl
->ehufsi
[i
] = huffsize
[p
];
278 /* Outputting bytes to the file */
280 /* Emit a byte, taking 'action' if must suspend. */
281 #define emit_byte(state,val,action) \
282 { *(state)->next_output_byte++ = (JOCTET) (val); \
283 if (--(state)->free_in_buffer == 0) \
284 if (! dump_buffer(state)) \
289 dump_buffer (working_state
* state
)
290 /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
292 struct jpeg_destination_mgr
* dest
= state
->cinfo
->dest
;
294 dest
->free_in_buffer
= state
->free_in_buffer
;
296 if (! (*dest
->empty_output_buffer
) (state
->cinfo
))
298 /* After a successful buffer dump, must reset buffer pointers */
299 state
->next_output_byte
= dest
->next_output_byte
;
300 state
->free_in_buffer
= dest
->free_in_buffer
;
305 /* Outputting bits to the file */
307 /* These macros perform the same task as the emit_bits() function in the
308 * original libjpeg code. In addition to reducing overhead by explicitly
309 * inlining the code, additional performance is achieved by taking into
310 * account the size of the bit buffer and waiting until it is almost full
311 * before emptying it. This mostly benefits 64-bit platforms, since 6
312 * bytes can be stored in a 64-bit bit buffer before it has to be emptied.
315 #define EMIT_BYTE() { \
318 c = (JOCTET)GETJOCTET(put_buffer >> put_bits); \
320 if (c == 0xFF) /* need to stuff a zero byte? */ \
324 #define PUT_BITS(code, size) { \
326 put_buffer = (put_buffer << size) | code; \
329 #define CHECKBUF15() { \
330 if (put_bits > 15) { \
336 #define CHECKBUF31() { \
337 if (put_bits > 31) { \
345 #define CHECKBUF47() { \
346 if (put_bits > 47) { \
356 #if __WORDSIZE==64 || defined(_WIN64)
358 #define EMIT_BITS(code, size) { \
360 PUT_BITS(code, size) \
363 #define EMIT_CODE(code, size) { \
364 temp2 &= (((INT32) 1)<<nbits) - 1; \
366 PUT_BITS(code, size) \
367 PUT_BITS(temp2, nbits) \
372 #define EMIT_BITS(code, size) { \
373 PUT_BITS(code, size) \
377 #define EMIT_CODE(code, size) { \
378 temp2 &= (((INT32) 1)<<nbits) - 1; \
379 PUT_BITS(code, size) \
381 PUT_BITS(temp2, nbits) \
388 #define BUFSIZE (DCTSIZE2 * 2)
390 #define LOAD_BUFFER() { \
391 if (state->free_in_buffer < BUFSIZE) { \
395 else buffer = state->next_output_byte; \
398 #define STORE_BUFFER() { \
400 bytes = buffer - _buffer; \
402 while (bytes > 0) { \
403 bytestocopy = min(bytes, state->free_in_buffer); \
404 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
405 state->next_output_byte += bytestocopy; \
406 buffer += bytestocopy; \
407 state->free_in_buffer -= bytestocopy; \
408 if (state->free_in_buffer == 0) \
409 if (! dump_buffer(state)) return FALSE; \
410 bytes -= bytestocopy; \
414 state->free_in_buffer -= (buffer - state->next_output_byte); \
415 state->next_output_byte = buffer; \
421 flush_bits (working_state
* state
)
423 JOCTET _buffer
[BUFSIZE
], *buffer
;
424 size_t put_buffer
; int put_bits
;
425 size_t bytes
, bytestocopy
; int localbuf
= 0;
427 put_buffer
= state
->cur
.put_buffer
;
428 put_bits
= state
->cur
.put_bits
;
431 /* fill any partial byte with ones */
433 while (put_bits
>= 8) EMIT_BYTE()
435 state
->cur
.put_buffer
= 0; /* and reset bit-buffer to empty */
436 state
->cur
.put_bits
= 0;
443 /* Encode a single block's worth of coefficients */
446 encode_one_block (working_state
* state
, JCOEFPTR block
, int last_dc_val
,
447 c_derived_tbl
*dctbl
, c_derived_tbl
*actbl
)
449 int temp
, temp2
, temp3
;
452 JOCTET _buffer
[BUFSIZE
], *buffer
;
453 size_t put_buffer
; int put_bits
;
454 int code_0xf0
= actbl
->ehufco
[0xf0], size_0xf0
= actbl
->ehufsi
[0xf0];
455 size_t bytes
, bytestocopy
; int localbuf
= 0;
457 put_buffer
= state
->cur
.put_buffer
;
458 put_bits
= state
->cur
.put_bits
;
461 /* Encode the DC coefficient difference per section F.1.2.1 */
463 temp
= temp2
= block
[0] - last_dc_val
;
465 /* This is a well-known technique for obtaining the absolute value without a
466 * branch. It is derived from an assembly language technique presented in
467 * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
470 temp3
= temp
>> (CHAR_BIT
* sizeof(int) - 1);
474 /* For a negative input, want temp2 = bitwise complement of abs(input) */
475 /* This code assumes we are on a two's complement machine */
478 /* Find the number of bits needed for the magnitude of the coefficient */
479 nbits
= jpeg_nbits_table
[temp
];
481 /* Emit the Huffman-coded symbol for the number of bits */
482 code
= dctbl
->ehufco
[nbits
];
483 size
= dctbl
->ehufsi
[nbits
];
487 /* Mask off any extra bits in code */
488 temp2
&= (((INT32
) 1)<<nbits
) - 1;
490 /* Emit that number of bits of the value, if positive, */
491 /* or the complement of its magnitude, if negative. */
492 PUT_BITS(temp2
, nbits
)
495 /* Encode the AC coefficients per section F.1.2.2 */
497 r
= 0; /* r = run length of zeros */
499 /* Manually unroll the k loop to eliminate the counter variable. This
500 * improves performance greatly on systems with a limited number of
501 * registers (such as x86.)
503 #define kloop(jpeg_natural_order_of_k) { \
504 if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
508 /* Branch-less absolute value, bitwise complement, etc., same as above */ \
509 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1); \
513 nbits = jpeg_nbits_table[temp]; \
514 /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
516 EMIT_BITS(code_0xf0, size_0xf0) \
519 /* Emit Huffman symbol for run length / number of bits */ \
520 temp3 = (r << 4) + nbits; \
521 code = actbl->ehufco[temp3]; \
522 size = actbl->ehufsi[temp3]; \
523 EMIT_CODE(code, size) \
528 /* One iteration for each value in jpeg_natural_order[] */
529 kloop(1); kloop(8); kloop(16); kloop(9); kloop(2); kloop(3);
530 kloop(10); kloop(17); kloop(24); kloop(32); kloop(25); kloop(18);
531 kloop(11); kloop(4); kloop(5); kloop(12); kloop(19); kloop(26);
532 kloop(33); kloop(40); kloop(48); kloop(41); kloop(34); kloop(27);
533 kloop(20); kloop(13); kloop(6); kloop(7); kloop(14); kloop(21);
534 kloop(28); kloop(35); kloop(42); kloop(49); kloop(56); kloop(57);
535 kloop(50); kloop(43); kloop(36); kloop(29); kloop(22); kloop(15);
536 kloop(23); kloop(30); kloop(37); kloop(44); kloop(51); kloop(58);
537 kloop(59); kloop(52); kloop(45); kloop(38); kloop(31); kloop(39);
538 kloop(46); kloop(53); kloop(60); kloop(61); kloop(54); kloop(47);
539 kloop(55); kloop(62); kloop(63);
541 /* If the last coef(s) were zero, emit an end-of-block code */
543 code
= actbl
->ehufco
[0];
544 size
= actbl
->ehufsi
[0];
545 EMIT_BITS(code
, size
)
548 state
->cur
.put_buffer
= put_buffer
;
549 state
->cur
.put_bits
= put_bits
;
557 * Emit a restart marker & resynchronize predictions.
561 emit_restart (working_state
* state
, int restart_num
)
565 if (! flush_bits(state
))
568 emit_byte(state
, 0xFF, return FALSE
);
569 emit_byte(state
, JPEG_RST0
+ restart_num
, return FALSE
);
571 /* Re-initialize DC predictions to 0 */
572 for (ci
= 0; ci
< state
->cinfo
->comps_in_scan
; ci
++)
573 state
->cur
.last_dc_val
[ci
] = 0;
575 /* The restart counter is not updated until we successfully write the MCU. */
582 * Encode and output one MCU's worth of Huffman-compressed coefficients.
586 encode_mcu_huff (j_compress_ptr cinfo
, JBLOCKROW
*MCU_data
)
588 huff_entropy_ptr entropy
= (huff_entropy_ptr
) cinfo
->entropy
;
591 jpeg_component_info
* compptr
;
593 /* Load up working state */
594 state
.next_output_byte
= cinfo
->dest
->next_output_byte
;
595 state
.free_in_buffer
= cinfo
->dest
->free_in_buffer
;
596 ASSIGN_STATE(state
.cur
, entropy
->saved
);
599 /* Emit restart marker if needed */
600 if (cinfo
->restart_interval
) {
601 if (entropy
->restarts_to_go
== 0)
602 if (! emit_restart(&state
, entropy
->next_restart_num
))
606 /* Encode the MCU data blocks */
607 for (blkn
= 0; blkn
< cinfo
->blocks_in_MCU
; blkn
++) {
608 ci
= cinfo
->MCU_membership
[blkn
];
609 compptr
= cinfo
->cur_comp_info
[ci
];
610 if (! encode_one_block(&state
,
611 MCU_data
[blkn
][0], state
.cur
.last_dc_val
[ci
],
612 entropy
->dc_derived_tbls
[compptr
->dc_tbl_no
],
613 entropy
->ac_derived_tbls
[compptr
->ac_tbl_no
]))
615 /* Update last_dc_val */
616 state
.cur
.last_dc_val
[ci
] = MCU_data
[blkn
][0][0];
619 /* Completed MCU, so update state */
620 cinfo
->dest
->next_output_byte
= state
.next_output_byte
;
621 cinfo
->dest
->free_in_buffer
= state
.free_in_buffer
;
622 ASSIGN_STATE(entropy
->saved
, state
.cur
);
624 /* Update restart-interval state too */
625 if (cinfo
->restart_interval
) {
626 if (entropy
->restarts_to_go
== 0) {
627 entropy
->restarts_to_go
= cinfo
->restart_interval
;
628 entropy
->next_restart_num
++;
629 entropy
->next_restart_num
&= 7;
631 entropy
->restarts_to_go
--;
639 * Finish up at the end of a Huffman-compressed scan.
643 finish_pass_huff (j_compress_ptr cinfo
)
645 huff_entropy_ptr entropy
= (huff_entropy_ptr
) cinfo
->entropy
;
648 /* Load up working state ... flush_bits needs it */
649 state
.next_output_byte
= cinfo
->dest
->next_output_byte
;
650 state
.free_in_buffer
= cinfo
->dest
->free_in_buffer
;
651 ASSIGN_STATE(state
.cur
, entropy
->saved
);
654 /* Flush out the last data */
655 if (! flush_bits(&state
))
656 ERREXIT(cinfo
, JERR_CANT_SUSPEND
);
659 cinfo
->dest
->next_output_byte
= state
.next_output_byte
;
660 cinfo
->dest
->free_in_buffer
= state
.free_in_buffer
;
661 ASSIGN_STATE(entropy
->saved
, state
.cur
);
666 * Huffman coding optimization.
668 * We first scan the supplied data and count the number of uses of each symbol
669 * that is to be Huffman-coded. (This process MUST agree with the code above.)
670 * Then we build a Huffman coding tree for the observed counts.
671 * Symbols which are not needed at all for the particular image are not
672 * assigned any code, which saves space in the DHT marker as well as in
673 * the compressed data.
676 #ifdef ENTROPY_OPT_SUPPORTED
679 /* Process a single block's worth of coefficients */
682 htest_one_block (j_compress_ptr cinfo
, JCOEFPTR block
, int last_dc_val
,
683 long dc_counts
[], long ac_counts
[])
689 /* Encode the DC coefficient difference per section F.1.2.1 */
691 temp
= block
[0] - last_dc_val
;
695 /* Find the number of bits needed for the magnitude of the coefficient */
701 /* Check for out-of-range coefficient values.
702 * Since we're encoding a difference, the range limit is twice as much.
704 if (nbits
> MAX_COEF_BITS
+1)
705 ERREXIT(cinfo
, JERR_BAD_DCT_COEF
);
707 /* Count the Huffman symbol for the number of bits */
710 /* Encode the AC coefficients per section F.1.2.2 */
712 r
= 0; /* r = run length of zeros */
714 for (k
= 1; k
< DCTSIZE2
; k
++) {
715 if ((temp
= block
[jpeg_natural_order
[k
]]) == 0) {
718 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
724 /* Find the number of bits needed for the magnitude of the coefficient */
728 /* Find the number of bits needed for the magnitude of the coefficient */
729 nbits
= 1; /* there must be at least one 1 bit */
732 /* Check for out-of-range coefficient values */
733 if (nbits
> MAX_COEF_BITS
)
734 ERREXIT(cinfo
, JERR_BAD_DCT_COEF
);
736 /* Count Huffman symbol for run length / number of bits */
737 ac_counts
[(r
<< 4) + nbits
]++;
743 /* If the last coef(s) were zero, emit an end-of-block code */
750 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
751 * No data is actually output, so no suspension return is possible.
755 encode_mcu_gather (j_compress_ptr cinfo
, JBLOCKROW
*MCU_data
)
757 huff_entropy_ptr entropy
= (huff_entropy_ptr
) cinfo
->entropy
;
759 jpeg_component_info
* compptr
;
761 /* Take care of restart intervals if needed */
762 if (cinfo
->restart_interval
) {
763 if (entropy
->restarts_to_go
== 0) {
764 /* Re-initialize DC predictions to 0 */
765 for (ci
= 0; ci
< cinfo
->comps_in_scan
; ci
++)
766 entropy
->saved
.last_dc_val
[ci
] = 0;
767 /* Update restart state */
768 entropy
->restarts_to_go
= cinfo
->restart_interval
;
770 entropy
->restarts_to_go
--;
773 for (blkn
= 0; blkn
< cinfo
->blocks_in_MCU
; blkn
++) {
774 ci
= cinfo
->MCU_membership
[blkn
];
775 compptr
= cinfo
->cur_comp_info
[ci
];
776 htest_one_block(cinfo
, MCU_data
[blkn
][0], entropy
->saved
.last_dc_val
[ci
],
777 entropy
->dc_count_ptrs
[compptr
->dc_tbl_no
],
778 entropy
->ac_count_ptrs
[compptr
->ac_tbl_no
]);
779 entropy
->saved
.last_dc_val
[ci
] = MCU_data
[blkn
][0][0];
787 * Generate the best Huffman code table for the given counts, fill htbl.
788 * Note this is also used by jcphuff.c.
790 * The JPEG standard requires that no symbol be assigned a codeword of all
791 * one bits (so that padding bits added at the end of a compressed segment
792 * can't look like a valid code). Because of the canonical ordering of
793 * codewords, this just means that there must be an unused slot in the
794 * longest codeword length category. Section K.2 of the JPEG spec suggests
795 * reserving such a slot by pretending that symbol 256 is a valid symbol
796 * with count 1. In theory that's not optimal; giving it count zero but
797 * including it in the symbol set anyway should give a better Huffman code.
798 * But the theoretically better code actually seems to come out worse in
799 * practice, because it produces more all-ones bytes (which incur stuffed
800 * zero bytes in the final file). In any case the difference is tiny.
802 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
803 * If some symbols have a very small but nonzero probability, the Huffman tree
804 * must be adjusted to meet the code length restriction. We currently use
805 * the adjustment method suggested in JPEG section K.2. This method is *not*
806 * optimal; it may not choose the best possible limited-length code. But
807 * typically only very-low-frequency symbols will be given less-than-optimal
808 * lengths, so the code is almost optimal. Experimental comparisons against
809 * an optimal limited-length-code algorithm indicate that the difference is
810 * microscopic --- usually less than a hundredth of a percent of total size.
811 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
815 jpeg_gen_optimal_table (j_compress_ptr cinfo
, JHUFF_TBL
* htbl
, long freq
[])
817 #define MAX_CLEN 32 /* assumed maximum initial code length */
818 UINT8 bits
[MAX_CLEN
+1]; /* bits[k] = # of symbols with code length k */
819 int codesize
[257]; /* codesize[k] = code length of symbol k */
820 int others
[257]; /* next symbol in current branch of tree */
825 /* This algorithm is explained in section K.2 of the JPEG standard */
827 MEMZERO(bits
, SIZEOF(bits
));
828 MEMZERO(codesize
, SIZEOF(codesize
));
829 for (i
= 0; i
< 257; i
++)
830 others
[i
] = -1; /* init links to empty */
832 freq
[256] = 1; /* make sure 256 has a nonzero count */
833 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
834 * that no real symbol is given code-value of all ones, because 256
835 * will be placed last in the largest codeword category.
838 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
841 /* Find the smallest nonzero frequency, set c1 = its symbol */
842 /* In case of ties, take the larger symbol number */
845 for (i
= 0; i
<= 256; i
++) {
846 if (freq
[i
] && freq
[i
] <= v
) {
852 /* Find the next smallest nonzero frequency, set c2 = its symbol */
853 /* In case of ties, take the larger symbol number */
856 for (i
= 0; i
<= 256; i
++) {
857 if (freq
[i
] && freq
[i
] <= v
&& i
!= c1
) {
863 /* Done if we've merged everything into one frequency */
867 /* Else merge the two counts/trees */
868 freq
[c1
] += freq
[c2
];
871 /* Increment the codesize of everything in c1's tree branch */
873 while (others
[c1
] >= 0) {
878 others
[c1
] = c2
; /* chain c2 onto c1's tree branch */
880 /* Increment the codesize of everything in c2's tree branch */
882 while (others
[c2
] >= 0) {
888 /* Now count the number of symbols of each code length */
889 for (i
= 0; i
<= 256; i
++) {
891 /* The JPEG standard seems to think that this can't happen, */
892 /* but I'm paranoid... */
893 if (codesize
[i
] > MAX_CLEN
)
894 ERREXIT(cinfo
, JERR_HUFF_CLEN_OVERFLOW
);
900 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
901 * Huffman procedure assigned any such lengths, we must adjust the coding.
902 * Here is what the JPEG spec says about how this next bit works:
903 * Since symbols are paired for the longest Huffman code, the symbols are
904 * removed from this length category two at a time. The prefix for the pair
905 * (which is one bit shorter) is allocated to one of the pair; then,
906 * skipping the BITS entry for that prefix length, a code word from the next
907 * shortest nonzero BITS entry is converted into a prefix for two code words
911 for (i
= MAX_CLEN
; i
> 16; i
--) {
912 while (bits
[i
] > 0) {
913 j
= i
- 2; /* find length of new prefix to be used */
917 bits
[i
] -= 2; /* remove two symbols */
918 bits
[i
-1]++; /* one goes in this length */
919 bits
[j
+1] += 2; /* two new symbols in this length */
920 bits
[j
]--; /* symbol of this length is now a prefix */
924 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
925 while (bits
[i
] == 0) /* find largest codelength still in use */
929 /* Return final symbol counts (only for lengths 0..16) */
930 MEMCOPY(htbl
->bits
, bits
, SIZEOF(htbl
->bits
));
932 /* Return a list of the symbols sorted by code length */
933 /* It's not real clear to me why we don't need to consider the codelength
934 * changes made above, but the JPEG spec seems to think this works.
937 for (i
= 1; i
<= MAX_CLEN
; i
++) {
938 for (j
= 0; j
<= 255; j
++) {
939 if (codesize
[j
] == i
) {
940 htbl
->huffval
[p
] = (UINT8
) j
;
946 /* Set sent_table FALSE so updated table will be written to JPEG file. */
947 htbl
->sent_table
= FALSE
;
952 * Finish up a statistics-gathering pass and create the new Huffman tables.
956 finish_pass_gather (j_compress_ptr cinfo
)
958 huff_entropy_ptr entropy
= (huff_entropy_ptr
) cinfo
->entropy
;
959 int ci
, dctbl
, actbl
;
960 jpeg_component_info
* compptr
;
962 boolean did_dc
[NUM_HUFF_TBLS
];
963 boolean did_ac
[NUM_HUFF_TBLS
];
965 /* It's important not to apply jpeg_gen_optimal_table more than once
966 * per table, because it clobbers the input frequency counts!
968 MEMZERO(did_dc
, SIZEOF(did_dc
));
969 MEMZERO(did_ac
, SIZEOF(did_ac
));
971 for (ci
= 0; ci
< cinfo
->comps_in_scan
; ci
++) {
972 compptr
= cinfo
->cur_comp_info
[ci
];
973 dctbl
= compptr
->dc_tbl_no
;
974 actbl
= compptr
->ac_tbl_no
;
975 if (! did_dc
[dctbl
]) {
976 htblptr
= & cinfo
->dc_huff_tbl_ptrs
[dctbl
];
977 if (*htblptr
== NULL
)
978 *htblptr
= jpeg_alloc_huff_table((j_common_ptr
) cinfo
);
979 jpeg_gen_optimal_table(cinfo
, *htblptr
, entropy
->dc_count_ptrs
[dctbl
]);
980 did_dc
[dctbl
] = TRUE
;
982 if (! did_ac
[actbl
]) {
983 htblptr
= & cinfo
->ac_huff_tbl_ptrs
[actbl
];
984 if (*htblptr
== NULL
)
985 *htblptr
= jpeg_alloc_huff_table((j_common_ptr
) cinfo
);
986 jpeg_gen_optimal_table(cinfo
, *htblptr
, entropy
->ac_count_ptrs
[actbl
]);
987 did_ac
[actbl
] = TRUE
;
993 #endif /* ENTROPY_OPT_SUPPORTED */
997 * Module initialization routine for Huffman entropy encoding.
1001 jinit_huff_encoder (j_compress_ptr cinfo
)
1003 huff_entropy_ptr entropy
;
1006 entropy
= (huff_entropy_ptr
)
1007 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
1008 SIZEOF(huff_entropy_encoder
));
1009 cinfo
->entropy
= (struct jpeg_entropy_encoder
*) entropy
;
1010 entropy
->pub
.start_pass
= start_pass_huff
;
1012 /* Mark tables unallocated */
1013 for (i
= 0; i
< NUM_HUFF_TBLS
; i
++) {
1014 entropy
->dc_derived_tbls
[i
] = entropy
->ac_derived_tbls
[i
] = NULL
;
1015 #ifdef ENTROPY_OPT_SUPPORTED
1016 entropy
->dc_count_ptrs
[i
] = entropy
->ac_count_ptrs
[i
] = NULL
;