blob: 8110c7e376c48fdc6a785fb3c239f51be1d9c381 [file] [log] [blame]
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001/*
2 * jchuff.c
3 *
Thomas G. Lane5ead57a1998-03-27 00:00:00 +00004 * Copyright (C) 1991-1997, Thomas G. Lane.
DRC6bb57b72011-04-26 22:08:31 +00005 * Copyright (C) 2009-2011, D. R. Commander.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00006 * This file is part of the Independent JPEG Group's software.
7 * For conditions of distribution and use, see the accompanying README file.
8 *
9 * This file contains Huffman entropy encoding routines.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000010 *
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.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000016 */
17
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000018#define JPEG_INTERNALS
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000019#include "jinclude.h"
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000020#include "jpeglib.h"
Thomas G. Lanebc79e061995-08-02 00:00:00 +000021#include "jchuff.h" /* Declarations shared with jcphuff.c */
DRC8443e522009-07-30 08:35:06 +000022#include <limits.h>
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000023
DRC99313382009-03-12 17:24:27 +000024static unsigned char jpeg_first_bit_table[65536];
DRC6bb57b72011-04-26 22:08:31 +000025static int jpeg_first_bit_table_init = 0;
DRC99313382009-03-12 17:24:27 +000026
DRC3cba8db2009-03-16 23:58:30 +000027#ifndef min
28 #define min(a,b) ((a)<(b)?(a):(b))
29#endif
30
DRC6bb57b72011-04-26 22:08:31 +000031
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000032/* Expanded entropy encoder object for Huffman encoding.
33 *
34 * The savable_state subrecord contains fields that change within an MCU,
35 * but must not be updated permanently until we complete the MCU.
36 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000037
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000038typedef struct {
DRC04899092010-02-26 23:01:19 +000039 size_t put_buffer; /* current bit-accumulation buffer */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000040 int put_bits; /* # of bits now in it */
41 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
42} savable_state;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000043
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000044/* This macro is to work around compilers with missing or broken
45 * structure assignment. You'll need to fix this code if you have
46 * such a compiler and you change MAX_COMPS_IN_SCAN.
47 */
48
49#ifndef NO_STRUCT_ASSIGN
50#define ASSIGN_STATE(dest,src) ((dest) = (src))
51#else
52#if MAX_COMPS_IN_SCAN == 4
53#define ASSIGN_STATE(dest,src) \
54 ((dest).put_buffer = (src).put_buffer, \
55 (dest).put_bits = (src).put_bits, \
56 (dest).last_dc_val[0] = (src).last_dc_val[0], \
57 (dest).last_dc_val[1] = (src).last_dc_val[1], \
58 (dest).last_dc_val[2] = (src).last_dc_val[2], \
59 (dest).last_dc_val[3] = (src).last_dc_val[3])
60#endif
61#endif
62
63
64typedef struct {
65 struct jpeg_entropy_encoder pub; /* public fields */
66
67 savable_state saved; /* Bit buffer & DC state at start of MCU */
68
69 /* These fields are NOT loaded into local working state. */
70 unsigned int restarts_to_go; /* MCUs left in this restart interval */
71 int next_restart_num; /* next restart number to write (0-7) */
72
73 /* Pointers to derived tables (these workspaces have image lifespan) */
Thomas G. Lanebc79e061995-08-02 00:00:00 +000074 c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
75 c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000076
77#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
78 long * dc_count_ptrs[NUM_HUFF_TBLS];
79 long * ac_count_ptrs[NUM_HUFF_TBLS];
80#endif
81} huff_entropy_encoder;
82
83typedef huff_entropy_encoder * huff_entropy_ptr;
84
85/* Working state while writing an MCU.
86 * This struct contains all the fields that are needed by subroutines.
87 */
88
89typedef struct {
90 JOCTET * next_output_byte; /* => next byte to write in buffer */
91 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
92 savable_state cur; /* Current bit buffer & DC state */
93 j_compress_ptr cinfo; /* dump_buffer needs access to this */
94} working_state;
95
96
97/* Forward declarations */
Thomas G. Lane489583f1996-02-07 00:00:00 +000098METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
99 JBLOCKROW *MCU_data));
100METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000101#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane489583f1996-02-07 00:00:00 +0000102METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
103 JBLOCKROW *MCU_data));
104METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000105#endif
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000106
107
108/*
109 * Initialize for a Huffman-compressed scan.
110 * If gather_statistics is TRUE, we do not output anything during the scan,
111 * just count the Huffman symbols used and generate Huffman code tables.
112 */
113
Thomas G. Lane489583f1996-02-07 00:00:00 +0000114METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000115start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
116{
117 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
118 int ci, dctbl, actbl;
119 jpeg_component_info * compptr;
120
121 if (gather_statistics) {
122#ifdef ENTROPY_OPT_SUPPORTED
123 entropy->pub.encode_mcu = encode_mcu_gather;
124 entropy->pub.finish_pass = finish_pass_gather;
125#else
126 ERREXIT(cinfo, JERR_NOT_COMPILED);
127#endif
128 } else {
129 entropy->pub.encode_mcu = encode_mcu_huff;
130 entropy->pub.finish_pass = finish_pass_huff;
131 }
132
133 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
134 compptr = cinfo->cur_comp_info[ci];
135 dctbl = compptr->dc_tbl_no;
136 actbl = compptr->ac_tbl_no;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000137 if (gather_statistics) {
138#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000139 /* Check for invalid table indexes */
140 /* (make_c_derived_tbl does this in the other path) */
141 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
142 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
143 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
144 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000145 /* Allocate and zero the statistics tables */
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000146 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000147 if (entropy->dc_count_ptrs[dctbl] == NULL)
148 entropy->dc_count_ptrs[dctbl] = (long *)
149 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
150 257 * SIZEOF(long));
151 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
152 if (entropy->ac_count_ptrs[actbl] == NULL)
153 entropy->ac_count_ptrs[actbl] = (long *)
154 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
155 257 * SIZEOF(long));
156 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
157#endif
158 } else {
159 /* Compute derived values for Huffman tables */
160 /* We may do this more than once for a table, but it's not expensive */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000161 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000162 & entropy->dc_derived_tbls[dctbl]);
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000163 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000164 & entropy->ac_derived_tbls[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000165 }
166 /* Initialize DC predictions to 0 */
167 entropy->saved.last_dc_val[ci] = 0;
168 }
169
170 /* Initialize bit buffer to empty */
171 entropy->saved.put_buffer = 0;
172 entropy->saved.put_bits = 0;
173
174 /* Initialize restart stuff */
175 entropy->restarts_to_go = cinfo->restart_interval;
176 entropy->next_restart_num = 0;
177}
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000178
179
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000180/*
181 * Compute the derived values for a Huffman table.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000182 * This routine also performs some validation checks on the table.
183 *
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000184 * Note this is also used by jcphuff.c.
185 */
186
Thomas G. Lane489583f1996-02-07 00:00:00 +0000187GLOBAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000188jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000189 c_derived_tbl ** pdtbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000190{
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000191 JHUFF_TBL *htbl;
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000192 c_derived_tbl *dtbl;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000193 int p, i, l, lastp, si, maxsymbol;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000194 char huffsize[257];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000195 unsigned int huffcode[257];
196 unsigned int code;
197
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000198 /* Note that huffsize[] and huffcode[] are filled in code-length order,
199 * paralleling the order of the symbols themselves in htbl->huffval[].
200 */
201
202 /* Find the input Huffman table */
203 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
204 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
205 htbl =
206 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
207 if (htbl == NULL)
208 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
209
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000210 /* Allocate a workspace if we haven't already done so. */
211 if (*pdtbl == NULL)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000212 *pdtbl = (c_derived_tbl *)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000213 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000214 SIZEOF(c_derived_tbl));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000215 dtbl = *pdtbl;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000216
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000217 /* Figure C.1: make table of Huffman code length for each symbol */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000218
219 p = 0;
220 for (l = 1; l <= 16; l++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000221 i = (int) htbl->bits[l];
222 if (i < 0 || p + i > 256) /* protect against table overrun */
223 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
224 while (i--)
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000225 huffsize[p++] = (char) l;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000226 }
227 huffsize[p] = 0;
228 lastp = p;
229
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000230 /* Figure C.2: generate the codes themselves */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000231 /* We also validate that the counts represent a legal Huffman code tree. */
232
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000233 code = 0;
234 si = huffsize[0];
235 p = 0;
236 while (huffsize[p]) {
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000237 while (((int) huffsize[p]) == si) {
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000238 huffcode[p++] = code;
239 code++;
240 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000241 /* code is now 1 more than the last code used for codelength si; but
242 * it must still fit in si bits, since no code is allowed to be all ones.
243 */
244 if (((INT32) code) >= (((INT32) 1) << si))
245 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000246 code <<= 1;
247 si++;
248 }
249
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000250 /* Figure C.3: generate encoding tables */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000251 /* These are code and size indexed by symbol value */
252
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000253 /* Set all codeless symbols to have code length 0;
254 * this lets us detect duplicate VAL entries here, and later
255 * allows emit_bits to detect any attempt to emit such symbols.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000256 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000257 MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000258
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000259 /* This is also a convenient place to check for out-of-range
260 * and duplicated VAL entries. We allow 0..255 for AC symbols
261 * but only 0..15 for DC. (We could constrain them further
262 * based on data depth and mode, but this seems enough.)
263 */
264 maxsymbol = isDC ? 15 : 255;
265
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000266 for (p = 0; p < lastp; p++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000267 i = htbl->huffval[p];
268 if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
269 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
270 dtbl->ehufco[i] = huffcode[p];
271 dtbl->ehufsi[i] = huffsize[p];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000272 }
DRC99313382009-03-12 17:24:27 +0000273
274 if(!jpeg_first_bit_table_init) {
275 for(i = 0; i < 65536; i++) {
276 int bit = 0, val = i;
277 while (val) {val >>= 1; bit++;}
278 jpeg_first_bit_table[i] = bit;
279 }
280 jpeg_first_bit_table_init = 1;
281 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000282}
283
284
285/* Outputting bytes to the file */
286
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000287/* Emit a byte, taking 'action' if must suspend. */
288#define emit_byte(state,val,action) \
289 { *(state)->next_output_byte++ = (JOCTET) (val); \
290 if (--(state)->free_in_buffer == 0) \
291 if (! dump_buffer(state)) \
292 { action; } }
293
294
Thomas G. Lane489583f1996-02-07 00:00:00 +0000295LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000296dump_buffer (working_state * state)
297/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000298{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000299 struct jpeg_destination_mgr * dest = state->cinfo->dest;
300
DRC86299882009-03-14 01:21:13 +0000301 dest->free_in_buffer = state->free_in_buffer;
302
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000303 if (! (*dest->empty_output_buffer) (state->cinfo))
304 return FALSE;
305 /* After a successful buffer dump, must reset buffer pointers */
306 state->next_output_byte = dest->next_output_byte;
307 state->free_in_buffer = dest->free_in_buffer;
308 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000309}
310
311
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000312/* Outputting bits to the file */
313
DRC6bb57b72011-04-26 22:08:31 +0000314/* These macros perform the same task as the emit_bits() function in the
315 * original libjpeg code. In addition to reducing overhead by explicitly
316 * inlining the code, additional performance is achieved by taking into
317 * account the size of the bit buffer and waiting until it is almost full
318 * before emptying it. This mostly benefits 64-bit platforms, since 6
319 * bytes can be stored in a 64-bit bit buffer before it has to be emptied.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000320 */
321
DRC6bb57b72011-04-26 22:08:31 +0000322#define EMIT_BYTE() { \
323 JOCTET c; \
324 put_bits -= 8; \
325 c = (JOCTET)GETJOCTET(put_buffer >> put_bits); \
326 *buffer++ = c; \
327 if (c == 0xFF) /* need to stuff a zero byte? */ \
328 *buffer++ = 0; \
DRC8443e522009-07-30 08:35:06 +0000329 }
330
DRC6bb57b72011-04-26 22:08:31 +0000331#define PUT_BITS(code, size) { \
332 put_bits += size; \
333 put_buffer = (put_buffer << size) | code; \
DRC8443e522009-07-30 08:35:06 +0000334}
335
DRC6bb57b72011-04-26 22:08:31 +0000336#define CHECKBUF15() { \
337 if (put_bits > 15) { \
338 EMIT_BYTE() \
339 EMIT_BYTE() \
340 } \
DRC8443e522009-07-30 08:35:06 +0000341}
342
DRC6bb57b72011-04-26 22:08:31 +0000343#define CHECKBUF31() { \
344 if (put_bits > 31) { \
345 EMIT_BYTE() \
346 EMIT_BYTE() \
347 EMIT_BYTE() \
348 EMIT_BYTE() \
349 } \
DRC8443e522009-07-30 08:35:06 +0000350}
351
DRC6bb57b72011-04-26 22:08:31 +0000352#define CHECKBUF47() { \
353 if (put_bits > 47) { \
354 EMIT_BYTE() \
355 EMIT_BYTE() \
356 EMIT_BYTE() \
357 EMIT_BYTE() \
358 EMIT_BYTE() \
359 EMIT_BYTE() \
360 } \
361}
DRC8443e522009-07-30 08:35:06 +0000362
DRC830d5fc2010-04-20 21:13:26 +0000363#if __WORDSIZE==64 || defined(_WIN64)
DRC8443e522009-07-30 08:35:06 +0000364
DRC6bb57b72011-04-26 22:08:31 +0000365#define EMIT_BITS(code, size) { \
366 CHECKBUF47() \
367 PUT_BITS(code, size) \
368}
369
370#define EMIT_CODE(code, size) { \
371 temp2 &= (((INT32) 1)<<nbits) - 1; \
372 CHECKBUF31() \
373 PUT_BITS(code, size) \
374 PUT_BITS(temp2, nbits) \
DRC8443e522009-07-30 08:35:06 +0000375 }
376
377#else
378
DRC6bb57b72011-04-26 22:08:31 +0000379#define EMIT_BITS(code, size) { \
380 PUT_BITS(code, size) \
381 CHECKBUF15() \
382}
383
384#define EMIT_CODE(code, size) { \
385 temp2 &= (((INT32) 1)<<nbits) - 1; \
386 PUT_BITS(code, size) \
387 CHECKBUF15() \
388 PUT_BITS(temp2, nbits) \
389 CHECKBUF15() \
DRC99313382009-03-12 17:24:27 +0000390 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000391
DRC8443e522009-07-30 08:35:06 +0000392#endif
393
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000394
DRC3cba8db2009-03-16 23:58:30 +0000395#define BUFSIZE (DCTSIZE2 * 2)
396
DRC6bb57b72011-04-26 22:08:31 +0000397#define LOAD_BUFFER() { \
398 if (state->free_in_buffer < BUFSIZE) { \
399 localbuf = 1; \
400 buffer = _buffer; \
401 } \
402 else buffer = state->next_output_byte; \
DRC3cba8db2009-03-16 23:58:30 +0000403 }
404
DRC6bb57b72011-04-26 22:08:31 +0000405#define STORE_BUFFER() { \
406 if (localbuf) { \
407 bytes = buffer - _buffer; \
408 buffer = _buffer; \
409 while (bytes > 0) { \
410 bytestocopy = min(bytes, state->free_in_buffer); \
411 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
412 state->next_output_byte += bytestocopy; \
413 buffer += bytestocopy; \
414 state->free_in_buffer -= bytestocopy; \
415 if (state->free_in_buffer == 0) \
416 if (! dump_buffer(state)) return FALSE; \
417 bytes -= bytestocopy; \
418 } \
419 } \
420 else { \
421 state->free_in_buffer -= (buffer - state->next_output_byte); \
422 state->next_output_byte = buffer; \
423 } \
DRC3cba8db2009-03-16 23:58:30 +0000424 }
425
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000426
Thomas G. Lane489583f1996-02-07 00:00:00 +0000427LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000428flush_bits (working_state * state)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000429{
DRC6bb57b72011-04-26 22:08:31 +0000430 JOCTET _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000431 size_t put_buffer; int put_bits;
432 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000433
DRC99313382009-03-12 17:24:27 +0000434 put_buffer = state->cur.put_buffer;
435 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000436 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000437
DRC6bb57b72011-04-26 22:08:31 +0000438 /* fill any partial byte with ones */
439 PUT_BITS(0x7F, 7)
440 while (put_bits >= 8) EMIT_BYTE()
DRC99313382009-03-12 17:24:27 +0000441
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000442 state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
443 state->cur.put_bits = 0;
DRC3cba8db2009-03-16 23:58:30 +0000444 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000445
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000446 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000447}
448
DRC6bb57b72011-04-26 22:08:31 +0000449
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000450/* Encode a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000451
Thomas G. Lane489583f1996-02-07 00:00:00 +0000452LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000453encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000454 c_derived_tbl *dctbl, c_derived_tbl *actbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000455{
DRC6bb57b72011-04-26 22:08:31 +0000456 int temp, temp2, temp3;
DRC99313382009-03-12 17:24:27 +0000457 int nbits;
DRC6bb57b72011-04-26 22:08:31 +0000458 int r, code, size;
459 JOCTET _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000460 size_t put_buffer; int put_bits;
DRC99313382009-03-12 17:24:27 +0000461 int code_0xf0 = actbl->ehufco[0xf0], size_0xf0 = actbl->ehufsi[0xf0];
DRC04899092010-02-26 23:01:19 +0000462 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000463
DRC99313382009-03-12 17:24:27 +0000464 put_buffer = state->cur.put_buffer;
465 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000466 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000467
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000468 /* Encode the DC coefficient difference per section F.1.2.1 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000469
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000470 temp = temp2 = block[0] - last_dc_val;
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000471
DRC6bb57b72011-04-26 22:08:31 +0000472 /* This is a well-known technique for obtaining the absolute value without a
473 * branch. It is derived from an assembly language technique presented in
474 * "How to Optimize for the Pentium Processors", Copyright (c) 1996, 1997 by
475 * Agner Fog.
476 */
477 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1);
478 temp ^= temp3;
479 temp -= temp3;
480
481 /* For a negative input, want temp2 = bitwise complement of abs(input) */
482 /* This code assumes we are on a two's complement machine */
483 temp2 += temp3;
484
485 /* Find the number of bits needed for the magnitude of the coefficient */
DRC8443e522009-07-30 08:35:06 +0000486 nbits = jpeg_first_bit_table[temp];
DRC6bb57b72011-04-26 22:08:31 +0000487
488 /* Emit the Huffman-coded symbol for the number of bits */
489 code = dctbl->ehufco[nbits];
490 size = dctbl->ehufsi[nbits];
491 PUT_BITS(code, size)
492 CHECKBUF15()
493
494 /* Mask off any extra bits in code */
495 temp2 &= (((INT32) 1)<<nbits) - 1;
496
497 /* Emit that number of bits of the value, if positive, */
498 /* or the complement of its magnitude, if negative. */
499 PUT_BITS(temp2, nbits)
500 CHECKBUF15()
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000501
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000502 /* Encode the AC coefficients per section F.1.2.2 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000503
504 r = 0; /* r = run length of zeros */
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000505
DRC6bb57b72011-04-26 22:08:31 +0000506/* Manually unroll the k loop to eliminate the counter variable. This
507 * improves performance greatly on systems with a limited number of
508 * registers (such as x86.)
509 */
510#define kloop(jpeg_natural_order_of_k) { \
511 if ((temp = block[jpeg_natural_order_of_k]) == 0) { \
512 r++; \
513 } else { \
514 temp2 = temp; \
515 /* Branch-less absolute value, bitwise complement, etc., same as above */ \
516 temp3 = temp >> (CHAR_BIT * sizeof(int) - 1); \
517 temp ^= temp3; \
518 temp -= temp3; \
519 temp2 += temp3; \
520 nbits = jpeg_first_bit_table[temp]; \
521 /* if run length > 15, must emit special run-length-16 codes (0xF0) */ \
522 while (r > 15) { \
523 EMIT_BITS(code_0xf0, size_0xf0) \
524 r -= 16; \
525 } \
526 /* Emit Huffman symbol for run length / number of bits */ \
527 temp3 = (r << 4) + nbits; \
528 code = actbl->ehufco[temp3]; \
529 size = actbl->ehufsi[temp3]; \
530 EMIT_CODE(code, size) \
DRC99313382009-03-12 17:24:27 +0000531 r = 0; \
DRC6bb57b72011-04-26 22:08:31 +0000532 } \
533}
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000534
DRC6bb57b72011-04-26 22:08:31 +0000535 /* One iteration for each value in jpeg_natural_order[] */
536 kloop(1); kloop(8); kloop(16); kloop(9); kloop(2); kloop(3);
537 kloop(10); kloop(17); kloop(24); kloop(32); kloop(25); kloop(18);
538 kloop(11); kloop(4); kloop(5); kloop(12); kloop(19); kloop(26);
539 kloop(33); kloop(40); kloop(48); kloop(41); kloop(34); kloop(27);
540 kloop(20); kloop(13); kloop(6); kloop(7); kloop(14); kloop(21);
541 kloop(28); kloop(35); kloop(42); kloop(49); kloop(56); kloop(57);
542 kloop(50); kloop(43); kloop(36); kloop(29); kloop(22); kloop(15);
543 kloop(23); kloop(30); kloop(37); kloop(44); kloop(51); kloop(58);
544 kloop(59); kloop(52); kloop(45); kloop(38); kloop(31); kloop(39);
545 kloop(46); kloop(53); kloop(60); kloop(61); kloop(54); kloop(47);
546 kloop(55); kloop(62); kloop(63);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000547
548 /* If the last coef(s) were zero, emit an end-of-block code */
DRC6bb57b72011-04-26 22:08:31 +0000549 if (r > 0) {
550 code = actbl->ehufco[0];
551 size = actbl->ehufsi[0];
552 EMIT_BITS(code, size)
553 }
DRC99313382009-03-12 17:24:27 +0000554
555 state->cur.put_buffer = put_buffer;
556 state->cur.put_bits = put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000557 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000558
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000559 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000560}
561
562
563/*
564 * Emit a restart marker & resynchronize predictions.
565 */
566
Thomas G. Lane489583f1996-02-07 00:00:00 +0000567LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000568emit_restart (working_state * state, int restart_num)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000569{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000570 int ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000571
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000572 if (! flush_bits(state))
573 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000574
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000575 emit_byte(state, 0xFF, return FALSE);
576 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000577
578 /* Re-initialize DC predictions to 0 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000579 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
580 state->cur.last_dc_val[ci] = 0;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000581
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000582 /* The restart counter is not updated until we successfully write the MCU. */
583
584 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000585}
586
587
588/*
589 * Encode and output one MCU's worth of Huffman-compressed coefficients.
590 */
591
Thomas G. Lane489583f1996-02-07 00:00:00 +0000592METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000593encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000594{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000595 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
596 working_state state;
597 int blkn, ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000598 jpeg_component_info * compptr;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000599
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000600 /* Load up working state */
601 state.next_output_byte = cinfo->dest->next_output_byte;
602 state.free_in_buffer = cinfo->dest->free_in_buffer;
603 ASSIGN_STATE(state.cur, entropy->saved);
604 state.cinfo = cinfo;
605
606 /* Emit restart marker if needed */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000607 if (cinfo->restart_interval) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000608 if (entropy->restarts_to_go == 0)
609 if (! emit_restart(&state, entropy->next_restart_num))
610 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000611 }
612
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000613 /* Encode the MCU data blocks */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000614 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
615 ci = cinfo->MCU_membership[blkn];
616 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000617 if (! encode_one_block(&state,
618 MCU_data[blkn][0], state.cur.last_dc_val[ci],
619 entropy->dc_derived_tbls[compptr->dc_tbl_no],
620 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
621 return FALSE;
622 /* Update last_dc_val */
623 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000624 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000625
626 /* Completed MCU, so update state */
627 cinfo->dest->next_output_byte = state.next_output_byte;
628 cinfo->dest->free_in_buffer = state.free_in_buffer;
629 ASSIGN_STATE(entropy->saved, state.cur);
630
631 /* Update restart-interval state too */
632 if (cinfo->restart_interval) {
633 if (entropy->restarts_to_go == 0) {
634 entropy->restarts_to_go = cinfo->restart_interval;
635 entropy->next_restart_num++;
636 entropy->next_restart_num &= 7;
637 }
638 entropy->restarts_to_go--;
639 }
640
641 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000642}
643
644
645/*
646 * Finish up at the end of a Huffman-compressed scan.
647 */
648
Thomas G. Lane489583f1996-02-07 00:00:00 +0000649METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000650finish_pass_huff (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000651{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000652 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
653 working_state state;
654
655 /* Load up working state ... flush_bits needs it */
656 state.next_output_byte = cinfo->dest->next_output_byte;
657 state.free_in_buffer = cinfo->dest->free_in_buffer;
658 ASSIGN_STATE(state.cur, entropy->saved);
659 state.cinfo = cinfo;
660
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000661 /* Flush out the last data */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000662 if (! flush_bits(&state))
663 ERREXIT(cinfo, JERR_CANT_SUSPEND);
664
665 /* Update state */
666 cinfo->dest->next_output_byte = state.next_output_byte;
667 cinfo->dest->free_in_buffer = state.free_in_buffer;
668 ASSIGN_STATE(entropy->saved, state.cur);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000669}
670
671
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000672/*
673 * Huffman coding optimization.
674 *
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000675 * We first scan the supplied data and count the number of uses of each symbol
676 * that is to be Huffman-coded. (This process MUST agree with the code above.)
677 * Then we build a Huffman coding tree for the observed counts.
678 * Symbols which are not needed at all for the particular image are not
679 * assigned any code, which saves space in the DHT marker as well as in
680 * the compressed data.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000681 */
682
683#ifdef ENTROPY_OPT_SUPPORTED
684
685
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000686/* Process a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000687
Thomas G. Lane489583f1996-02-07 00:00:00 +0000688LOCAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000689htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000690 long dc_counts[], long ac_counts[])
691{
692 register int temp;
693 register int nbits;
694 register int k, r;
695
696 /* Encode the DC coefficient difference per section F.1.2.1 */
697
698 temp = block[0] - last_dc_val;
699 if (temp < 0)
700 temp = -temp;
701
702 /* Find the number of bits needed for the magnitude of the coefficient */
703 nbits = 0;
704 while (temp) {
705 nbits++;
706 temp >>= 1;
707 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000708 /* Check for out-of-range coefficient values.
709 * Since we're encoding a difference, the range limit is twice as much.
710 */
711 if (nbits > MAX_COEF_BITS+1)
712 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000713
714 /* Count the Huffman symbol for the number of bits */
715 dc_counts[nbits]++;
716
717 /* Encode the AC coefficients per section F.1.2.2 */
718
719 r = 0; /* r = run length of zeros */
720
721 for (k = 1; k < DCTSIZE2; k++) {
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000722 if ((temp = block[jpeg_natural_order[k]]) == 0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000723 r++;
724 } else {
725 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
726 while (r > 15) {
727 ac_counts[0xF0]++;
728 r -= 16;
729 }
730
731 /* Find the number of bits needed for the magnitude of the coefficient */
732 if (temp < 0)
733 temp = -temp;
734
735 /* Find the number of bits needed for the magnitude of the coefficient */
736 nbits = 1; /* there must be at least one 1 bit */
737 while ((temp >>= 1))
738 nbits++;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000739 /* Check for out-of-range coefficient values */
740 if (nbits > MAX_COEF_BITS)
741 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000742
743 /* Count Huffman symbol for run length / number of bits */
744 ac_counts[(r << 4) + nbits]++;
745
746 r = 0;
747 }
748 }
749
750 /* If the last coef(s) were zero, emit an end-of-block code */
751 if (r > 0)
752 ac_counts[0]++;
753}
754
755
756/*
757 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
758 * No data is actually output, so no suspension return is possible.
759 */
760
Thomas G. Lane489583f1996-02-07 00:00:00 +0000761METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000762encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
763{
764 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
765 int blkn, ci;
766 jpeg_component_info * compptr;
767
768 /* Take care of restart intervals if needed */
769 if (cinfo->restart_interval) {
770 if (entropy->restarts_to_go == 0) {
771 /* Re-initialize DC predictions to 0 */
772 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
773 entropy->saved.last_dc_val[ci] = 0;
774 /* Update restart state */
775 entropy->restarts_to_go = cinfo->restart_interval;
776 }
777 entropy->restarts_to_go--;
778 }
779
780 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
781 ci = cinfo->MCU_membership[blkn];
782 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000783 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000784 entropy->dc_count_ptrs[compptr->dc_tbl_no],
785 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
786 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
787 }
788
789 return TRUE;
790}
791
792
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000793/*
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000794 * Generate the best Huffman code table for the given counts, fill htbl.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000795 * Note this is also used by jcphuff.c.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000796 *
797 * The JPEG standard requires that no symbol be assigned a codeword of all
798 * one bits (so that padding bits added at the end of a compressed segment
799 * can't look like a valid code). Because of the canonical ordering of
800 * codewords, this just means that there must be an unused slot in the
801 * longest codeword length category. Section K.2 of the JPEG spec suggests
802 * reserving such a slot by pretending that symbol 256 is a valid symbol
803 * with count 1. In theory that's not optimal; giving it count zero but
804 * including it in the symbol set anyway should give a better Huffman code.
805 * But the theoretically better code actually seems to come out worse in
806 * practice, because it produces more all-ones bytes (which incur stuffed
807 * zero bytes in the final file). In any case the difference is tiny.
808 *
809 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
810 * If some symbols have a very small but nonzero probability, the Huffman tree
811 * must be adjusted to meet the code length restriction. We currently use
812 * the adjustment method suggested in JPEG section K.2. This method is *not*
813 * optimal; it may not choose the best possible limited-length code. But
814 * typically only very-low-frequency symbols will be given less-than-optimal
815 * lengths, so the code is almost optimal. Experimental comparisons against
816 * an optimal limited-length-code algorithm indicate that the difference is
817 * microscopic --- usually less than a hundredth of a percent of total size.
818 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000819 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000820
Thomas G. Lane489583f1996-02-07 00:00:00 +0000821GLOBAL(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000822jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000823{
824#define MAX_CLEN 32 /* assumed maximum initial code length */
825 UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000826 int codesize[257]; /* codesize[k] = code length of symbol k */
827 int others[257]; /* next symbol in current branch of tree */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000828 int c1, c2;
829 int p, i, j;
830 long v;
831
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000832 /* This algorithm is explained in section K.2 of the JPEG standard */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000833
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000834 MEMZERO(bits, SIZEOF(bits));
835 MEMZERO(codesize, SIZEOF(codesize));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000836 for (i = 0; i < 257; i++)
837 others[i] = -1; /* init links to empty */
838
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000839 freq[256] = 1; /* make sure 256 has a nonzero count */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000840 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000841 * that no real symbol is given code-value of all ones, because 256
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000842 * will be placed last in the largest codeword category.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000843 */
844
845 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
846
847 for (;;) {
848 /* Find the smallest nonzero frequency, set c1 = its symbol */
849 /* In case of ties, take the larger symbol number */
850 c1 = -1;
851 v = 1000000000L;
852 for (i = 0; i <= 256; i++) {
853 if (freq[i] && freq[i] <= v) {
854 v = freq[i];
855 c1 = i;
856 }
857 }
858
859 /* Find the next smallest nonzero frequency, set c2 = its symbol */
860 /* In case of ties, take the larger symbol number */
861 c2 = -1;
862 v = 1000000000L;
863 for (i = 0; i <= 256; i++) {
864 if (freq[i] && freq[i] <= v && i != c1) {
865 v = freq[i];
866 c2 = i;
867 }
868 }
869
870 /* Done if we've merged everything into one frequency */
871 if (c2 < 0)
872 break;
873
874 /* Else merge the two counts/trees */
875 freq[c1] += freq[c2];
876 freq[c2] = 0;
877
878 /* Increment the codesize of everything in c1's tree branch */
879 codesize[c1]++;
880 while (others[c1] >= 0) {
881 c1 = others[c1];
882 codesize[c1]++;
883 }
884
885 others[c1] = c2; /* chain c2 onto c1's tree branch */
886
887 /* Increment the codesize of everything in c2's tree branch */
888 codesize[c2]++;
889 while (others[c2] >= 0) {
890 c2 = others[c2];
891 codesize[c2]++;
892 }
893 }
894
895 /* Now count the number of symbols of each code length */
896 for (i = 0; i <= 256; i++) {
897 if (codesize[i]) {
898 /* The JPEG standard seems to think that this can't happen, */
899 /* but I'm paranoid... */
900 if (codesize[i] > MAX_CLEN)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000901 ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000902
903 bits[codesize[i]]++;
904 }
905 }
906
907 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
908 * Huffman procedure assigned any such lengths, we must adjust the coding.
909 * Here is what the JPEG spec says about how this next bit works:
910 * Since symbols are paired for the longest Huffman code, the symbols are
911 * removed from this length category two at a time. The prefix for the pair
912 * (which is one bit shorter) is allocated to one of the pair; then,
913 * skipping the BITS entry for that prefix length, a code word from the next
914 * shortest nonzero BITS entry is converted into a prefix for two code words
915 * one bit longer.
916 */
917
918 for (i = MAX_CLEN; i > 16; i--) {
919 while (bits[i] > 0) {
920 j = i - 2; /* find length of new prefix to be used */
921 while (bits[j] == 0)
922 j--;
923
924 bits[i] -= 2; /* remove two symbols */
925 bits[i-1]++; /* one goes in this length */
926 bits[j+1] += 2; /* two new symbols in this length */
927 bits[j]--; /* symbol of this length is now a prefix */
928 }
929 }
930
931 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
932 while (bits[i] == 0) /* find largest codelength still in use */
933 i--;
934 bits[i]--;
935
936 /* Return final symbol counts (only for lengths 0..16) */
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000937 MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000938
939 /* Return a list of the symbols sorted by code length */
940 /* It's not real clear to me why we don't need to consider the codelength
941 * changes made above, but the JPEG spec seems to think this works.
942 */
943 p = 0;
944 for (i = 1; i <= MAX_CLEN; i++) {
945 for (j = 0; j <= 255; j++) {
946 if (codesize[j] == i) {
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000947 htbl->huffval[p] = (UINT8) j;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000948 p++;
949 }
950 }
951 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000952
953 /* Set sent_table FALSE so updated table will be written to JPEG file. */
954 htbl->sent_table = FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000955}
956
957
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000958/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000959 * Finish up a statistics-gathering pass and create the new Huffman tables.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000960 */
961
Thomas G. Lane489583f1996-02-07 00:00:00 +0000962METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000963finish_pass_gather (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000964{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000965 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
966 int ci, dctbl, actbl;
967 jpeg_component_info * compptr;
968 JHUFF_TBL **htblptr;
969 boolean did_dc[NUM_HUFF_TBLS];
970 boolean did_ac[NUM_HUFF_TBLS];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000971
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000972 /* It's important not to apply jpeg_gen_optimal_table more than once
973 * per table, because it clobbers the input frequency counts!
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000974 */
975 MEMZERO(did_dc, SIZEOF(did_dc));
976 MEMZERO(did_ac, SIZEOF(did_ac));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000977
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000978 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
979 compptr = cinfo->cur_comp_info[ci];
980 dctbl = compptr->dc_tbl_no;
981 actbl = compptr->ac_tbl_no;
982 if (! did_dc[dctbl]) {
983 htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000984 if (*htblptr == NULL)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000985 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000986 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000987 did_dc[dctbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000988 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000989 if (! did_ac[actbl]) {
990 htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000991 if (*htblptr == NULL)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000992 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000993 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000994 did_ac[actbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000995 }
996 }
997}
998
999
1000#endif /* ENTROPY_OPT_SUPPORTED */
1001
1002
1003/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001004 * Module initialization routine for Huffman entropy encoding.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001005 */
1006
Thomas G. Lane489583f1996-02-07 00:00:00 +00001007GLOBAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001008jinit_huff_encoder (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001009{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001010 huff_entropy_ptr entropy;
1011 int i;
1012
1013 entropy = (huff_entropy_ptr)
1014 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1015 SIZEOF(huff_entropy_encoder));
1016 cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
1017 entropy->pub.start_pass = start_pass_huff;
1018
1019 /* Mark tables unallocated */
1020 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1021 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001022#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001023 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001024#endif
1025 }
1026}