8 * Copyright (C) 1991-1998, Thomas G. Lane.
9 * This file is part of the Independent JPEG Group's software.
10 * For conditions of distribution and use, see the accompanying README file.
12 * This file contains Huffman entropy encoding routines for sequential JPEG.
14 * Much of the complexity here has to do with supporting output suspension.
15 * If the data destination module demands suspension, we want to be able to
16 * back up to the start of the current MCU. To do this, we copy state
17 * variables into local working storage, and update them back to the
18 * permanent JPEG objects only upon successful completion of an MCU.
21 #define JPEG_INTERNALS
24 #include "jlossy.h" /* Private declarations for lossy codec */
25 #include "jchuff.h" /* Declarations shared with jc*huff.c */
28 /* Expanded entropy encoder object for Huffman encoding.
30 * The savable_state subrecord contains fields that change within an MCU,
31 * but must not be updated permanently until we complete the MCU.
35 INT32 put_buffer
; /* current bit-accumulation buffer */
36 int put_bits
; /* # of bits now in it */
37 int last_dc_val
[MAX_COMPS_IN_SCAN
]; /* last DC coef for each component */
40 /* This macro is to work around compilers with missing or broken
41 * structure assignment. You'll need to fix this code if you have
42 * such a compiler and you change MAX_COMPS_IN_SCAN.
45 #ifndef NO_STRUCT_ASSIGN
46 #define ASSIGN_STATE(dest,src) ((dest) = (src))
48 #if MAX_COMPS_IN_SCAN == 4
49 #define ASSIGN_STATE(dest,src) \
50 ((dest).put_buffer = (src).put_buffer, \
51 (dest).put_bits = (src).put_bits, \
52 (dest).last_dc_val[0] = (src).last_dc_val[0], \
53 (dest).last_dc_val[1] = (src).last_dc_val[1], \
54 (dest).last_dc_val[2] = (src).last_dc_val[2], \
55 (dest).last_dc_val[3] = (src).last_dc_val[3])
61 savable_state saved
; /* Bit buffer & DC state at start of MCU */
63 /* These fields are NOT loaded into local working state. */
64 unsigned int restarts_to_go
; /* MCUs left in this restart interval */
65 int next_restart_num
; /* next restart number to write (0-7) */
67 /* Pointers to derived tables (these workspaces have image lifespan) */
68 c_derived_tbl
* dc_derived_tbls
[NUM_HUFF_TBLS
];
69 c_derived_tbl
* ac_derived_tbls
[NUM_HUFF_TBLS
];
71 #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
72 long * dc_count_ptrs
[NUM_HUFF_TBLS
];
73 long * ac_count_ptrs
[NUM_HUFF_TBLS
];
75 } shuff_entropy_encoder
;
77 typedef shuff_entropy_encoder
* shuff_entropy_ptr
;
79 /* Working state while writing an MCU.
80 * This struct contains all the fields that are needed by subroutines.
84 JOCTET
* next_output_byte
; /* => next byte to write in buffer */
85 size_t free_in_buffer
; /* # of byte spaces remaining in buffer */
86 savable_state cur
; /* Current bit buffer & DC state */
87 j_compress_ptr cinfo
; /* dump_buffer needs access to this */
91 /* Forward declarations */
92 METHODDEF(boolean
) encode_mcu_huff
JPP((j_compress_ptr cinfo
,
93 JBLOCKROW
*MCU_data
));
94 METHODDEF(void) finish_pass_huff
JPP((j_compress_ptr cinfo
));
95 #ifdef ENTROPY_OPT_SUPPORTED
96 METHODDEF(boolean
) encode_mcu_gather
JPP((j_compress_ptr cinfo
,
97 JBLOCKROW
*MCU_data
));
98 METHODDEF(void) finish_pass_gather
JPP((j_compress_ptr cinfo
));
103 * Initialize for a Huffman-compressed scan.
104 * If gather_statistics is TRUE, we do not output anything during the scan,
105 * just count the Huffman symbols used and generate Huffman code tables.
109 start_pass_huff (j_compress_ptr cinfo
, boolean gather_statistics
)
111 j_lossy_c_ptr lossyc
= (j_lossy_c_ptr
) cinfo
->codec
;
112 shuff_entropy_ptr entropy
= (shuff_entropy_ptr
) lossyc
->entropy_private
;
113 int ci
, dctbl
, actbl
;
114 jpeg_component_info
* compptr
;
116 if (gather_statistics
) {
117 #ifdef ENTROPY_OPT_SUPPORTED
118 lossyc
->entropy_encode_mcu
= encode_mcu_gather
;
119 lossyc
->pub
.entropy_finish_pass
= finish_pass_gather
;
121 ERREXIT(cinfo
, JERR_NOT_COMPILED
);
124 lossyc
->entropy_encode_mcu
= encode_mcu_huff
;
125 lossyc
->pub
.entropy_finish_pass
= finish_pass_huff
;
128 for (ci
= 0; ci
< cinfo
->comps_in_scan
; ci
++) {
129 compptr
= cinfo
->cur_comp_info
[ci
];
130 dctbl
= compptr
->dc_tbl_no
;
131 actbl
= compptr
->ac_tbl_no
;
132 if (gather_statistics
) {
133 #ifdef ENTROPY_OPT_SUPPORTED
134 /* Check for invalid table indexes */
135 /* (make_c_derived_tbl does this in the other path) */
136 if (dctbl
< 0 || dctbl
>= NUM_HUFF_TBLS
)
137 ERREXIT1(cinfo
, JERR_NO_HUFF_TABLE
, dctbl
);
138 if (actbl
< 0 || actbl
>= NUM_HUFF_TBLS
)
139 ERREXIT1(cinfo
, JERR_NO_HUFF_TABLE
, actbl
);
140 /* Allocate and zero the statistics tables */
141 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
142 if (entropy
->dc_count_ptrs
[dctbl
] == NULL
)
143 entropy
->dc_count_ptrs
[dctbl
] = (long *)
144 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
146 MEMZERO(entropy
->dc_count_ptrs
[dctbl
], 257 * SIZEOF(long));
147 if (entropy
->ac_count_ptrs
[actbl
] == NULL
)
148 entropy
->ac_count_ptrs
[actbl
] = (long *)
149 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
151 MEMZERO(entropy
->ac_count_ptrs
[actbl
], 257 * SIZEOF(long));
154 /* Compute derived values for Huffman tables */
155 /* We may do this more than once for a table, but it's not expensive */
156 jpeg_make_c_derived_tbl(cinfo
, TRUE
, dctbl
,
157 & entropy
->dc_derived_tbls
[dctbl
]);
158 jpeg_make_c_derived_tbl(cinfo
, FALSE
, actbl
,
159 & entropy
->ac_derived_tbls
[actbl
]);
161 /* Initialize DC predictions to 0 */
162 entropy
->saved
.last_dc_val
[ci
] = 0;
165 /* Initialize bit buffer to empty */
166 entropy
->saved
.put_buffer
= 0;
167 entropy
->saved
.put_bits
= 0;
169 /* Initialize restart stuff */
170 entropy
->restarts_to_go
= cinfo
->restart_interval
;
171 entropy
->next_restart_num
= 0;
175 /* Outputting bytes to the file */
177 /* Emit a byte, taking 'action' if must suspend. */
178 #define emit_byte(state,val,action) \
179 { *(state)->next_output_byte++ = (JOCTET) (val); \
180 if (--(state)->free_in_buffer == 0) \
181 if (! dump_buffer(state)) \
186 dump_buffer (working_state
* state
)
187 /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
189 struct jpeg_destination_mgr
* dest
= state
->cinfo
->dest
;
191 if (! (*dest
->empty_output_buffer
) (state
->cinfo
))
193 /* After a successful buffer dump, must reset buffer pointers */
194 state
->next_output_byte
= dest
->next_output_byte
;
195 state
->free_in_buffer
= dest
->free_in_buffer
;
200 /* Outputting bits to the file */
202 /* Only the right 24 bits of put_buffer are used; the valid bits are
203 * left-justified in this part. At most 16 bits can be passed to emit_bits
204 * in one call, and we never retain more than 7 bits in put_buffer
205 * between calls, so 24 bits are sufficient.
210 emit_bits (working_state
* state
, unsigned int code
, int size
)
211 /* Emit some bits; return TRUE if successful, FALSE if must suspend */
213 /* This routine is heavily used, so it's worth coding tightly. */
214 register INT32 put_buffer
= (INT32
) code
;
215 register int put_bits
= state
->cur
.put_bits
;
217 /* if size is 0, caller used an invalid Huffman table entry */
219 ERREXIT(state
->cinfo
, JERR_HUFF_MISSING_CODE
);
221 put_buffer
&= (((INT32
) 1)<<size
) - 1; /* mask off any extra bits in code */
223 put_bits
+= size
; /* new number of bits in buffer */
225 put_buffer
<<= 24 - put_bits
; /* align incoming bits */
227 put_buffer
|= state
->cur
.put_buffer
; /* and merge with old buffer contents */
229 while (put_bits
>= 8) {
230 int c
= (int) ((put_buffer
>> 16) & 0xFF);
232 emit_byte(state
, c
, return FALSE
);
233 if (c
== 0xFF) { /* need to stuff a zero byte? */
234 emit_byte(state
, 0, return FALSE
);
240 state
->cur
.put_buffer
= put_buffer
; /* update state variables */
241 state
->cur
.put_bits
= put_bits
;
248 flush_bits (working_state
* state
)
250 if (! emit_bits(state
, 0x7F, 7)) /* fill any partial byte with ones */
252 state
->cur
.put_buffer
= 0; /* and reset bit-buffer to empty */
253 state
->cur
.put_bits
= 0;
258 /* Encode a single block's worth of coefficients */
261 encode_one_block (working_state
* state
, JCOEFPTR block
, int last_dc_val
,
262 c_derived_tbl
*dctbl
, c_derived_tbl
*actbl
)
264 register int temp
, temp2
;
266 register int k
, r
, i
;
268 /* Encode the DC coefficient difference per section F.1.2.1 */
270 temp
= temp2
= block
[0] - last_dc_val
;
273 temp
= -temp
; /* temp is abs value of input */
274 /* For a negative input, want temp2 = bitwise complement of abs(input) */
275 /* This code assumes we are on a two's complement machine */
279 /* Find the number of bits needed for the magnitude of the coefficient */
285 /* Check for out-of-range coefficient values.
286 * Since we're encoding a difference, the range limit is twice as much.
288 if (nbits
> MAX_COEF_BITS
+1)
289 ERREXIT(state
->cinfo
, JERR_BAD_DCT_COEF
);
291 /* Emit the Huffman-coded symbol for the number of bits */
292 if (! emit_bits(state
, dctbl
->ehufco
[nbits
], dctbl
->ehufsi
[nbits
]))
295 /* Emit that number of bits of the value, if positive, */
296 /* or the complement of its magnitude, if negative. */
297 if (nbits
) /* emit_bits rejects calls with size 0 */
298 if (! emit_bits(state
, (unsigned int) temp2
, nbits
))
301 /* Encode the AC coefficients per section F.1.2.2 */
303 r
= 0; /* r = run length of zeros */
305 for (k
= 1; k
< DCTSIZE2
; k
++) {
306 if ((temp
= block
[jpeg_natural_order
[k
]]) == 0) {
309 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
311 if (! emit_bits(state
, actbl
->ehufco
[0xF0], actbl
->ehufsi
[0xF0]))
318 temp
= -temp
; /* temp is abs value of input */
319 /* This code assumes we are on a two's complement machine */
323 /* Find the number of bits needed for the magnitude of the coefficient */
324 nbits
= 1; /* there must be at least one 1 bit */
327 /* Check for out-of-range coefficient values */
328 if (nbits
> MAX_COEF_BITS
)
329 ERREXIT(state
->cinfo
, JERR_BAD_DCT_COEF
);
331 /* Emit Huffman symbol for run length / number of bits */
332 i
= (r
<< 4) + nbits
;
333 if (! emit_bits(state
, actbl
->ehufco
[i
], actbl
->ehufsi
[i
]))
336 /* Emit that number of bits of the value, if positive, */
337 /* or the complement of its magnitude, if negative. */
338 if (! emit_bits(state
, (unsigned int) temp2
, nbits
))
345 /* If the last coef(s) were zero, emit an end-of-block code */
347 if (! emit_bits(state
, actbl
->ehufco
[0], actbl
->ehufsi
[0]))
355 * Emit a restart marker & resynchronize predictions.
359 emit_restart (working_state
* state
, int restart_num
)
363 if (! flush_bits(state
))
366 emit_byte(state
, 0xFF, return FALSE
);
367 emit_byte(state
, JPEG_RST0
+ restart_num
, return FALSE
);
369 /* Re-initialize DC predictions to 0 */
370 for (ci
= 0; ci
< state
->cinfo
->comps_in_scan
; ci
++)
371 state
->cur
.last_dc_val
[ci
] = 0;
373 /* The restart counter is not updated until we successfully write the MCU. */
380 * Encode and output one MCU's worth of Huffman-compressed coefficients.
384 encode_mcu_huff (j_compress_ptr cinfo
, JBLOCKROW
*MCU_data
)
386 j_lossy_c_ptr lossyc
= (j_lossy_c_ptr
) cinfo
->codec
;
387 shuff_entropy_ptr entropy
= (shuff_entropy_ptr
) lossyc
->entropy_private
;
390 jpeg_component_info
* compptr
;
392 /* Load up working state */
393 state
.next_output_byte
= cinfo
->dest
->next_output_byte
;
394 state
.free_in_buffer
= cinfo
->dest
->free_in_buffer
;
395 ASSIGN_STATE(state
.cur
, entropy
->saved
);
398 /* Emit restart marker if needed */
399 if (cinfo
->restart_interval
) {
400 if (entropy
->restarts_to_go
== 0)
401 if (! emit_restart(&state
, entropy
->next_restart_num
))
405 /* Encode the MCU data blocks */
406 for (blkn
= 0; blkn
< cinfo
->data_units_in_MCU
; blkn
++) {
407 ci
= cinfo
->MCU_membership
[blkn
];
408 compptr
= cinfo
->cur_comp_info
[ci
];
409 if (! encode_one_block(&state
,
410 MCU_data
[blkn
][0], state
.cur
.last_dc_val
[ci
],
411 entropy
->dc_derived_tbls
[compptr
->dc_tbl_no
],
412 entropy
->ac_derived_tbls
[compptr
->ac_tbl_no
]))
414 /* Update last_dc_val */
415 state
.cur
.last_dc_val
[ci
] = MCU_data
[blkn
][0][0];
418 /* Completed MCU, so update state */
419 cinfo
->dest
->next_output_byte
= state
.next_output_byte
;
420 cinfo
->dest
->free_in_buffer
= state
.free_in_buffer
;
421 ASSIGN_STATE(entropy
->saved
, state
.cur
);
423 /* Update restart-interval state too */
424 if (cinfo
->restart_interval
) {
425 if (entropy
->restarts_to_go
== 0) {
426 entropy
->restarts_to_go
= cinfo
->restart_interval
;
427 entropy
->next_restart_num
++;
428 entropy
->next_restart_num
&= 7;
430 entropy
->restarts_to_go
--;
438 * Finish up at the end of a Huffman-compressed scan.
442 finish_pass_huff (j_compress_ptr cinfo
)
444 j_lossy_c_ptr lossyc
= (j_lossy_c_ptr
) cinfo
->codec
;
445 shuff_entropy_ptr entropy
= (shuff_entropy_ptr
) lossyc
->entropy_private
;
448 /* Load up working state ... flush_bits needs it */
449 state
.next_output_byte
= cinfo
->dest
->next_output_byte
;
450 state
.free_in_buffer
= cinfo
->dest
->free_in_buffer
;
451 ASSIGN_STATE(state
.cur
, entropy
->saved
);
454 /* Flush out the last data */
455 if (! flush_bits(&state
))
456 ERREXIT(cinfo
, JERR_CANT_SUSPEND
);
459 cinfo
->dest
->next_output_byte
= state
.next_output_byte
;
460 cinfo
->dest
->free_in_buffer
= state
.free_in_buffer
;
461 ASSIGN_STATE(entropy
->saved
, state
.cur
);
466 * Huffman coding optimization.
468 * We first scan the supplied data and count the number of uses of each symbol
469 * that is to be Huffman-coded. (This process MUST agree with the code above.)
470 * Then we build a Huffman coding tree for the observed counts.
471 * Symbols which are not needed at all for the particular image are not
472 * assigned any code, which saves space in the DHT marker as well as in
473 * the compressed data.
476 #ifdef ENTROPY_OPT_SUPPORTED
479 /* Process a single block's worth of coefficients */
482 htest_one_block (j_compress_ptr cinfo
, JCOEFPTR block
, int last_dc_val
,
483 long dc_counts
[], long ac_counts
[])
489 /* Encode the DC coefficient difference per section F.1.2.1 */
491 temp
= block
[0] - last_dc_val
;
495 /* Find the number of bits needed for the magnitude of the coefficient */
501 /* Check for out-of-range coefficient values.
502 * Since we're encoding a difference, the range limit is twice as much.
504 if (nbits
> MAX_COEF_BITS
+1)
505 ERREXIT(cinfo
, JERR_BAD_DCT_COEF
);
507 /* Count the Huffman symbol for the number of bits */
510 /* Encode the AC coefficients per section F.1.2.2 */
512 r
= 0; /* r = run length of zeros */
514 for (k
= 1; k
< DCTSIZE2
; k
++) {
515 if ((temp
= block
[jpeg_natural_order
[k
]]) == 0) {
518 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
524 /* Find the number of bits needed for the magnitude of the coefficient */
528 /* Find the number of bits needed for the magnitude of the coefficient */
529 nbits
= 1; /* there must be at least one 1 bit */
532 /* Check for out-of-range coefficient values */
533 if (nbits
> MAX_COEF_BITS
)
534 ERREXIT(cinfo
, JERR_BAD_DCT_COEF
);
536 /* Count Huffman symbol for run length / number of bits */
537 ac_counts
[(r
<< 4) + nbits
]++;
543 /* If the last coef(s) were zero, emit an end-of-block code */
550 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
551 * No data is actually output, so no suspension return is possible.
555 encode_mcu_gather (j_compress_ptr cinfo
, JBLOCKROW
*MCU_data
)
557 j_lossy_c_ptr lossyc
= (j_lossy_c_ptr
) cinfo
->codec
;
558 shuff_entropy_ptr entropy
= (shuff_entropy_ptr
) lossyc
->entropy_private
;
560 jpeg_component_info
* compptr
;
562 /* Take care of restart intervals if needed */
563 if (cinfo
->restart_interval
) {
564 if (entropy
->restarts_to_go
== 0) {
565 /* Re-initialize DC predictions to 0 */
566 for (ci
= 0; ci
< cinfo
->comps_in_scan
; ci
++)
567 entropy
->saved
.last_dc_val
[ci
] = 0;
568 /* Update restart state */
569 entropy
->restarts_to_go
= cinfo
->restart_interval
;
571 entropy
->restarts_to_go
--;
574 for (blkn
= 0; blkn
< cinfo
->data_units_in_MCU
; blkn
++) {
575 ci
= cinfo
->MCU_membership
[blkn
];
576 compptr
= cinfo
->cur_comp_info
[ci
];
577 htest_one_block(cinfo
, MCU_data
[blkn
][0], entropy
->saved
.last_dc_val
[ci
],
578 entropy
->dc_count_ptrs
[compptr
->dc_tbl_no
],
579 entropy
->ac_count_ptrs
[compptr
->ac_tbl_no
]);
580 entropy
->saved
.last_dc_val
[ci
] = MCU_data
[blkn
][0][0];
588 * Finish up a statistics-gathering pass and create the new Huffman tables.
592 finish_pass_gather (j_compress_ptr cinfo
)
594 j_lossy_c_ptr lossyc
= (j_lossy_c_ptr
) cinfo
->codec
;
595 shuff_entropy_ptr entropy
= (shuff_entropy_ptr
) lossyc
->entropy_private
;
596 int ci
, dctbl
, actbl
;
597 jpeg_component_info
* compptr
;
599 boolean did_dc
[NUM_HUFF_TBLS
];
600 boolean did_ac
[NUM_HUFF_TBLS
];
602 /* It's important not to apply jpeg_gen_optimal_table more than once
603 * per table, because it clobbers the input frequency counts!
605 MEMZERO(did_dc
, SIZEOF(did_dc
));
606 MEMZERO(did_ac
, SIZEOF(did_ac
));
608 for (ci
= 0; ci
< cinfo
->comps_in_scan
; ci
++) {
609 compptr
= cinfo
->cur_comp_info
[ci
];
610 dctbl
= compptr
->dc_tbl_no
;
611 actbl
= compptr
->ac_tbl_no
;
612 if (! did_dc
[dctbl
]) {
613 htblptr
= & cinfo
->dc_huff_tbl_ptrs
[dctbl
];
614 if (*htblptr
== NULL
)
615 *htblptr
= jpeg_alloc_huff_table((j_common_ptr
) cinfo
);
616 jpeg_gen_optimal_table(cinfo
, *htblptr
, entropy
->dc_count_ptrs
[dctbl
]);
617 did_dc
[dctbl
] = TRUE
;
619 if (! did_ac
[actbl
]) {
620 htblptr
= & cinfo
->ac_huff_tbl_ptrs
[actbl
];
621 if (*htblptr
== NULL
)
622 *htblptr
= jpeg_alloc_huff_table((j_common_ptr
) cinfo
);
623 jpeg_gen_optimal_table(cinfo
, *htblptr
, entropy
->ac_count_ptrs
[actbl
]);
624 did_ac
[actbl
] = TRUE
;
630 #endif /* ENTROPY_OPT_SUPPORTED */
634 need_optimization_pass (j_compress_ptr cinfo
)
641 * Module initialization routine for Huffman entropy encoding.
645 jinit_shuff_encoder (j_compress_ptr cinfo
)
647 j_lossy_c_ptr lossyc
= (j_lossy_c_ptr
) cinfo
->codec
;
648 shuff_entropy_ptr entropy
;
651 entropy
= (shuff_entropy_ptr
)
652 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
653 SIZEOF(shuff_entropy_encoder
));
654 lossyc
->entropy_private
= (struct jpeg_entropy_encoder
*) entropy
;
655 lossyc
->pub
.entropy_start_pass
= start_pass_huff
;
656 lossyc
->pub
.need_optimization_pass
= need_optimization_pass
;
658 /* Mark tables unallocated */
659 for (i
= 0; i
< NUM_HUFF_TBLS
; i
++) {
660 entropy
->dc_derived_tbls
[i
] = entropy
->ac_derived_tbls
[i
] = NULL
;
661 #ifdef ENTROPY_OPT_SUPPORTED
662 entropy
->dc_count_ptrs
[i
] = entropy
->ac_count_ptrs
[i
] = NULL
;