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 lossless 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 "jlossls.h" /* Private declarations for lossless 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 */
39 /* This macro is to work around compilers with missing or broken
40 * structure assignment. You'll need to fix this code if you have
41 * such a compiler and you change MAX_COMPS_IN_SCAN.
44 #ifndef NO_STRUCT_ASSIGN
45 #define ASSIGN_STATE(dest,src) ((dest) = (src))
47 #define ASSIGN_STATE(dest,src) \
48 ((dest).put_buffer = (src).put_buffer, \
49 (dest).put_bits = (src).put_bits)
54 int ci
, yoffset
, MCU_width
;
59 savable_state saved
; /* Bit buffer at start of MCU */
61 /* These fields are NOT loaded into local working state. */
62 unsigned int restarts_to_go
; /* MCUs left in this restart interval */
63 int next_restart_num
; /* next restart number to write (0-7) */
65 /* Pointers to derived tables (these workspaces have image lifespan) */
66 c_derived_tbl
* derived_tbls
[NUM_HUFF_TBLS
];
68 /* Pointers to derived tables to be used for each data unit within an MCU */
69 c_derived_tbl
* cur_tbls
[C_MAX_DATA_UNITS_IN_MCU
];
71 #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
72 long * count_ptrs
[NUM_HUFF_TBLS
];
74 /* Pointers to stats tables to be used for each data unit within an MCU */
75 long * cur_counts
[C_MAX_DATA_UNITS_IN_MCU
];
78 /* Pointers to the proper input difference row for each group of data units
79 * within an MCU. For each component, there are Vi groups of Hi data units.
81 JDIFFROW input_ptr
[C_MAX_DATA_UNITS_IN_MCU
];
83 /* Number of input pointers in use for the current MCU. This is the sum
84 * of all Vi in the MCU.
88 /* Information used for positioning the input pointers within the input
91 lhe_input_ptr_info input_ptr_info
[C_MAX_DATA_UNITS_IN_MCU
];
93 /* Index of the proper input pointer for each data unit within an MCU */
94 int input_ptr_index
[C_MAX_DATA_UNITS_IN_MCU
];
96 } lhuff_entropy_encoder
;
98 typedef lhuff_entropy_encoder
* lhuff_entropy_ptr
;
100 /* Working state while writing an MCU.
101 * This struct contains all the fields that are needed by subroutines.
105 JOCTET
* next_output_byte
; /* => next byte to write in buffer */
106 size_t free_in_buffer
; /* # of byte spaces remaining in buffer */
107 savable_state cur
; /* Current bit buffer & DC state */
108 j_compress_ptr cinfo
; /* dump_buffer needs access to this */
112 /* Forward declarations */
113 METHODDEF(JDIMENSION
) encode_mcus_huff (j_compress_ptr cinfo
,
115 JDIMENSION MCU_row_num
,
116 JDIMENSION MCU_col_num
,
118 METHODDEF(void) finish_pass_huff
JPP((j_compress_ptr cinfo
));
119 #ifdef ENTROPY_OPT_SUPPORTED
120 METHODDEF(JDIMENSION
) encode_mcus_gather (j_compress_ptr cinfo
,
122 JDIMENSION MCU_row_num
,
123 JDIMENSION MCU_col_num
,
125 METHODDEF(void) finish_pass_gather
JPP((j_compress_ptr cinfo
));
130 * Initialize for a Huffman-compressed scan.
131 * If gather_statistics is TRUE, we do not output anything during the scan,
132 * just count the Huffman symbols used and generate Huffman code tables.
136 start_pass_huff (j_compress_ptr cinfo
, boolean gather_statistics
)
138 j_lossless_c_ptr losslsc
= (j_lossless_c_ptr
) cinfo
->codec
;
139 lhuff_entropy_ptr entropy
= (lhuff_entropy_ptr
) losslsc
->entropy_private
;
140 int ci
, dctbl
, sampn
, ptrn
, yoffset
, xoffset
;
141 jpeg_component_info
* compptr
;
143 if (gather_statistics
) {
144 #ifdef ENTROPY_OPT_SUPPORTED
145 losslsc
->entropy_encode_mcus
= encode_mcus_gather
;
146 losslsc
->pub
.entropy_finish_pass
= finish_pass_gather
;
148 ERREXIT(cinfo
, JERR_NOT_COMPILED
);
151 losslsc
->entropy_encode_mcus
= encode_mcus_huff
;
152 losslsc
->pub
.entropy_finish_pass
= finish_pass_huff
;
155 for (ci
= 0; ci
< cinfo
->comps_in_scan
; ci
++) {
156 compptr
= cinfo
->cur_comp_info
[ci
];
157 dctbl
= compptr
->dc_tbl_no
;
158 if (gather_statistics
) {
159 #ifdef ENTROPY_OPT_SUPPORTED
160 /* Check for invalid table indexes */
161 /* (make_c_derived_tbl does this in the other path) */
162 if (dctbl
< 0 || dctbl
>= NUM_HUFF_TBLS
)
163 ERREXIT1(cinfo
, JERR_NO_HUFF_TABLE
, dctbl
);
164 /* Allocate and zero the statistics tables */
165 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
166 if (entropy
->count_ptrs
[dctbl
] == NULL
)
167 entropy
->count_ptrs
[dctbl
] = (long *)
168 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
170 MEMZERO(entropy
->count_ptrs
[dctbl
], 257 * SIZEOF(long));
173 /* Compute derived values for Huffman tables */
174 /* We may do this more than once for a table, but it's not expensive */
175 jpeg_make_c_derived_tbl(cinfo
, TRUE
, dctbl
,
176 & entropy
->derived_tbls
[dctbl
]);
180 /* Precalculate encoding info for each sample in an MCU of this scan */
181 for (sampn
= 0, ptrn
= 0; sampn
< cinfo
->data_units_in_MCU
;) {
182 compptr
= cinfo
->cur_comp_info
[cinfo
->MCU_membership
[sampn
]];
183 ci
= compptr
->component_index
;
184 /* ci = cinfo->MCU_membership[sampn];
185 compptr = cinfo->cur_comp_info[ci];*/
186 for (yoffset
= 0; yoffset
< compptr
->MCU_height
; yoffset
++, ptrn
++) {
187 /* Precalculate the setup info for each input pointer */
188 entropy
->input_ptr_info
[ptrn
].ci
= ci
;
189 entropy
->input_ptr_info
[ptrn
].yoffset
= yoffset
;
190 entropy
->input_ptr_info
[ptrn
].MCU_width
= compptr
->MCU_width
;
191 for (xoffset
= 0; xoffset
< compptr
->MCU_width
; xoffset
++, sampn
++) {
192 /* Precalculate the input pointer index for each sample */
193 entropy
->input_ptr_index
[sampn
] = ptrn
;
194 /* Precalculate which tables to use for each sample */
195 entropy
->cur_tbls
[sampn
] = entropy
->derived_tbls
[compptr
->dc_tbl_no
];
196 entropy
->cur_counts
[sampn
] = entropy
->count_ptrs
[compptr
->dc_tbl_no
];
200 entropy
->num_input_ptrs
= ptrn
;
202 /* Initialize bit buffer to empty */
203 entropy
->saved
.put_buffer
= 0;
204 entropy
->saved
.put_bits
= 0;
206 /* Initialize restart stuff */
207 entropy
->restarts_to_go
= cinfo
->restart_interval
;
208 entropy
->next_restart_num
= 0;
212 /* Outputting bytes to the file */
214 /* Emit a byte, taking 'action' if must suspend. */
215 #define emit_byte(state,val,action) \
216 { *(state)->next_output_byte++ = (JOCTET) (val); \
217 if (--(state)->free_in_buffer == 0) \
218 if (! dump_buffer(state)) \
223 dump_buffer (working_state
* state
)
224 /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
226 struct jpeg_destination_mgr
* dest
= state
->cinfo
->dest
;
228 if (! (*dest
->empty_output_buffer
) (state
->cinfo
))
230 /* After a successful buffer dump, must reset buffer pointers */
231 state
->next_output_byte
= dest
->next_output_byte
;
232 state
->free_in_buffer
= dest
->free_in_buffer
;
237 /* Outputting bits to the file */
239 /* Only the right 24 bits of put_buffer are used; the valid bits are
240 * left-justified in this part. At most 16 bits can be passed to emit_bits
241 * in one call, and we never retain more than 7 bits in put_buffer
242 * between calls, so 24 bits are sufficient.
247 emit_bits (working_state
* state
, unsigned int code
, int size
)
248 /* Emit some bits; return TRUE if successful, FALSE if must suspend */
250 /* This routine is heavily used, so it's worth coding tightly. */
251 register INT32 put_buffer
= (INT32
) code
;
252 register int put_bits
= state
->cur
.put_bits
;
254 /* if size is 0, caller used an invalid Huffman table entry */
256 ERREXIT(state
->cinfo
, JERR_HUFF_MISSING_CODE
);
258 put_buffer
&= (((INT32
) 1)<<size
) - 1; /* mask off any extra bits in code */
260 put_bits
+= size
; /* new number of bits in buffer */
262 put_buffer
<<= 24 - put_bits
; /* align incoming bits */
264 put_buffer
|= state
->cur
.put_buffer
; /* and merge with old buffer contents */
266 while (put_bits
>= 8) {
267 int c
= (int) ((put_buffer
>> 16) & 0xFF);
269 emit_byte(state
, c
, return FALSE
);
270 if (c
== 0xFF) { /* need to stuff a zero byte? */
271 emit_byte(state
, 0, return FALSE
);
277 state
->cur
.put_buffer
= put_buffer
; /* update state variables */
278 state
->cur
.put_bits
= put_bits
;
285 flush_bits (working_state
* state
)
287 if (! emit_bits(state
, 0x7F, 7)) /* fill any partial byte with ones */
289 state
->cur
.put_buffer
= 0; /* and reset bit-buffer to empty */
290 state
->cur
.put_bits
= 0;
296 * Emit a restart marker & resynchronize predictions.
300 emit_restart (working_state
* state
, int restart_num
)
304 if (! flush_bits(state
))
307 emit_byte(state
, 0xFF, return FALSE
);
308 emit_byte(state
, JPEG_RST0
+ restart_num
, return FALSE
);
310 /* The restart counter is not updated until we successfully write the MCU. */
317 * Encode and output one nMCU's worth of Huffman-compressed differences.
320 METHODDEF(JDIMENSION
)
321 encode_mcus_huff (j_compress_ptr cinfo
, JDIFFIMAGE diff_buf
,
322 JDIMENSION MCU_row_num
, JDIMENSION MCU_col_num
,
325 j_lossless_c_ptr losslsc
= (j_lossless_c_ptr
) cinfo
->codec
;
326 lhuff_entropy_ptr entropy
= (lhuff_entropy_ptr
) losslsc
->entropy_private
;
328 int mcu_num
, sampn
, ci
, yoffset
, MCU_width
, ptrn
;
329 jpeg_component_info
* compptr
;
331 /* Load up working state */
332 state
.next_output_byte
= cinfo
->dest
->next_output_byte
;
333 state
.free_in_buffer
= cinfo
->dest
->free_in_buffer
;
334 ASSIGN_STATE(state
.cur
, entropy
->saved
);
337 /* Emit restart marker if needed */
338 if (cinfo
->restart_interval
) {
339 if (entropy
->restarts_to_go
== 0)
340 if (! emit_restart(&state
, entropy
->next_restart_num
))
344 /* Set input pointer locations based on MCU_col_num */
345 for (ptrn
= 0; ptrn
< entropy
->num_input_ptrs
; ptrn
++) {
346 ci
= entropy
->input_ptr_info
[ptrn
].ci
;
347 yoffset
= entropy
->input_ptr_info
[ptrn
].yoffset
;
348 MCU_width
= entropy
->input_ptr_info
[ptrn
].MCU_width
;
349 entropy
->input_ptr
[ptrn
] =
350 diff_buf
[ci
][MCU_row_num
+ yoffset
] + (MCU_col_num
* MCU_width
);
353 for (mcu_num
= 0; mcu_num
< nMCU
; mcu_num
++) {
355 /* Inner loop handles the samples in the MCU */
356 for (sampn
= 0; sampn
< cinfo
->data_units_in_MCU
; sampn
++) {
357 register int temp
, temp2
, temp3
;
359 c_derived_tbl
*dctbl
= entropy
->cur_tbls
[sampn
];
361 /* Encode the difference per section H.1.2.2 */
363 /* Input the sample difference */
364 temp
= *entropy
->input_ptr
[entropy
->input_ptr_index
[sampn
]]++;
366 if (temp
& 0x8000) { /* instead of temp < 0 */
367 temp
= (-temp
) & 0x7FFF; /* absolute value, mod 2^16 */
368 if (temp
== 0) /* special case: magnitude = 32768 */
369 temp2
= temp
= 0x8000;
370 temp2
= ~ temp
; /* one's complement of magnitude */
372 temp
&= 0x7FFF; /* abs value mod 2^16 */
373 temp2
= temp
; /* magnitude */
376 /* Find the number of bits needed for the magnitude of the difference */
382 /* Check for out-of-range difference values.
384 if (nbits
> MAX_DIFF_BITS
)
385 ERREXIT(cinfo
, JERR_BAD_DIFF
);
387 /* Emit the Huffman-coded symbol for the number of bits */
388 if (! emit_bits(&state
, dctbl
->ehufco
[nbits
], dctbl
->ehufsi
[nbits
]))
391 /* Emit that number of bits of the value, if positive, */
392 /* or the complement of its magnitude, if negative. */
393 if (nbits
&& /* emit_bits rejects calls with size 0 */
394 nbits
!= 16) /* special case: no bits should be emitted */
395 if (! emit_bits(&state
, (unsigned int) temp2
, nbits
))
399 /* Completed MCU, so update state */
400 cinfo
->dest
->next_output_byte
= state
.next_output_byte
;
401 cinfo
->dest
->free_in_buffer
= state
.free_in_buffer
;
402 ASSIGN_STATE(entropy
->saved
, state
.cur
);
404 /* Update restart-interval state too */
405 if (cinfo
->restart_interval
) {
406 if (entropy
->restarts_to_go
== 0) {
407 entropy
->restarts_to_go
= cinfo
->restart_interval
;
408 entropy
->next_restart_num
++;
409 entropy
->next_restart_num
&= 7;
411 entropy
->restarts_to_go
--;
421 * Finish up at the end of a Huffman-compressed scan.
425 finish_pass_huff (j_compress_ptr cinfo
)
427 j_lossless_c_ptr losslsc
= (j_lossless_c_ptr
) cinfo
->codec
;
428 lhuff_entropy_ptr entropy
= (lhuff_entropy_ptr
) losslsc
->entropy_private
;
431 /* Load up working state ... flush_bits needs it */
432 state
.next_output_byte
= cinfo
->dest
->next_output_byte
;
433 state
.free_in_buffer
= cinfo
->dest
->free_in_buffer
;
434 ASSIGN_STATE(state
.cur
, entropy
->saved
);
437 /* Flush out the last data */
438 if (! flush_bits(&state
))
439 ERREXIT(cinfo
, JERR_CANT_SUSPEND
);
442 cinfo
->dest
->next_output_byte
= state
.next_output_byte
;
443 cinfo
->dest
->free_in_buffer
= state
.free_in_buffer
;
444 ASSIGN_STATE(entropy
->saved
, state
.cur
);
449 * Huffman coding optimization.
451 * We first scan the supplied data and count the number of uses of each symbol
452 * that is to be Huffman-coded. (This process MUST agree with the code above.)
453 * Then we build a Huffman coding tree for the observed counts.
454 * Symbols which are not needed at all for the particular image are not
455 * assigned any code, which saves space in the DHT marker as well as in
456 * the compressed data.
459 #ifdef ENTROPY_OPT_SUPPORTED
462 * Trial-encode one nMCU's worth of Huffman-compressed differences.
463 * No data is actually output, so no suspension return is possible.
466 METHODDEF(JDIMENSION
)
467 encode_mcus_gather (j_compress_ptr cinfo
, JDIFFIMAGE diff_buf
,
468 JDIMENSION MCU_row_num
, JDIMENSION MCU_col_num
,
471 j_lossless_c_ptr losslsc
= (j_lossless_c_ptr
) cinfo
->codec
;
472 lhuff_entropy_ptr entropy
= (lhuff_entropy_ptr
) losslsc
->entropy_private
;
473 int mcu_num
, sampn
, ci
, yoffset
, MCU_width
, ptrn
;
474 jpeg_component_info
* compptr
;
476 /* Take care of restart intervals if needed */
477 if (cinfo
->restart_interval
) {
478 if (entropy
->restarts_to_go
== 0) {
479 /* Update restart state */
480 entropy
->restarts_to_go
= cinfo
->restart_interval
;
482 entropy
->restarts_to_go
--;
485 /* Set input pointer locations based on MCU_col_num */
486 for (ptrn
= 0; ptrn
< entropy
->num_input_ptrs
; ptrn
++) {
487 ci
= entropy
->input_ptr_info
[ptrn
].ci
;
488 yoffset
= entropy
->input_ptr_info
[ptrn
].yoffset
;
489 MCU_width
= entropy
->input_ptr_info
[ptrn
].MCU_width
;
490 entropy
->input_ptr
[ptrn
] =
491 diff_buf
[ci
][MCU_row_num
+ yoffset
] + (MCU_col_num
* MCU_width
);
494 for (mcu_num
= 0; mcu_num
< nMCU
; mcu_num
++) {
496 /* Inner loop handles the samples in the MCU */
497 for (sampn
= 0; sampn
< cinfo
->data_units_in_MCU
; sampn
++) {
500 c_derived_tbl
*dctbl
= entropy
->cur_tbls
[sampn
];
501 long * counts
= entropy
->cur_counts
[sampn
];
503 /* Encode the difference per section H.1.2.2 */
505 /* Input the sample difference */
506 temp
= *entropy
->input_ptr
[entropy
->input_ptr_index
[sampn
]]++;
508 if (temp
& 0x8000) { /* instead of temp < 0 */
509 temp
= (-temp
) & 0x7FFF; /* absolute value, mod 2^16 */
510 if (temp
== 0) /* special case: magnitude = 32768 */
513 temp
&= 0x7FFF; /* abs value mod 2^16 */
515 /* Find the number of bits needed for the magnitude of the difference */
521 /* Check for out-of-range difference values.
523 if (nbits
> MAX_DIFF_BITS
)
524 ERREXIT(cinfo
, JERR_BAD_DIFF
);
526 /* Count the Huffman symbol for the number of bits */
536 * Finish up a statistics-gathering pass and create the new Huffman tables.
540 finish_pass_gather (j_compress_ptr cinfo
)
542 j_lossless_c_ptr losslsc
= (j_lossless_c_ptr
) cinfo
->codec
;
543 lhuff_entropy_ptr entropy
= (lhuff_entropy_ptr
) losslsc
->entropy_private
;
545 jpeg_component_info
* compptr
;
547 boolean did_dc
[NUM_HUFF_TBLS
];
549 /* It's important not to apply jpeg_gen_optimal_table more than once
550 * per table, because it clobbers the input frequency counts!
552 MEMZERO(did_dc
, SIZEOF(did_dc
));
554 for (ci
= 0; ci
< cinfo
->comps_in_scan
; ci
++) {
555 compptr
= cinfo
->cur_comp_info
[ci
];
556 dctbl
= compptr
->dc_tbl_no
;
557 if (! did_dc
[dctbl
]) {
558 htblptr
= & cinfo
->dc_huff_tbl_ptrs
[dctbl
];
559 if (*htblptr
== NULL
)
560 *htblptr
= jpeg_alloc_huff_table((j_common_ptr
) cinfo
);
561 jpeg_gen_optimal_table(cinfo
, *htblptr
, entropy
->count_ptrs
[dctbl
]);
562 did_dc
[dctbl
] = TRUE
;
568 #endif /* ENTROPY_OPT_SUPPORTED */
572 need_optimization_pass (j_compress_ptr cinfo
)
579 * Module initialization routine for Huffman entropy encoding.
583 jinit_lhuff_encoder (j_compress_ptr cinfo
)
585 j_lossless_c_ptr losslsc
= (j_lossless_c_ptr
) cinfo
->codec
;
586 lhuff_entropy_ptr entropy
;
589 entropy
= (lhuff_entropy_ptr
)
590 (*cinfo
->mem
->alloc_small
) ((j_common_ptr
) cinfo
, JPOOL_IMAGE
,
591 SIZEOF(lhuff_entropy_encoder
));
592 losslsc
->entropy_private
= (struct jpeg_entropy_encoder
*) entropy
;
593 losslsc
->pub
.entropy_start_pass
= start_pass_huff
;
594 losslsc
->pub
.need_optimization_pass
= need_optimization_pass
;
596 /* Mark tables unallocated */
597 for (i
= 0; i
< NUM_HUFF_TBLS
; i
++) {
598 entropy
->derived_tbls
[i
] = NULL
;
599 #ifdef ENTROPY_OPT_SUPPORTED
600 entropy
->count_ptrs
[i
] = NULL
;