blob: b05c8e71a0d7528c0d49b94d78a4e2d2d4383ffa [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];
39int jpeg_first_bit_table_init=0;
40
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
DRCdae44742009-08-06 08:58:48 +0000426int _max=0;
427
DRC830d5fc2010-04-20 21:13:26 +0000428#if __WORDSIZE==64 || defined(_WIN64)
DRC8443e522009-07-30 08:35:06 +0000429
DRC99313382009-03-12 17:24:27 +0000430#define DUMP_VALUE(ht, codevalue, t, nbits) { \
431 size = ht->ehufsi[codevalue]; \
432 code = ht->ehufco[codevalue]; \
433 t &= ~(-1 << nbits); \
DRCdae44742009-08-06 08:58:48 +0000434 CHECKBUF31() \
DRC8443e522009-07-30 08:35:06 +0000435 DUMP_BITS_NOCHECK(code, size) \
436 DUMP_BITS_NOCHECK(t, nbits) \
DRC99313382009-03-12 17:24:27 +0000437 }
438
DRC8443e522009-07-30 08:35:06 +0000439#else
440
441#define DUMP_VALUE(ht, codevalue, t, nbits) { \
442 size = ht->ehufsi[codevalue]; \
443 code = ht->ehufco[codevalue]; \
444 t &= ~(-1 << nbits); \
445 DUMP_BITS_NOCHECK(code, size) \
DRCdae44742009-08-06 08:58:48 +0000446 CHECKBUF15() \
DRC8443e522009-07-30 08:35:06 +0000447 DUMP_BITS_NOCHECK(t, nbits) \
448 CHECKBUF15() \
449 }
450
451#endif
452
DRC99313382009-03-12 17:24:27 +0000453/***************************************************************/
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000454
DRC3cba8db2009-03-16 23:58:30 +0000455#define BUFSIZE (DCTSIZE2 * 2)
456
457#define LOAD_BUFFER() { \
458 if (state->free_in_buffer < BUFSIZE) { \
459 localbuf = 1; \
460 buffer = _buffer; \
461 } \
462 else buffer = state->next_output_byte; \
463 }
464
465#define STORE_BUFFER() { \
466 if (localbuf) { \
467 bytes = buffer - _buffer; \
468 buffer = _buffer; \
469 while (bytes > 0) { \
470 bytestocopy = min(bytes, state->free_in_buffer); \
471 MEMCOPY(state->next_output_byte, buffer, bytestocopy); \
472 state->next_output_byte += bytestocopy; \
473 buffer += bytestocopy; \
474 state->free_in_buffer -= bytestocopy; \
475 if (state->free_in_buffer == 0) \
476 if (! dump_buffer(state)) return FALSE; \
477 bytes -= bytestocopy; \
478 } \
479 } \
480 else { \
481 state->free_in_buffer -= (buffer - state->next_output_byte); \
482 state->next_output_byte = buffer; \
483 } \
484 }
485
486/***************************************************************/
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000487
Thomas G. Lane489583f1996-02-07 00:00:00 +0000488LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000489flush_bits (working_state * state)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000490{
DRC3cba8db2009-03-16 23:58:30 +0000491 unsigned char _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000492 size_t put_buffer; int put_bits;
493 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000494
DRC99313382009-03-12 17:24:27 +0000495 put_buffer = state->cur.put_buffer;
496 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000497 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000498
499 DUMP_BITS_(0x7F, 7)
500
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000501 state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
502 state->cur.put_bits = 0;
DRC3cba8db2009-03-16 23:58:30 +0000503 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000504
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000505 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000506}
507
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000508/* Encode a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000509
Thomas G. Lane489583f1996-02-07 00:00:00 +0000510LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000511encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000512 c_derived_tbl *dctbl, c_derived_tbl *actbl)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000513{
DRC99313382009-03-12 17:24:27 +0000514 int temp, temp2;
515 int nbits;
516 int r, sflag, size, code;
DRC3cba8db2009-03-16 23:58:30 +0000517 unsigned char _buffer[BUFSIZE], *buffer;
DRC04899092010-02-26 23:01:19 +0000518 size_t put_buffer; int put_bits;
DRC99313382009-03-12 17:24:27 +0000519 int code_0xf0 = actbl->ehufco[0xf0], size_0xf0 = actbl->ehufsi[0xf0];
DRC04899092010-02-26 23:01:19 +0000520 size_t bytes, bytestocopy; int localbuf = 0;
DRC99313382009-03-12 17:24:27 +0000521
DRC99313382009-03-12 17:24:27 +0000522 put_buffer = state->cur.put_buffer;
523 put_bits = state->cur.put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000524 LOAD_BUFFER()
DRC99313382009-03-12 17:24:27 +0000525
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000526 /* Encode the DC coefficient difference per section F.1.2.1 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000527
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000528 temp = temp2 = block[0] - last_dc_val;
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000529
DRC99313382009-03-12 17:24:27 +0000530 sflag = temp >> 31;
531 temp -= ((temp + temp) & sflag);
532 temp2 += sflag;
DRC8443e522009-07-30 08:35:06 +0000533 nbits = jpeg_first_bit_table[temp];
534 DUMP_VALUE_SLOW(dctbl, nbits, temp2, nbits)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000535
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000536 /* Encode the AC coefficients per section F.1.2.2 */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000537
538 r = 0; /* r = run length of zeros */
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000539
DRC99313382009-03-12 17:24:27 +0000540#define innerloop(order) { \
541 temp2 = *(JCOEF*)((unsigned char*)block + order); \
542 if(temp2 == 0) r++; \
543 else { \
544 temp = (JCOEF)temp2; \
545 sflag = temp >> 31; \
546 temp = (temp ^ sflag) - sflag; \
547 temp2 += sflag; \
DRC8443e522009-07-30 08:35:06 +0000548 nbits = jpeg_first_bit_table[temp]; \
DRCdae44742009-08-06 08:58:48 +0000549 for(; r > 15; r -= 16) DUMP_BITS(code_0xf0, size_0xf0) \
DRC99313382009-03-12 17:24:27 +0000550 sflag = (r << 4) + nbits; \
551 DUMP_VALUE(actbl, sflag, temp2, nbits) \
552 r = 0; \
553 }}
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000554
DRC99313382009-03-12 17:24:27 +0000555 innerloop(2*1); innerloop(2*8); innerloop(2*16); innerloop(2*9);
556 innerloop(2*2); innerloop(2*3); innerloop(2*10); innerloop(2*17);
557 innerloop(2*24); innerloop(2*32); innerloop(2*25); innerloop(2*18);
558 innerloop(2*11); innerloop(2*4); innerloop(2*5); innerloop(2*12);
559 innerloop(2*19); innerloop(2*26); innerloop(2*33); innerloop(2*40);
560 innerloop(2*48); innerloop(2*41); innerloop(2*34); innerloop(2*27);
561 innerloop(2*20); innerloop(2*13); innerloop(2*6); innerloop(2*7);
562 innerloop(2*14); innerloop(2*21); innerloop(2*28); innerloop(2*35);
563 innerloop(2*42); innerloop(2*49); innerloop(2*56); innerloop(2*57);
564 innerloop(2*50); innerloop(2*43); innerloop(2*36); innerloop(2*29);
565 innerloop(2*22); innerloop(2*15); innerloop(2*23); innerloop(2*30);
566 innerloop(2*37); innerloop(2*44); innerloop(2*51); innerloop(2*58);
567 innerloop(2*59); innerloop(2*52); innerloop(2*45); innerloop(2*38);
568 innerloop(2*31); innerloop(2*39); innerloop(2*46); innerloop(2*53);
569 innerloop(2*60); innerloop(2*61); innerloop(2*54); innerloop(2*47);
570 innerloop(2*55); innerloop(2*62); innerloop(2*63);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000571
572 /* If the last coef(s) were zero, emit an end-of-block code */
DRC99313382009-03-12 17:24:27 +0000573 if (r > 0) DUMP_SINGLE_VALUE(actbl, 0x0)
574
575 state->cur.put_buffer = put_buffer;
576 state->cur.put_bits = put_bits;
DRC3cba8db2009-03-16 23:58:30 +0000577 STORE_BUFFER()
DRC99313382009-03-12 17:24:27 +0000578
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000579 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000580}
581
582
583/*
584 * Emit a restart marker & resynchronize predictions.
585 */
586
Thomas G. Lane489583f1996-02-07 00:00:00 +0000587LOCAL(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000588emit_restart (working_state * state, int restart_num)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000589{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000590 int ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000591
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000592 if (! flush_bits(state))
593 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000594
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000595 emit_byte(state, 0xFF, return FALSE);
596 emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000597
598 /* Re-initialize DC predictions to 0 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000599 for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
600 state->cur.last_dc_val[ci] = 0;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000601
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000602 /* The restart counter is not updated until we successfully write the MCU. */
603
604 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000605}
606
607
608/*
609 * Encode and output one MCU's worth of Huffman-compressed coefficients.
610 */
611
Thomas G. Lane489583f1996-02-07 00:00:00 +0000612METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000613encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000614{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000615 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
616 working_state state;
617 int blkn, ci;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000618 jpeg_component_info * compptr;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000619
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000620 /* Load up working state */
621 state.next_output_byte = cinfo->dest->next_output_byte;
622 state.free_in_buffer = cinfo->dest->free_in_buffer;
623 ASSIGN_STATE(state.cur, entropy->saved);
624 state.cinfo = cinfo;
625
626 /* Emit restart marker if needed */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000627 if (cinfo->restart_interval) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000628 if (entropy->restarts_to_go == 0)
629 if (! emit_restart(&state, entropy->next_restart_num))
630 return FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000631 }
632
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000633 /* Encode the MCU data blocks */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000634 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
635 ci = cinfo->MCU_membership[blkn];
636 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000637 if (! encode_one_block(&state,
638 MCU_data[blkn][0], state.cur.last_dc_val[ci],
639 entropy->dc_derived_tbls[compptr->dc_tbl_no],
640 entropy->ac_derived_tbls[compptr->ac_tbl_no]))
641 return FALSE;
642 /* Update last_dc_val */
643 state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000644 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000645
646 /* Completed MCU, so update state */
647 cinfo->dest->next_output_byte = state.next_output_byte;
648 cinfo->dest->free_in_buffer = state.free_in_buffer;
649 ASSIGN_STATE(entropy->saved, state.cur);
650
651 /* Update restart-interval state too */
652 if (cinfo->restart_interval) {
653 if (entropy->restarts_to_go == 0) {
654 entropy->restarts_to_go = cinfo->restart_interval;
655 entropy->next_restart_num++;
656 entropy->next_restart_num &= 7;
657 }
658 entropy->restarts_to_go--;
659 }
660
661 return TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000662}
663
664
665/*
666 * Finish up at the end of a Huffman-compressed scan.
667 */
668
Thomas G. Lane489583f1996-02-07 00:00:00 +0000669METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000670finish_pass_huff (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000671{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000672 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
673 working_state state;
674
675 /* Load up working state ... flush_bits needs it */
676 state.next_output_byte = cinfo->dest->next_output_byte;
677 state.free_in_buffer = cinfo->dest->free_in_buffer;
678 ASSIGN_STATE(state.cur, entropy->saved);
679 state.cinfo = cinfo;
680
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000681 /* Flush out the last data */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000682 if (! flush_bits(&state))
683 ERREXIT(cinfo, JERR_CANT_SUSPEND);
684
685 /* Update state */
686 cinfo->dest->next_output_byte = state.next_output_byte;
687 cinfo->dest->free_in_buffer = state.free_in_buffer;
688 ASSIGN_STATE(entropy->saved, state.cur);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000689}
690
691
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000692/*
693 * Huffman coding optimization.
694 *
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000695 * We first scan the supplied data and count the number of uses of each symbol
696 * that is to be Huffman-coded. (This process MUST agree with the code above.)
697 * Then we build a Huffman coding tree for the observed counts.
698 * Symbols which are not needed at all for the particular image are not
699 * assigned any code, which saves space in the DHT marker as well as in
700 * the compressed data.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000701 */
702
703#ifdef ENTROPY_OPT_SUPPORTED
704
705
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000706/* Process a single block's worth of coefficients */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000707
Thomas G. Lane489583f1996-02-07 00:00:00 +0000708LOCAL(void)
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000709htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000710 long dc_counts[], long ac_counts[])
711{
712 register int temp;
713 register int nbits;
714 register int k, r;
715
716 /* Encode the DC coefficient difference per section F.1.2.1 */
717
718 temp = block[0] - last_dc_val;
719 if (temp < 0)
720 temp = -temp;
721
722 /* Find the number of bits needed for the magnitude of the coefficient */
723 nbits = 0;
724 while (temp) {
725 nbits++;
726 temp >>= 1;
727 }
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000728 /* Check for out-of-range coefficient values.
729 * Since we're encoding a difference, the range limit is twice as much.
730 */
731 if (nbits > MAX_COEF_BITS+1)
732 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000733
734 /* Count the Huffman symbol for the number of bits */
735 dc_counts[nbits]++;
736
737 /* Encode the AC coefficients per section F.1.2.2 */
738
739 r = 0; /* r = run length of zeros */
740
741 for (k = 1; k < DCTSIZE2; k++) {
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000742 if ((temp = block[jpeg_natural_order[k]]) == 0) {
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000743 r++;
744 } else {
745 /* if run length > 15, must emit special run-length-16 codes (0xF0) */
746 while (r > 15) {
747 ac_counts[0xF0]++;
748 r -= 16;
749 }
750
751 /* Find the number of bits needed for the magnitude of the coefficient */
752 if (temp < 0)
753 temp = -temp;
754
755 /* Find the number of bits needed for the magnitude of the coefficient */
756 nbits = 1; /* there must be at least one 1 bit */
757 while ((temp >>= 1))
758 nbits++;
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000759 /* Check for out-of-range coefficient values */
760 if (nbits > MAX_COEF_BITS)
761 ERREXIT(cinfo, JERR_BAD_DCT_COEF);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000762
763 /* Count Huffman symbol for run length / number of bits */
764 ac_counts[(r << 4) + nbits]++;
765
766 r = 0;
767 }
768 }
769
770 /* If the last coef(s) were zero, emit an end-of-block code */
771 if (r > 0)
772 ac_counts[0]++;
773}
774
775
776/*
777 * Trial-encode one MCU's worth of Huffman-compressed coefficients.
778 * No data is actually output, so no suspension return is possible.
779 */
780
Thomas G. Lane489583f1996-02-07 00:00:00 +0000781METHODDEF(boolean)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000782encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
783{
784 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
785 int blkn, ci;
786 jpeg_component_info * compptr;
787
788 /* Take care of restart intervals if needed */
789 if (cinfo->restart_interval) {
790 if (entropy->restarts_to_go == 0) {
791 /* Re-initialize DC predictions to 0 */
792 for (ci = 0; ci < cinfo->comps_in_scan; ci++)
793 entropy->saved.last_dc_val[ci] = 0;
794 /* Update restart state */
795 entropy->restarts_to_go = cinfo->restart_interval;
796 }
797 entropy->restarts_to_go--;
798 }
799
800 for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
801 ci = cinfo->MCU_membership[blkn];
802 compptr = cinfo->cur_comp_info[ci];
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000803 htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000804 entropy->dc_count_ptrs[compptr->dc_tbl_no],
805 entropy->ac_count_ptrs[compptr->ac_tbl_no]);
806 entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
807 }
808
809 return TRUE;
810}
811
812
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000813/*
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000814 * Generate the best Huffman code table for the given counts, fill htbl.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000815 * Note this is also used by jcphuff.c.
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000816 *
817 * The JPEG standard requires that no symbol be assigned a codeword of all
818 * one bits (so that padding bits added at the end of a compressed segment
819 * can't look like a valid code). Because of the canonical ordering of
820 * codewords, this just means that there must be an unused slot in the
821 * longest codeword length category. Section K.2 of the JPEG spec suggests
822 * reserving such a slot by pretending that symbol 256 is a valid symbol
823 * with count 1. In theory that's not optimal; giving it count zero but
824 * including it in the symbol set anyway should give a better Huffman code.
825 * But the theoretically better code actually seems to come out worse in
826 * practice, because it produces more all-ones bytes (which incur stuffed
827 * zero bytes in the final file). In any case the difference is tiny.
828 *
829 * The JPEG standard requires Huffman codes to be no more than 16 bits long.
830 * If some symbols have a very small but nonzero probability, the Huffman tree
831 * must be adjusted to meet the code length restriction. We currently use
832 * the adjustment method suggested in JPEG section K.2. This method is *not*
833 * optimal; it may not choose the best possible limited-length code. But
834 * typically only very-low-frequency symbols will be given less-than-optimal
835 * lengths, so the code is almost optimal. Experimental comparisons against
836 * an optimal limited-length-code algorithm indicate that the difference is
837 * microscopic --- usually less than a hundredth of a percent of total size.
838 * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000839 */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000840
Thomas G. Lane489583f1996-02-07 00:00:00 +0000841GLOBAL(void)
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000842jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000843{
844#define MAX_CLEN 32 /* assumed maximum initial code length */
845 UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000846 int codesize[257]; /* codesize[k] = code length of symbol k */
847 int others[257]; /* next symbol in current branch of tree */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000848 int c1, c2;
849 int p, i, j;
850 long v;
851
Thomas G. Lane4a6b7301992-03-17 00:00:00 +0000852 /* This algorithm is explained in section K.2 of the JPEG standard */
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000853
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000854 MEMZERO(bits, SIZEOF(bits));
855 MEMZERO(codesize, SIZEOF(codesize));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000856 for (i = 0; i < 257; i++)
857 others[i] = -1; /* init links to empty */
858
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000859 freq[256] = 1; /* make sure 256 has a nonzero count */
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000860 /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000861 * that no real symbol is given code-value of all ones, because 256
Thomas G. Lane5ead57a1998-03-27 00:00:00 +0000862 * will be placed last in the largest codeword category.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000863 */
864
865 /* Huffman's basic algorithm to assign optimal code lengths to symbols */
866
867 for (;;) {
868 /* Find the smallest nonzero frequency, set c1 = its symbol */
869 /* In case of ties, take the larger symbol number */
870 c1 = -1;
871 v = 1000000000L;
872 for (i = 0; i <= 256; i++) {
873 if (freq[i] && freq[i] <= v) {
874 v = freq[i];
875 c1 = i;
876 }
877 }
878
879 /* Find the next smallest nonzero frequency, set c2 = its symbol */
880 /* In case of ties, take the larger symbol number */
881 c2 = -1;
882 v = 1000000000L;
883 for (i = 0; i <= 256; i++) {
884 if (freq[i] && freq[i] <= v && i != c1) {
885 v = freq[i];
886 c2 = i;
887 }
888 }
889
890 /* Done if we've merged everything into one frequency */
891 if (c2 < 0)
892 break;
893
894 /* Else merge the two counts/trees */
895 freq[c1] += freq[c2];
896 freq[c2] = 0;
897
898 /* Increment the codesize of everything in c1's tree branch */
899 codesize[c1]++;
900 while (others[c1] >= 0) {
901 c1 = others[c1];
902 codesize[c1]++;
903 }
904
905 others[c1] = c2; /* chain c2 onto c1's tree branch */
906
907 /* Increment the codesize of everything in c2's tree branch */
908 codesize[c2]++;
909 while (others[c2] >= 0) {
910 c2 = others[c2];
911 codesize[c2]++;
912 }
913 }
914
915 /* Now count the number of symbols of each code length */
916 for (i = 0; i <= 256; i++) {
917 if (codesize[i]) {
918 /* The JPEG standard seems to think that this can't happen, */
919 /* but I'm paranoid... */
920 if (codesize[i] > MAX_CLEN)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000921 ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000922
923 bits[codesize[i]]++;
924 }
925 }
926
927 /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
928 * Huffman procedure assigned any such lengths, we must adjust the coding.
929 * Here is what the JPEG spec says about how this next bit works:
930 * Since symbols are paired for the longest Huffman code, the symbols are
931 * removed from this length category two at a time. The prefix for the pair
932 * (which is one bit shorter) is allocated to one of the pair; then,
933 * skipping the BITS entry for that prefix length, a code word from the next
934 * shortest nonzero BITS entry is converted into a prefix for two code words
935 * one bit longer.
936 */
937
938 for (i = MAX_CLEN; i > 16; i--) {
939 while (bits[i] > 0) {
940 j = i - 2; /* find length of new prefix to be used */
941 while (bits[j] == 0)
942 j--;
943
944 bits[i] -= 2; /* remove two symbols */
945 bits[i-1]++; /* one goes in this length */
946 bits[j+1] += 2; /* two new symbols in this length */
947 bits[j]--; /* symbol of this length is now a prefix */
948 }
949 }
950
951 /* Remove the count for the pseudo-symbol 256 from the largest codelength */
952 while (bits[i] == 0) /* find largest codelength still in use */
953 i--;
954 bits[i]--;
955
956 /* Return final symbol counts (only for lengths 0..16) */
Thomas G. Lane88aeed41992-12-10 00:00:00 +0000957 MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000958
959 /* Return a list of the symbols sorted by code length */
960 /* It's not real clear to me why we don't need to consider the codelength
961 * changes made above, but the JPEG spec seems to think this works.
962 */
963 p = 0;
964 for (i = 1; i <= MAX_CLEN; i++) {
965 for (j = 0; j <= 255; j++) {
966 if (codesize[j] == i) {
Thomas G. Lanebd543f01991-12-13 00:00:00 +0000967 htbl->huffval[p] = (UINT8) j;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000968 p++;
969 }
970 }
971 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000972
973 /* Set sent_table FALSE so updated table will be written to JPEG file. */
974 htbl->sent_table = FALSE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000975}
976
977
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000978/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000979 * Finish up a statistics-gathering pass and create the new Huffman tables.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000980 */
981
Thomas G. Lane489583f1996-02-07 00:00:00 +0000982METHODDEF(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000983finish_pass_gather (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000984{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000985 huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
986 int ci, dctbl, actbl;
987 jpeg_component_info * compptr;
988 JHUFF_TBL **htblptr;
989 boolean did_dc[NUM_HUFF_TBLS];
990 boolean did_ac[NUM_HUFF_TBLS];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000991
Thomas G. Lanebc79e061995-08-02 00:00:00 +0000992 /* It's important not to apply jpeg_gen_optimal_table more than once
993 * per table, because it clobbers the input frequency counts!
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000994 */
995 MEMZERO(did_dc, SIZEOF(did_dc));
996 MEMZERO(did_ac, SIZEOF(did_ac));
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +0000997
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +0000998 for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
999 compptr = cinfo->cur_comp_info[ci];
1000 dctbl = compptr->dc_tbl_no;
1001 actbl = compptr->ac_tbl_no;
1002 if (! did_dc[dctbl]) {
1003 htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001004 if (*htblptr == NULL)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001005 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001006 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001007 did_dc[dctbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001008 }
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001009 if (! did_ac[actbl]) {
1010 htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001011 if (*htblptr == NULL)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001012 *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
Thomas G. Lanebc79e061995-08-02 00:00:00 +00001013 jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001014 did_ac[actbl] = TRUE;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001015 }
1016 }
1017}
1018
1019
1020#endif /* ENTROPY_OPT_SUPPORTED */
1021
1022
1023/*
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001024 * Module initialization routine for Huffman entropy encoding.
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001025 */
1026
Thomas G. Lane489583f1996-02-07 00:00:00 +00001027GLOBAL(void)
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001028jinit_huff_encoder (j_compress_ptr cinfo)
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001029{
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001030 huff_entropy_ptr entropy;
1031 int i;
1032
1033 entropy = (huff_entropy_ptr)
1034 (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
1035 SIZEOF(huff_entropy_encoder));
1036 cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
1037 entropy->pub.start_pass = start_pass_huff;
1038
1039 /* Mark tables unallocated */
1040 for (i = 0; i < NUM_HUFF_TBLS; i++) {
1041 entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001042#ifdef ENTROPY_OPT_SUPPORTED
Thomas G. Lane36a4ccc1994-09-24 00:00:00 +00001043 entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
Thomas G. Lane2cbeb8a1991-10-07 00:00:00 +00001044#endif
1045 }
1046}