blob: 8a46b98338b55cde5288177849b69e9944cf494c [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.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00005 * This file is part of the Independent JPEG Group's software.
6 * For conditions of distribution and use, see the accompanying README file.
7 *
8 * This file contains Huffman entropy encoding routines.
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00009 *
10 * Much of the complexity here has to do with supporting output suspension.
11 * If the data destination module demands suspension, we want to be able to
12 * back up to the start of the current MCU. To do this, we copy state
13 * variables into local working storage, and update them back to the
14 * permanent JPEG objects only upon successful completion of an MCU.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000015 */
16
DRC99313382009-03-12 17:24:27 +000017/* Modifications:
18 * Copyright (C)2007 Sun Microsystems, Inc.
19 * Copyright (C)2009 D. R. Commander
20 *
21 * This library is free software and may be redistributed and/or modified under
22 * the terms of the wxWindows Library License, Version 3.1 or (at your option)
23 * any later version. The full license is in the LICENSE.txt file included
24 * with this distribution.
25 *
26 * This library is distributed in the hope that it will be useful,
27 * but WITHOUT ANY WARRANTY; without even the implied warranty of
28 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
29 * wxWindows Library License for more details.
30 */
31
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000032#define JPEG_INTERNALS
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000033#include "jinclude.h"
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000034#include "jpeglib.h"
Thomas G. Lanebc79e061995-08-02 00:00:00 +000035#include "jchuff.h" /* Declarations shared with jcphuff.c */
DRC8443e522009-07-30 08:35:06 +000036#include <limits.h>
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000037
DRC99313382009-03-12 17:24:27 +000038static unsigned char jpeg_first_bit_table[65536];
DRCa46830b2010-11-23 18:00:46 +000039static int jpeg_first_bit_table_init=0;
DRC99313382009-03-12 17:24:27 +000040
DRC3cba8db2009-03-16 23:58:30 +000041#ifndef min
42 #define min(a,b) ((a)<(b)?(a):(b))
43#endif
44
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000045/* Expanded entropy encoder object for Huffman encoding.
46 *
47 * The savable_state subrecord contains fields that change within an MCU,
48 * but must not be updated permanently until we complete the MCU.
49 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000050
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000051typedef struct {
DRC04899092010-02-26 23:01:19 +000052 size_t put_buffer; /* current bit-accumulation buffer */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000053 int put_bits; /* # of bits now in it */
54 int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
55} savable_state;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +000056
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000057/* This macro is to work around compilers with missing or broken
58 * structure assignment. You'll need to fix this code if you have
59 * such a compiler and you change MAX_COMPS_IN_SCAN.
60 */
61
62#ifndef NO_STRUCT_ASSIGN
63#define ASSIGN_STATE(dest,src) ((dest) = (src))
64#else
65#if MAX_COMPS_IN_SCAN == 4
66#define ASSIGN_STATE(dest,src) \
67 ((dest).put_buffer = (src).put_buffer, \
68 (dest).put_bits = (src).put_bits, \
69 (dest).last_dc_val[0] = (src).last_dc_val[0], \
70 (dest).last_dc_val[1] = (src).last_dc_val[1], \
71 (dest).last_dc_val[2] = (src).last_dc_val[2], \
72 (dest).last_dc_val[3] = (src).last_dc_val[3])
73#endif
74#endif
75
76
77typedef struct {
78 struct jpeg_entropy_encoder pub; /* public fields */
79
80 savable_state saved; /* Bit buffer & DC state at start of MCU */
81
82 /* These fields are NOT loaded into local working state. */
83 unsigned int restarts_to_go; /* MCUs left in this restart interval */
84 int next_restart_num; /* next restart number to write (0-7) */
85
86 /* Pointers to derived tables (these workspaces have image lifespan) */
Thomas G. Lanebc79e061995-08-02 00:00:00 +000087 c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
88 c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +000089
90#ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
91 long * dc_count_ptrs[NUM_HUFF_TBLS];
92 long * ac_count_ptrs[NUM_HUFF_TBLS];
93#endif
94} huff_entropy_encoder;
95
96typedef huff_entropy_encoder * huff_entropy_ptr;
97
98/* Working state while writing an MCU.
99 * This struct contains all the fields that are needed by subroutines.
100 */
101
102typedef struct {
103 JOCTET * next_output_byte; /* => next byte to write in buffer */
104 size_t free_in_buffer; /* # of byte spaces remaining in buffer */
105 savable_state cur; /* Current bit buffer & DC state */
106 j_compress_ptr cinfo; /* dump_buffer needs access to this */
107} working_state;
108
109
110/* Forward declarations */
Thomas G. Lane489583f1996-02-07 00:00:00 +0000111METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
112 JBLOCKROW *MCU_data));
113METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000114#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane489583f1996-02-07 00:00:00 +0000115METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
116 JBLOCKROW *MCU_data));
117METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000118#endif
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000119
120
121/*
122 * Initialize for a Huffman-compressed scan.
123 * If gather_statistics is TRUE, we do not output anything during the scan,
124 * just count the Huffman symbols used and generate Huffman code tables.
125 */
126
Thomas G. Lane489583f1996-02-07 00:00:00 +0000127METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000128start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
129{
130 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
131 int ci, dctbl, actbl;
132 jpeg_component_info * compptr;
133
134 if (gather_statistics) {
135#ifdef ENTROPY_OPT_SUPPORTED
136 entropy->pub.encode_mcu = encode_mcu_gather;
137 entropy->pub.finish_pass = finish_pass_gather;
138#else
139 ERREXIT(cinfo, JERR_NOT_COMPILED);
140#endif
141 } else {
142 entropy->pub.encode_mcu = encode_mcu_huff;
143 entropy->pub.finish_pass = finish_pass_huff;
144 }
145
146 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
147 compptr = cinfo->cur_comp_info[ci];
148 dctbl = compptr->dc_tbl_no;
149 actbl = compptr->ac_tbl_no;
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000150 if (gather_statistics) {
151#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000152 /* Check for invalid table indexes */
153 /* (make_c_derived_tbl does this in the other path) */
154 if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
155 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
156 if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
157 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000158 /* Allocate and zero the statistics tables */
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000159 /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000160 if (entropy->dc_count_ptrs[dctbl] == NULL)
161 entropy->dc_count_ptrs[dctbl] = (long *)
162 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
163 257 * SIZEOF(long));
164 MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
165 if (entropy->ac_count_ptrs[actbl] == NULL)
166 entropy->ac_count_ptrs[actbl] = (long *)
167 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
168 257 * SIZEOF(long));
169 MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
170#endif
171 } else {
172 /* Compute derived values for Huffman tables */
173 /* We may do this more than once for a table, but it's not expensive */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000174 jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000175 & entropy->dc_derived_tbls[dctbl]);
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000176 jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000177 & entropy->ac_derived_tbls[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000178 }
179 /* Initialize DC predictions to 0 */
180 entropy->saved.last_dc_val[ci] = 0;
181 }
182
183 /* Initialize bit buffer to empty */
DRC8443e522009-07-30 08:35:06 +0000184
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000185 entropy->saved.put_buffer = 0;
186 entropy->saved.put_bits = 0;
187
188 /* Initialize restart stuff */
189 entropy->restarts_to_go = cinfo->restart_interval;
190 entropy->next_restart_num = 0;
191}
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000192
193
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000194/*
195 * Compute the derived values for a Huffman table.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000196 * This routine also performs some validation checks on the table.
197 *
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000198 * Note this is also used by jcphuff.c.
199 */
200
Thomas G. Lane489583f1996-02-07 00:00:00 +0000201GLOBAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000202jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000203 c_derived_tbl ** pdtbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000204{
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000205 JHUFF_TBL *htbl;
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000206 c_derived_tbl *dtbl;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000207 int p, i, l, lastp, si, maxsymbol;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000208 char huffsize[257];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000209 unsigned int huffcode[257];
210 unsigned int code;
211
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000212 /* Note that huffsize[] and huffcode[] are filled in code-length order,
213 * paralleling the order of the symbols themselves in htbl->huffval[].
214 */
215
216 /* Find the input Huffman table */
217 if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
218 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
219 htbl =
220 isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
221 if (htbl == NULL)
222 ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
223
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000224 /* Allocate a workspace if we haven't already done so. */
225 if (*pdtbl == NULL)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000226 *pdtbl = (c_derived_tbl *)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000227 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000228 SIZEOF(c_derived_tbl));
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000229 dtbl = *pdtbl;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000230
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000231 /* Figure C.1: make table of Huffman code length for each symbol */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000232
233 p = 0;
234 for (l = 1; l <= 16; l++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000235 i = (int) htbl->bits[l];
236 if (i < 0 || p + i > 256) /* protect against table overrun */
237 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
238 while (i--)
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000239 huffsize[p++] = (char) l;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000240 }
241 huffsize[p] = 0;
242 lastp = p;
243
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000244 /* Figure C.2: generate the codes themselves */
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000245 /* We also validate that the counts represent a legal Huffman code tree. */
246
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000247 code = 0;
248 si = huffsize[0];
249 p = 0;
250 while (huffsize[p]) {
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000251 while (((int) huffsize[p]) == si) {
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000252 huffcode[p++] = code;
253 code++;
254 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000255 /* code is now 1 more than the last code used for codelength si; but
256 * it must still fit in si bits, since no code is allowed to be all ones.
257 */
258 if (((INT32) code) >= (((INT32) 1) << si))
259 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000260 code <<= 1;
261 si++;
262 }
263
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000264 /* Figure C.3: generate encoding tables */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000265 /* These are code and size indexed by symbol value */
266
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000267 /* Set all codeless symbols to have code length 0;
268 * this lets us detect duplicate VAL entries here, and later
269 * allows emit_bits to detect any attempt to emit such symbols.
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000270 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000271 MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000272
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000273 /* This is also a convenient place to check for out-of-range
274 * and duplicated VAL entries. We allow 0..255 for AC symbols
275 * but only 0..15 for DC. (We could constrain them further
276 * based on data depth and mode, but this seems enough.)
277 */
278 maxsymbol = isDC ? 15 : 255;
279
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000280 for (p = 0; p < lastp; p++) {
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000281 i = htbl->huffval[p];
282 if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
283 ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
284 dtbl->ehufco[i] = huffcode[p];
285 dtbl->ehufsi[i] = huffsize[p];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000286 }
DRC99313382009-03-12 17:24:27 +0000287
288 if(!jpeg_first_bit_table_init) {
289 for(i = 0; i < 65536; i++) {
290 int bit = 0, val = i;
291 while (val) {val >>= 1; bit++;}
292 jpeg_first_bit_table[i] = bit;
293 }
294 jpeg_first_bit_table_init = 1;
295 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000296}
297
298
299/* Outputting bytes to the file */
300
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000301/* Emit a byte, taking 'action' if must suspend. */
302#define emit_byte(state,val,action) \
303 { *(state)->next_output_byte++ = (JOCTET) (val); \
304 if (--(state)->free_in_buffer == 0) \
305 if (! dump_buffer(state)) \
306 { action; } }
307
308
Thomas G. Lane489583f1996-02-07 00:00:00 +0000309LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000310dump_buffer (working_state * state)
311/* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000312{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000313 struct jpeg_destination_mgr * dest = state->cinfo->dest;
314
DRC86299882009-03-14 01:21:13 +0000315 dest->free_in_buffer = state->free_in_buffer;
316
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000317 if (! (*dest->empty_output_buffer) (state->cinfo))
318 return FALSE;
319 /* After a successful buffer dump, must reset buffer pointers */
320 state->next_output_byte = dest->next_output_byte;
321 state->free_in_buffer = dest->free_in_buffer;
322 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000323}
324
325
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000326/* Outputting bits to the file */
327
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000328/* Only the right 24 bits of put_buffer are used; the valid bits are
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000329 * left-justified in this part. At most 16 bits can be passed to emit_bits
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000330 * in one call, and we never retain more than 7 bits in put_buffer
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000331 * between calls, so 24 bits are sufficient.
332 */
333
DRC99313382009-03-12 17:24:27 +0000334/***************************************************************/
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000335
DRC8443e522009-07-30 08:35:06 +0000336#define EMIT_BYTE() { \
DRCdae44742009-08-06 08:58:48 +0000337 if (0xFF == (*buffer++ = (unsigned char)(put_buffer >> (put_bits -= 8)))) \
DRC8443e522009-07-30 08:35:06 +0000338 *buffer++ = 0; \
339 }
340
341/***************************************************************/
342
DRC99313382009-03-12 17:24:27 +0000343#define DUMP_BITS_(code, size) { \
344 put_bits += size; \
345 put_buffer = (put_buffer << size) | code; \
346 if (put_bits > 7) \
347 while(put_bits > 7) \
DRC8443e522009-07-30 08:35:06 +0000348 EMIT_BYTE() \
DRC99313382009-03-12 17:24:27 +0000349 }
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000350
DRC99313382009-03-12 17:24:27 +0000351/***************************************************************/
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000352
DRC8443e522009-07-30 08:35:06 +0000353#define CHECKBUF15() { \
354 if (put_bits > 15) { \
355 EMIT_BYTE() \
356 EMIT_BYTE() \
357 } \
358}
359
DRC8443e522009-07-30 08:35:06 +0000360#define CHECKBUF47() { \
361 if (put_bits > 47) { \
362 EMIT_BYTE() \
363 EMIT_BYTE() \
364 EMIT_BYTE() \
365 EMIT_BYTE() \
366 EMIT_BYTE() \
367 EMIT_BYTE() \
368 } \
369}
370
DRCdae44742009-08-06 08:58:48 +0000371#define CHECKBUF31() { \
372 if (put_bits > 31) { \
DRC8443e522009-07-30 08:35:06 +0000373 EMIT_BYTE() \
374 EMIT_BYTE() \
375 EMIT_BYTE() \
376 EMIT_BYTE() \
377 } \
378}
379
380/***************************************************************/
381
382#define DUMP_BITS_NOCHECK(code, size) { \
383 put_bits += size; \
384 put_buffer = (put_buffer << size) | code; \
385 }
386
DRC830d5fc2010-04-20 21:13:26 +0000387#if __WORDSIZE==64 || defined(_WIN64)
DRC8443e522009-07-30 08:35:06 +0000388
389#define DUMP_BITS(code, size) { \
DRCdae44742009-08-06 08:58:48 +0000390 CHECKBUF47() \
DRC8443e522009-07-30 08:35:06 +0000391 put_bits += size; \
392 put_buffer = (put_buffer << size) | code; \
393 }
394
395#else
396
DRC99313382009-03-12 17:24:27 +0000397#define DUMP_BITS(code, size) { \
398 put_bits += size; \
399 put_buffer = (put_buffer << size) | code; \
DRC8443e522009-07-30 08:35:06 +0000400 CHECKBUF15() \
DRC99313382009-03-12 17:24:27 +0000401 }
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000402
DRC8443e522009-07-30 08:35:06 +0000403#endif
404
DRC99313382009-03-12 17:24:27 +0000405/***************************************************************/
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000406
DRC99313382009-03-12 17:24:27 +0000407#define DUMP_SINGLE_VALUE(ht, codevalue) { \
408 size = ht->ehufsi[codevalue]; \
409 code = ht->ehufco[codevalue]; \
410 \
411 DUMP_BITS(code, size) \
412 }
413
414/***************************************************************/
415
DRC8443e522009-07-30 08:35:06 +0000416#define DUMP_VALUE_SLOW(ht, codevalue, t, nbits) { \
417 size = ht->ehufsi[codevalue]; \
418 code = ht->ehufco[codevalue]; \
419 t &= ~(-1 << nbits); \
420 DUMP_BITS_NOCHECK(code, size) \
421 CHECKBUF15() \
422 DUMP_BITS_NOCHECK(t, nbits) \
423 CHECKBUF15() \
424 }
425
DRC830d5fc2010-04-20 21:13:26 +0000426#if __WORDSIZE==64 || defined(_WIN64)
DRC8443e522009-07-30 08:35:06 +0000427
DRC99313382009-03-12 17:24:27 +0000428#define DUMP_VALUE(ht, codevalue, t, nbits) { \
429 size = ht->ehufsi[codevalue]; \
430 code = ht->ehufco[codevalue]; \
431 t &= ~(-1 << nbits); \
DRCdae44742009-08-06 08:58:48 +0000432 CHECKBUF31() \
DRC8443e522009-07-30 08:35:06 +0000433 DUMP_BITS_NOCHECK(code, size) \
434 DUMP_BITS_NOCHECK(t, nbits) \
DRC99313382009-03-12 17:24:27 +0000435 }
436
DRC8443e522009-07-30 08:35:06 +0000437#else
438
439#define DUMP_VALUE(ht, codevalue, t, nbits) { \
440 size = ht->ehufsi[codevalue]; \
441 code = ht->ehufco[codevalue]; \
442 t &= ~(-1 << nbits); \
443 DUMP_BITS_NOCHECK(code, size) \
DRCdae44742009-08-06 08:58:48 +0000444 CHECKBUF15() \
DRC8443e522009-07-30 08:35:06 +0000445 DUMP_BITS_NOCHECK(t, nbits) \
446 CHECKBUF15() \
447 }
448
449#endif
450
DRC99313382009-03-12 17:24:27 +0000451/***************************************************************/
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000452
DRC3cba8db2009-03-16 23:58:30 +0000453#define BUFSIZE (DCTSIZE2 * 2)
454
455#define LOAD_BUFFER() { \
456 if (state->free_in_buffer < BUFSIZE) { \
457 localbuf = 1; \
458 buffer = _buffer; \
459 } \
460 else buffer = state->next_output_byte; \
461 }
462
463#define STORE_BUFFER() { \
464 if (localbuf) { \
465 bytes = buffer - _buffer; \
466 buffer = _buffer; \
467 while (bytes > 0) { \
468 bytestocopy = min(bytes, state->free_in_buffer); \
469 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
470 state->next_output_byte += bytestocopy; \
471 buffer += bytestocopy; \
472 state->free_in_buffer -= bytestocopy; \
473 if (state->free_in_buffer == 0) \
474 if (! dump_buffer(state)) return FALSE; \
475 bytes -= bytestocopy; \
476 } \
477 } \
478 else { \
479 state->free_in_buffer -= (buffer - state->next_output_byte); \
480 state->next_output_byte = buffer; \
481 } \
482 }
483
484/***************************************************************/
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000485
Thomas G. Lane489583f1996-02-07 00:00:00 +0000486LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000487flush_bits (working_state * state)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000488{
DRC3cba8db2009-03-16 23:58:30 +0000489 unsigned char _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000490 size_t put_buffer; int put_bits;
491 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000492
DRC99313382009-03-12 17:24:27 +0000493 put_buffer = state->cur.put_buffer;
494 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000495 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000496
497 DUMP_BITS_(0x7F, 7)
498
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000499 state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
500 state->cur.put_bits = 0;
DRC3cba8db2009-03-16 23:58:30 +0000501 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000502
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000503 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000504}
505
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000506/* Encode a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000507
Thomas G. Lane489583f1996-02-07 00:00:00 +0000508LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000509encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000510 c_derived_tbl *dctbl, c_derived_tbl *actbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000511{
DRC99313382009-03-12 17:24:27 +0000512 int temp, temp2;
513 int nbits;
514 int r, sflag, size, code;
DRC3cba8db2009-03-16 23:58:30 +0000515 unsigned char _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000516 size_t put_buffer; int put_bits;
DRC99313382009-03-12 17:24:27 +0000517 int code_0xf0 = actbl->ehufco[0xf0], size_0xf0 = actbl->ehufsi[0xf0];
DRC04899092010-02-26 23:01:19 +0000518 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000519
DRC99313382009-03-12 17:24:27 +0000520 put_buffer = state->cur.put_buffer;
521 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000522 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000523
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000524 /* Encode the DC coefficient difference per section F.1.2.1 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000525
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000526 temp = temp2 = block[0] - last_dc_val;
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000527
DRC99313382009-03-12 17:24:27 +0000528 sflag = temp >> 31;
529 temp -= ((temp + temp) & sflag);
530 temp2 += sflag;
DRC8443e522009-07-30 08:35:06 +0000531 nbits = jpeg_first_bit_table[temp];
532 DUMP_VALUE_SLOW(dctbl, nbits, temp2, nbits)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000533
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000534 /* Encode the AC coefficients per section F.1.2.2 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000535
536 r = 0; /* r = run length of zeros */
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000537
DRC99313382009-03-12 17:24:27 +0000538#define innerloop(order) { \
539 temp2 = *(JCOEF*)((unsigned char*)block + order); \
540 if(temp2 == 0) r++; \
541 else { \
542 temp = (JCOEF)temp2; \
543 sflag = temp >> 31; \
544 temp = (temp ^ sflag) - sflag; \
545 temp2 += sflag; \
DRC8443e522009-07-30 08:35:06 +0000546 nbits = jpeg_first_bit_table[temp]; \
DRCdae44742009-08-06 08:58:48 +0000547 for(; r > 15; r -= 16) DUMP_BITS(code_0xf0, size_0xf0) \
DRC99313382009-03-12 17:24:27 +0000548 sflag = (r << 4) + nbits; \
549 DUMP_VALUE(actbl, sflag, temp2, nbits) \
550 r = 0; \
551 }}
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000552
DRC99313382009-03-12 17:24:27 +0000553 innerloop(2*1); innerloop(2*8); innerloop(2*16); innerloop(2*9);
554 innerloop(2*2); innerloop(2*3); innerloop(2*10); innerloop(2*17);
555 innerloop(2*24); innerloop(2*32); innerloop(2*25); innerloop(2*18);
556 innerloop(2*11); innerloop(2*4); innerloop(2*5); innerloop(2*12);
557 innerloop(2*19); innerloop(2*26); innerloop(2*33); innerloop(2*40);
558 innerloop(2*48); innerloop(2*41); innerloop(2*34); innerloop(2*27);
559 innerloop(2*20); innerloop(2*13); innerloop(2*6); innerloop(2*7);
560 innerloop(2*14); innerloop(2*21); innerloop(2*28); innerloop(2*35);
561 innerloop(2*42); innerloop(2*49); innerloop(2*56); innerloop(2*57);
562 innerloop(2*50); innerloop(2*43); innerloop(2*36); innerloop(2*29);
563 innerloop(2*22); innerloop(2*15); innerloop(2*23); innerloop(2*30);
564 innerloop(2*37); innerloop(2*44); innerloop(2*51); innerloop(2*58);
565 innerloop(2*59); innerloop(2*52); innerloop(2*45); innerloop(2*38);
566 innerloop(2*31); innerloop(2*39); innerloop(2*46); innerloop(2*53);
567 innerloop(2*60); innerloop(2*61); innerloop(2*54); innerloop(2*47);
568 innerloop(2*55); innerloop(2*62); innerloop(2*63);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000569
570 /* If the last coef(s) were zero, emit an end-of-block code */
DRC99313382009-03-12 17:24:27 +0000571 if (r > 0) DUMP_SINGLE_VALUE(actbl, 0x0)
572
573 state->cur.put_buffer = put_buffer;
574 state->cur.put_bits = put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000575 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000576
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000577 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000578}
579
580
581/*
582 * Emit a restart marker & resynchronize predictions.
583 */
584
Thomas G. Lane489583f1996-02-07 00:00:00 +0000585LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000586emit_restart (working_state * state, int restart_num)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000587{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000588 int ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000589
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000590 if (! flush_bits(state))
591 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000592
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000593 emit_byte(state, 0xFF, return FALSE);
594 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000595
596 /* Re-initialize DC predictions to 0 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000597 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
598 state->cur.last_dc_val[ci] = 0;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000599
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000600 /* The restart counter is not updated until we successfully write the MCU. */
601
602 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000603}
604
605
606/*
607 * Encode and output one MCU's worth of Huffman-compressed coefficients.
608 */
609
Thomas G. Lane489583f1996-02-07 00:00:00 +0000610METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000611encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000612{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000613 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
614 working_state state;
615 int blkn, ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000616 jpeg_component_info * compptr;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000617
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000618 /* Load up working state */
619 state.next_output_byte = cinfo->dest->next_output_byte;
620 state.free_in_buffer = cinfo->dest->free_in_buffer;
621 ASSIGN_STATE(state.cur, entropy->saved);
622 state.cinfo = cinfo;
623
624 /* Emit restart marker if needed */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000625 if (cinfo->restart_interval) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000626 if (entropy->restarts_to_go == 0)
627 if (! emit_restart(&state, entropy->next_restart_num))
628 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000629 }
630
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000631 /* Encode the MCU data blocks */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000632 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
633 ci = cinfo->MCU_membership[blkn];
634 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000635 if (! encode_one_block(&state,
636 MCU_data[blkn][0], state.cur.last_dc_val[ci],
637 entropy->dc_derived_tbls[compptr->dc_tbl_no],
638 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
639 return FALSE;
640 /* Update last_dc_val */
641 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000642 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000643
644 /* Completed MCU, so update state */
645 cinfo->dest->next_output_byte = state.next_output_byte;
646 cinfo->dest->free_in_buffer = state.free_in_buffer;
647 ASSIGN_STATE(entropy->saved, state.cur);
648
649 /* Update restart-interval state too */
650 if (cinfo->restart_interval) {
651 if (entropy->restarts_to_go == 0) {
652 entropy->restarts_to_go = cinfo->restart_interval;
653 entropy->next_restart_num++;
654 entropy->next_restart_num &= 7;
655 }
656 entropy->restarts_to_go--;
657 }
658
659 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000660}
661
662
663/*
664 * Finish up at the end of a Huffman-compressed scan.
665 */
666
Thomas G. Lane489583f1996-02-07 00:00:00 +0000667METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000668finish_pass_huff (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000669{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000670 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
671 working_state state;
672
673 /* Load up working state ... flush_bits needs it */
674 state.next_output_byte = cinfo->dest->next_output_byte;
675 state.free_in_buffer = cinfo->dest->free_in_buffer;
676 ASSIGN_STATE(state.cur, entropy->saved);
677 state.cinfo = cinfo;
678
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000679 /* Flush out the last data */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000680 if (! flush_bits(&state))
681 ERREXIT(cinfo, JERR_CANT_SUSPEND);
682
683 /* Update state */
684 cinfo->dest->next_output_byte = state.next_output_byte;
685 cinfo->dest->free_in_buffer = state.free_in_buffer;
686 ASSIGN_STATE(entropy->saved, state.cur);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000687}
688
689
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000690/*
691 * Huffman coding optimization.
692 *
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000693 * We first scan the supplied data and count the number of uses of each symbol
694 * that is to be Huffman-coded. (This process MUST agree with the code above.)
695 * Then we build a Huffman coding tree for the observed counts.
696 * Symbols which are not needed at all for the particular image are not
697 * assigned any code, which saves space in the DHT marker as well as in
698 * the compressed data.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000699 */
700
701#ifdef ENTROPY_OPT_SUPPORTED
702
703
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000704/* Process a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000705
Thomas G. Lane489583f1996-02-07 00:00:00 +0000706LOCAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000707htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000708 long dc_counts[], long ac_counts[])
709{
710 register int temp;
711 register int nbits;
712 register int k, r;
713
714 /* Encode the DC coefficient difference per section F.1.2.1 */
715
716 temp = block[0] - last_dc_val;
717 if (temp < 0)
718 temp = -temp;
719
720 /* Find the number of bits needed for the magnitude of the coefficient */
721 nbits = 0;
722 while (temp) {
723 nbits++;
724 temp >>= 1;
725 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000726 /* Check for out-of-range coefficient values.
727 * Since we're encoding a difference, the range limit is twice as much.
728 */
729 if (nbits > MAX_COEF_BITS+1)
730 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000731
732 /* Count the Huffman symbol for the number of bits */
733 dc_counts[nbits]++;
734
735 /* Encode the AC coefficients per section F.1.2.2 */
736
737 r = 0; /* r = run length of zeros */
738
739 for (k = 1; k < DCTSIZE2; k++) {
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000740 if ((temp = block[jpeg_natural_order[k]]) == 0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000741 r++;
742 } else {
743 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
744 while (r > 15) {
745 ac_counts[0xF0]++;
746 r -= 16;
747 }
748
749 /* Find the number of bits needed for the magnitude of the coefficient */
750 if (temp < 0)
751 temp = -temp;
752
753 /* Find the number of bits needed for the magnitude of the coefficient */
754 nbits = 1; /* there must be at least one 1 bit */
755 while ((temp >>= 1))
756 nbits++;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000757 /* Check for out-of-range coefficient values */
758 if (nbits > MAX_COEF_BITS)
759 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000760
761 /* Count Huffman symbol for run length / number of bits */
762 ac_counts[(r << 4) + nbits]++;
763
764 r = 0;
765 }
766 }
767
768 /* If the last coef(s) were zero, emit an end-of-block code */
769 if (r > 0)
770 ac_counts[0]++;
771}
772
773
774/*
775 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
776 * No data is actually output, so no suspension return is possible.
777 */
778
Thomas G. Lane489583f1996-02-07 00:00:00 +0000779METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000780encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
781{
782 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
783 int blkn, ci;
784 jpeg_component_info * compptr;
785
786 /* Take care of restart intervals if needed */
787 if (cinfo->restart_interval) {
788 if (entropy->restarts_to_go == 0) {
789 /* Re-initialize DC predictions to 0 */
790 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
791 entropy->saved.last_dc_val[ci] = 0;
792 /* Update restart state */
793 entropy->restarts_to_go = cinfo->restart_interval;
794 }
795 entropy->restarts_to_go--;
796 }
797
798 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
799 ci = cinfo->MCU_membership[blkn];
800 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000801 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000802 entropy->dc_count_ptrs[compptr->dc_tbl_no],
803 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
804 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
805 }
806
807 return TRUE;
808}
809
810
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000811/*
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000812 * Generate the best Huffman code table for the given counts, fill htbl.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000813 * Note this is also used by jcphuff.c.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000814 *
815 * The JPEG standard requires that no symbol be assigned a codeword of all
816 * one bits (so that padding bits added at the end of a compressed segment
817 * can't look like a valid code). Because of the canonical ordering of
818 * codewords, this just means that there must be an unused slot in the
819 * longest codeword length category. Section K.2 of the JPEG spec suggests
820 * reserving such a slot by pretending that symbol 256 is a valid symbol
821 * with count 1. In theory that's not optimal; giving it count zero but
822 * including it in the symbol set anyway should give a better Huffman code.
823 * But the theoretically better code actually seems to come out worse in
824 * practice, because it produces more all-ones bytes (which incur stuffed
825 * zero bytes in the final file). In any case the difference is tiny.
826 *
827 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
828 * If some symbols have a very small but nonzero probability, the Huffman tree
829 * must be adjusted to meet the code length restriction. We currently use
830 * the adjustment method suggested in JPEG section K.2. This method is *not*
831 * optimal; it may not choose the best possible limited-length code. But
832 * typically only very-low-frequency symbols will be given less-than-optimal
833 * lengths, so the code is almost optimal. Experimental comparisons against
834 * an optimal limited-length-code algorithm indicate that the difference is
835 * microscopic --- usually less than a hundredth of a percent of total size.
836 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000837 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000838
Thomas G. Lane489583f1996-02-07 00:00:00 +0000839GLOBAL(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000840jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000841{
842#define MAX_CLEN 32 /* assumed maximum initial code length */
843 UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000844 int codesize[257]; /* codesize[k] = code length of symbol k */
845 int others[257]; /* next symbol in current branch of tree */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000846 int c1, c2;
847 int p, i, j;
848 long v;
849
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000850 /* This algorithm is explained in section K.2 of the JPEG standard */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000851
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000852 MEMZERO(bits, SIZEOF(bits));
853 MEMZERO(codesize, SIZEOF(codesize));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000854 for (i = 0; i < 257; i++)
855 others[i] = -1; /* init links to empty */
856
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000857 freq[256] = 1; /* make sure 256 has a nonzero count */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000858 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000859 * that no real symbol is given code-value of all ones, because 256
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000860 * will be placed last in the largest codeword category.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000861 */
862
863 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
864
865 for (;;) {
866 /* Find the smallest nonzero frequency, set c1 = its symbol */
867 /* In case of ties, take the larger symbol number */
868 c1 = -1;
869 v = 1000000000L;
870 for (i = 0; i <= 256; i++) {
871 if (freq[i] && freq[i] <= v) {
872 v = freq[i];
873 c1 = i;
874 }
875 }
876
877 /* Find the next smallest nonzero frequency, set c2 = its symbol */
878 /* In case of ties, take the larger symbol number */
879 c2 = -1;
880 v = 1000000000L;
881 for (i = 0; i <= 256; i++) {
882 if (freq[i] && freq[i] <= v && i != c1) {
883 v = freq[i];
884 c2 = i;
885 }
886 }
887
888 /* Done if we've merged everything into one frequency */
889 if (c2 < 0)
890 break;
891
892 /* Else merge the two counts/trees */
893 freq[c1] += freq[c2];
894 freq[c2] = 0;
895
896 /* Increment the codesize of everything in c1's tree branch */
897 codesize[c1]++;
898 while (others[c1] >= 0) {
899 c1 = others[c1];
900 codesize[c1]++;
901 }
902
903 others[c1] = c2; /* chain c2 onto c1's tree branch */
904
905 /* Increment the codesize of everything in c2's tree branch */
906 codesize[c2]++;
907 while (others[c2] >= 0) {
908 c2 = others[c2];
909 codesize[c2]++;
910 }
911 }
912
913 /* Now count the number of symbols of each code length */
914 for (i = 0; i <= 256; i++) {
915 if (codesize[i]) {
916 /* The JPEG standard seems to think that this can't happen, */
917 /* but I'm paranoid... */
918 if (codesize[i] > MAX_CLEN)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000919 ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000920
921 bits[codesize[i]]++;
922 }
923 }
924
925 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
926 * Huffman procedure assigned any such lengths, we must adjust the coding.
927 * Here is what the JPEG spec says about how this next bit works:
928 * Since symbols are paired for the longest Huffman code, the symbols are
929 * removed from this length category two at a time. The prefix for the pair
930 * (which is one bit shorter) is allocated to one of the pair; then,
931 * skipping the BITS entry for that prefix length, a code word from the next
932 * shortest nonzero BITS entry is converted into a prefix for two code words
933 * one bit longer.
934 */
935
936 for (i = MAX_CLEN; i > 16; i--) {
937 while (bits[i] > 0) {
938 j = i - 2; /* find length of new prefix to be used */
939 while (bits[j] == 0)
940 j--;
941
942 bits[i] -= 2; /* remove two symbols */
943 bits[i-1]++; /* one goes in this length */
944 bits[j+1] += 2; /* two new symbols in this length */
945 bits[j]--; /* symbol of this length is now a prefix */
946 }
947 }
948
949 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
950 while (bits[i] == 0) /* find largest codelength still in use */
951 i--;
952 bits[i]--;
953
954 /* Return final symbol counts (only for lengths 0..16) */
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000955 MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000956
957 /* Return a list of the symbols sorted by code length */
958 /* It's not real clear to me why we don't need to consider the codelength
959 * changes made above, but the JPEG spec seems to think this works.
960 */
961 p = 0;
962 for (i = 1; i <= MAX_CLEN; i++) {
963 for (j = 0; j <= 255; j++) {
964 if (codesize[j] == i) {
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000965 htbl->huffval[p] = (UINT8) j;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000966 p++;
967 }
968 }
969 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000970
971 /* Set sent_table FALSE so updated table will be written to JPEG file. */
972 htbl->sent_table = FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000973}
974
975
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000976/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000977 * Finish up a statistics-gathering pass and create the new Huffman tables.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000978 */
979
Thomas G. Lane489583f1996-02-07 00:00:00 +0000980METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000981finish_pass_gather (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000982{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000983 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
984 int ci, dctbl, actbl;
985 jpeg_component_info * compptr;
986 JHUFF_TBL **htblptr;
987 boolean did_dc[NUM_HUFF_TBLS];
988 boolean did_ac[NUM_HUFF_TBLS];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000989
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000990 /* It's important not to apply jpeg_gen_optimal_table more than once
991 * per table, because it clobbers the input frequency counts!
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000992 */
993 MEMZERO(did_dc, SIZEOF(did_dc));
994 MEMZERO(did_ac, SIZEOF(did_ac));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000995
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000996 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
997 compptr = cinfo->cur_comp_info[ci];
998 dctbl = compptr->dc_tbl_no;
999 actbl = compptr->ac_tbl_no;
1000 if (! did_dc[dctbl]) {
1001 htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001002 if (*htblptr == NULL)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001003 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001004 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001005 did_dc[dctbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001006 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001007 if (! did_ac[actbl]) {
1008 htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001009 if (*htblptr == NULL)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001010 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001011 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001012 did_ac[actbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001013 }
1014 }
1015}
1016
1017
1018#endif /* ENTROPY_OPT_SUPPORTED */
1019
1020
1021/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001022 * Module initialization routine for Huffman entropy encoding.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001023 */
1024
Thomas G. Lane489583f1996-02-07 00:00:00 +00001025GLOBAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001026jinit_huff_encoder (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001027{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001028 huff_entropy_ptr entropy;
1029 int i;
1030
1031 entropy = (huff_entropy_ptr)
1032 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1033 SIZEOF(huff_entropy_encoder));
1034 cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
1035 entropy->pub.start_pass = start_pass_huff;
1036
1037 /* Mark tables unallocated */
1038 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1039 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001040#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001041 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001042#endif
1043 }
1044}